blob: 1991f382f38cc0f9ae880ededa1b937c361d8429 [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 Moolenaara10ae5e2018-05-11 20:48:29 +020041 * - Win32: Termdebug doesn't work, because gdb does not support mi2. This
42 * plugin: https://github.com/cpiger/NeoDebug runs gdb as a job, redirecting
43 * input and output. Command I/O is in gdb window.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020044 * - Win32: Redirecting input does not work, half of Test_terminal_redir_file()
Bram Moolenaar802bfb12018-04-15 17:28:13 +020045 * is disabled.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020046 * - Win32: Redirecting output works but includes escape sequences.
47 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
48 * redirection.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +020049 * - When the job only outputs lines, we could handle resizing the terminal
50 * better: store lines separated by line breaks, instead of screen lines,
51 * then when the window is resized redraw those lines.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020052 * - Redrawing is slow with Athena and Motif. (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020053 * - For the GUI fill termios with default values, perhaps like pangoterm:
54 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020055 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020057 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
58 * "run". Everything else works, including communication channel. Not
59 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 */
61
62#include "vim.h"
63
64#if defined(FEAT_TERMINAL) || defined(PROTO)
65
66#ifndef MIN
67# define MIN(x,y) ((x) < (y) ? (x) : (y))
68#endif
69#ifndef MAX
70# define MAX(x,y) ((x) > (y) ? (x) : (y))
71#endif
72
73#include "libvterm/include/vterm.h"
74
75/* This is VTermScreenCell without the characters, thus much smaller. */
76typedef struct {
77 VTermScreenCellAttrs attrs;
78 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010079 VTermColor fg;
80 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020081} cellattr_T;
82
83typedef struct sb_line_S {
84 int sb_cols; /* can differ per line */
85 cellattr_T *sb_cells; /* allocated */
86 cellattr_T sb_fill_attr; /* for short line */
87} sb_line_T;
88
89/* typedef term_T in structs.h */
90struct terminal_S {
91 term_T *tl_next;
92
93 VTerm *tl_vterm;
94 job_T *tl_job;
95 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010096#if defined(FEAT_GUI)
97 int tl_system; /* when non-zero used for :!cmd output */
98 int tl_toprow; /* row with first line of system terminal */
99#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200100
101 /* Set when setting the size of a vterm, reset after redrawing. */
102 int tl_vterm_size_changed;
103
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200104 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
105 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200106 int tl_channel_recently_closed; // still need to handle tl_finish
107
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100108 int tl_finish;
109#define TL_FINISH_UNSET NUL
110#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
111#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
112#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113 char_u *tl_opencmd;
114 char_u *tl_eof_chars;
115
116#ifdef WIN3264
117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
120 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200121#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100122#if defined(FEAT_SESSION)
123 char_u *tl_command;
124#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100125 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200126
127 /* last known vterm size */
128 int tl_rows;
129 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
131 char_u *tl_title; /* NULL or allocated */
132 char_u *tl_status_text; /* NULL or allocated */
133
134 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200135 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200137 int tl_dirty_snapshot; /* text updated after making snapshot */
138#ifdef FEAT_TIMERS
139 int tl_timer_set;
140 proftime_T tl_timer_due;
141#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200142 int tl_postponed_scroll; /* to be scrolled up */
143
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200144 garray_T tl_scrollback;
145 int tl_scrollback_scrolled;
146 cellattr_T tl_default_color;
147
Bram Moolenaard96ff162018-02-18 22:13:29 +0100148 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
149 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 VTermPos tl_cursor_pos;
152 int tl_cursor_visible;
153 int tl_cursor_blink;
154 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
155 char_u *tl_cursor_color; /* NULL or allocated */
156
157 int tl_using_altscreen;
158};
159
160#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
161#define TMODE_LOOP 2 /* CTRL-W N used */
162
163/*
164 * List of all active terminals.
165 */
166static term_T *first_term = NULL;
167
168/* Terminal active in terminal_loop(). */
169static term_T *in_terminal_loop = NULL;
170
171#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
172#define KEY_BUF_LEN 200
173
174/*
175 * Functions with separate implementation for MS-Windows and Unix-like systems.
176 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200177static 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 +0200178static int create_pty_only(term_T *term, jobopt_T *opt);
179static void term_report_winsize(term_T *term, int rows, int cols);
180static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100181#ifdef FEAT_GUI
182static void update_system_term(term_T *term);
183#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200184
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100185/* The character that we know (or assume) that the terminal expects for the
186 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100189/* "Terminal" highlight group colors. */
190static int term_default_cterm_fg = -1;
191static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200192
Bram Moolenaard317b382018-02-08 22:33:31 +0100193/* Store the last set and the desired cursor properties, so that we only update
194 * them when needed. Doing it unnecessary may result in flicker. */
195static char_u *last_set_cursor_color = (char_u *)"";
196static char_u *desired_cursor_color = (char_u *)"";
197static int last_set_cursor_shape = -1;
198static int desired_cursor_shape = -1;
199static int last_set_cursor_blink = -1;
200static int desired_cursor_blink = -1;
201
202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203/**************************************
204 * 1. Generic code for all systems.
205 */
206
207/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200208 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200209 * current window.
210 * Sets "rows" and/or "cols" to zero when it should follow the window size.
211 * Return TRUE if the size is the minimum size: "24*80".
212 */
213 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200214parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200215{
216 int minsize = FALSE;
217
218 *rows = 0;
219 *cols = 0;
220
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200221 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200222 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200223 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200224
225 /* Syntax of value was already checked when it's set. */
226 if (p == NULL)
227 {
228 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200229 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200230 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200231 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200232 *cols = atoi((char *)p + 1);
233 }
234 return minsize;
235}
236
237/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200238 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200239 */
240 static void
241set_term_and_win_size(term_T *term)
242{
Bram Moolenaar13568252018-03-16 20:46:58 +0100243#ifdef FEAT_GUI
244 if (term->tl_system)
245 {
246 /* Use the whole screen for the system command. However, it will start
247 * at the command line and scroll up as needed, using tl_toprow. */
248 term->tl_rows = Rows;
249 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200250 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100251 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100252#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200253 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200254 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200255 if (term->tl_rows != 0)
256 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
257 if (term->tl_cols != 0)
258 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200259 }
260 if (term->tl_rows == 0)
261 term->tl_rows = curwin->w_height;
262 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200263 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200264 if (term->tl_cols == 0)
265 term->tl_cols = curwin->w_width;
266 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200267 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268}
269
270/*
271 * Initialize job options for a terminal job.
272 * Caller may overrule some of them.
273 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100274 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275init_job_options(jobopt_T *opt)
276{
277 clear_job_options(opt);
278
279 opt->jo_mode = MODE_RAW;
280 opt->jo_out_mode = MODE_RAW;
281 opt->jo_err_mode = MODE_RAW;
282 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
283}
284
285/*
286 * Set job options mandatory for a terminal job.
287 */
288 static void
289setup_job_options(jobopt_T *opt, int rows, int cols)
290{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200291#ifndef WIN3264
292 /* Win32: Redirecting the job output won't work, thus always connect stdout
293 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200294 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200295#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 {
297 /* Connect stdout to the terminal. */
298 opt->jo_io[PART_OUT] = JIO_BUFFER;
299 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
300 opt->jo_modifiable[PART_OUT] = 0;
301 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
302 }
303
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200304#ifndef WIN3264
305 /* Win32: Redirecting the job output won't work, thus always connect stderr
306 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200307 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200308#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200309 {
310 /* Connect stderr to the terminal. */
311 opt->jo_io[PART_ERR] = JIO_BUFFER;
312 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
313 opt->jo_modifiable[PART_ERR] = 0;
314 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
315 }
316
317 opt->jo_pty = TRUE;
318 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
319 opt->jo_term_rows = rows;
320 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
321 opt->jo_term_cols = cols;
322}
323
324/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100325 * Close a terminal buffer (and its window). Used when creating the terminal
326 * fails.
327 */
328 static void
329term_close_buffer(buf_T *buf, buf_T *old_curbuf)
330{
331 free_terminal(buf);
332 if (old_curbuf != NULL)
333 {
334 --curbuf->b_nwindows;
335 curbuf = old_curbuf;
336 curwin->w_buffer = curbuf;
337 ++curbuf->b_nwindows;
338 }
339
340 /* Wiping out the buffer will also close the window and call
341 * free_terminal(). */
342 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
343}
344
345/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100347 * Use either "argvar" or "argv", the other must be NULL.
348 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
349 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200350 * Returns NULL when failed.
351 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100352 buf_T *
353term_start(
354 typval_T *argvar,
355 char **argv,
356 jobopt_T *opt,
357 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200358{
359 exarg_T split_ea;
360 win_T *old_curwin = curwin;
361 term_T *term;
362 buf_T *old_curbuf = NULL;
363 int res;
364 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100365 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367
368 if (check_restricted() || check_secure())
369 return NULL;
370
371 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
372 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
373 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
374 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
375 {
376 EMSG(_(e_invarg));
377 return NULL;
378 }
379
380 term = (term_T *)alloc_clear(sizeof(term_T));
381 if (term == NULL)
382 return NULL;
383 term->tl_dirty_row_end = MAX_ROW;
384 term->tl_cursor_visible = TRUE;
385 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
386 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100387#ifdef FEAT_GUI
388 term->tl_system = (flags & TERM_START_SYSTEM);
389#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200390 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
391
392 vim_memset(&split_ea, 0, sizeof(split_ea));
393 if (opt->jo_curwin)
394 {
395 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100396 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 {
398 no_write_message();
399 vim_free(term);
400 return NULL;
401 }
402 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100403 ECMD_HIDE
404 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
405 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200406 {
407 vim_free(term);
408 return NULL;
409 }
410 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100411 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200412 {
413 buf_T *buf;
414
415 /* Create a new buffer without a window. Make it the current buffer for
416 * a moment to be able to do the initialisations. */
417 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
418 BLN_NEW | BLN_LISTED);
419 if (buf == NULL || ml_open(buf) == FAIL)
420 {
421 vim_free(term);
422 return NULL;
423 }
424 old_curbuf = curbuf;
425 --curbuf->b_nwindows;
426 curbuf = buf;
427 curwin->w_buffer = buf;
428 ++curbuf->b_nwindows;
429 }
430 else
431 {
432 /* Open a new window or tab. */
433 split_ea.cmdidx = CMD_new;
434 split_ea.cmd = (char_u *)"new";
435 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100436 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 {
438 split_ea.line2 = opt->jo_term_rows;
439 split_ea.addr_count = 1;
440 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100441 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442 {
443 split_ea.line2 = opt->jo_term_cols;
444 split_ea.addr_count = 1;
445 }
446
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100447 if (vertical)
448 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 ex_splitview(&split_ea);
450 if (curwin == old_curwin)
451 {
452 /* split failed */
453 vim_free(term);
454 return NULL;
455 }
456 }
457 term->tl_buffer = curbuf;
458 curbuf->b_term = term;
459
460 if (!opt->jo_hidden)
461 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100462 /* Only one size was taken care of with :new, do the other one. With
463 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100464 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200465 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100466 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 win_setwidth(opt->jo_term_cols);
468 }
469
470 /* Link the new terminal in the list of active terminals. */
471 term->tl_next = first_term;
472 first_term = term;
473
474 if (opt->jo_term_name != NULL)
475 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100476 else if (argv != NULL)
477 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200478 else
479 {
480 int i;
481 size_t len;
482 char_u *cmd, *p;
483
484 if (argvar->v_type == VAR_STRING)
485 {
486 cmd = argvar->vval.v_string;
487 if (cmd == NULL)
488 cmd = (char_u *)"";
489 else if (STRCMP(cmd, "NONE") == 0)
490 cmd = (char_u *)"pty";
491 }
492 else if (argvar->v_type != VAR_LIST
493 || argvar->vval.v_list == NULL
494 || argvar->vval.v_list->lv_len < 1
495 || (cmd = get_tv_string_chk(
496 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
497 cmd = (char_u*)"";
498
499 len = STRLEN(cmd) + 10;
500 p = alloc((int)len);
501
502 for (i = 0; p != NULL; ++i)
503 {
504 /* Prepend a ! to the command name to avoid the buffer name equals
505 * the executable, otherwise ":w!" would overwrite it. */
506 if (i == 0)
507 vim_snprintf((char *)p, len, "!%s", cmd);
508 else
509 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
510 if (buflist_findname(p) == NULL)
511 {
512 vim_free(curbuf->b_ffname);
513 curbuf->b_ffname = p;
514 break;
515 }
516 }
517 }
518 curbuf->b_fname = curbuf->b_ffname;
519
520 if (opt->jo_term_opencmd != NULL)
521 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
522
523 if (opt->jo_eof_chars != NULL)
524 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
525
526 set_string_option_direct((char_u *)"buftype", -1,
527 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
528
529 /* Mark the buffer as not modifiable. It can only be made modifiable after
530 * the job finished. */
531 curbuf->b_p_ma = FALSE;
532
533 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200534#ifdef WIN3264
535 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
536#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200537 setup_job_options(opt, term->tl_rows, term->tl_cols);
538
Bram Moolenaar13568252018-03-16 20:46:58 +0100539 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100540 return curbuf;
541
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100542#if defined(FEAT_SESSION)
543 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100544 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100545 {
546 term->tl_command = vim_strsave((char_u *)"NONE");
547 }
548 else if (argvar->v_type == VAR_STRING)
549 {
550 char_u *cmd = argvar->vval.v_string;
551
552 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
553 term->tl_command = vim_strsave(cmd);
554 }
555 else if (argvar->v_type == VAR_LIST
556 && argvar->vval.v_list != NULL
557 && argvar->vval.v_list->lv_len > 0)
558 {
559 garray_T ga;
560 listitem_T *item;
561
562 ga_init2(&ga, 1, 100);
563 for (item = argvar->vval.v_list->lv_first;
564 item != NULL; item = item->li_next)
565 {
566 char_u *s = get_tv_string_chk(&item->li_tv);
567 char_u *p;
568
569 if (s == NULL)
570 break;
571 p = vim_strsave_fnameescape(s, FALSE);
572 if (p == NULL)
573 break;
574 ga_concat(&ga, p);
575 vim_free(p);
576 ga_append(&ga, ' ');
577 }
578 if (item == NULL)
579 {
580 ga_append(&ga, NUL);
581 term->tl_command = ga.ga_data;
582 }
583 else
584 ga_clear(&ga);
585 }
586#endif
587
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100588 if (opt->jo_term_kill != NULL)
589 {
590 char_u *p = skiptowhite(opt->jo_term_kill);
591
592 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
593 }
594
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200595 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100596 if (argv == NULL
597 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598 && argvar->vval.v_string != NULL
599 && STRCMP(argvar->vval.v_string, "NONE") == 0)
600 res = create_pty_only(term, opt);
601 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200602 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603
604 newbuf = curbuf;
605 if (res == OK)
606 {
607 /* Get and remember the size we ended up with. Update the pty. */
608 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
609 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100610#ifdef FEAT_GUI
611 if (term->tl_system)
612 {
613 /* display first line below typed command */
614 term->tl_toprow = msg_row + 1;
615 term->tl_dirty_row_end = 0;
616 }
617#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200618
619 /* Make sure we don't get stuck on sending keys to the job, it leads to
620 * a deadlock if the job is waiting for Vim to read. */
621 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
622
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200623 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624 {
625 --curbuf->b_nwindows;
626 curbuf = old_curbuf;
627 curwin->w_buffer = curbuf;
628 ++curbuf->b_nwindows;
629 }
630 }
631 else
632 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100633 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634 return NULL;
635 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100636
Bram Moolenaar13568252018-03-16 20:46:58 +0100637 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200638 return newbuf;
639}
640
641/*
642 * ":terminal": open a terminal window and execute a job in it.
643 */
644 void
645ex_terminal(exarg_T *eap)
646{
647 typval_T argvar[2];
648 jobopt_T opt;
649 char_u *cmd;
650 char_u *tofree = NULL;
651
652 init_job_options(&opt);
653
654 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100655 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200656 {
657 char_u *p, *ep;
658
659 cmd += 2;
660 p = skiptowhite(cmd);
661 ep = vim_strchr(cmd, '=');
662 if (ep != NULL && ep < p)
663 p = ep;
664
665 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
666 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100667 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
668 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200669 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
670 opt.jo_term_finish = 'o';
671 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
672 opt.jo_curwin = 1;
673 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
674 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100675 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
676 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100677 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
678 && ep != NULL)
679 {
680 opt.jo_set2 |= JO2_TERM_KILL;
681 opt.jo_term_kill = ep + 1;
682 p = skiptowhite(cmd);
683 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200684 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
685 && ep != NULL && isdigit(ep[1]))
686 {
687 opt.jo_set2 |= JO2_TERM_ROWS;
688 opt.jo_term_rows = atoi((char *)ep + 1);
689 p = skiptowhite(cmd);
690 }
691 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
692 && ep != NULL && isdigit(ep[1]))
693 {
694 opt.jo_set2 |= JO2_TERM_COLS;
695 opt.jo_term_cols = atoi((char *)ep + 1);
696 p = skiptowhite(cmd);
697 }
698 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
699 && ep != NULL)
700 {
701 char_u *buf = NULL;
702 char_u *keys;
703
704 p = skiptowhite(cmd);
705 *p = NUL;
706 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
707 opt.jo_set2 |= JO2_EOF_CHARS;
708 opt.jo_eof_chars = vim_strsave(keys);
709 vim_free(buf);
710 *p = ' ';
711 }
712 else
713 {
714 if (*p)
715 *p = NUL;
716 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100717 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 }
719 cmd = skipwhite(p);
720 }
721 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100722 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200723 /* Make a copy of 'shell', an autocommand may change the option. */
724 tofree = cmd = vim_strsave(p_sh);
725
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100726 /* default to close when the shell exits */
727 if (opt.jo_term_finish == NUL)
728 opt.jo_term_finish = 'c';
729 }
730
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200731 if (eap->addr_count > 0)
732 {
733 /* Write lines from current buffer to the job. */
734 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
735 opt.jo_io[PART_IN] = JIO_BUFFER;
736 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
737 opt.jo_in_top = eap->line1;
738 opt.jo_in_bot = eap->line2;
739 }
740
741 argvar[0].v_type = VAR_STRING;
742 argvar[0].vval.v_string = cmd;
743 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100744 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100746
747theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vim_free(opt.jo_eof_chars);
749}
750
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100751#if defined(FEAT_SESSION) || defined(PROTO)
752/*
753 * Write a :terminal command to the session file to restore the terminal in
754 * window "wp".
755 * Return FAIL if writing fails.
756 */
757 int
758term_write_session(FILE *fd, win_T *wp)
759{
760 term_T *term = wp->w_buffer->b_term;
761
762 /* Create the terminal and run the command. This is not without
763 * risk, but let's assume the user only creates a session when this
764 * will be OK. */
765 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
766 term->tl_cols, term->tl_rows) < 0)
767 return FAIL;
768 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
769 return FAIL;
770
771 return put_eol(fd);
772}
773
774/*
775 * Return TRUE if "buf" has a terminal that should be restored.
776 */
777 int
778term_should_restore(buf_T *buf)
779{
780 term_T *term = buf->b_term;
781
782 return term != NULL && (term->tl_command == NULL
783 || STRCMP(term->tl_command, "NONE") != 0);
784}
785#endif
786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787/*
788 * Free the scrollback buffer for "term".
789 */
790 static void
791free_scrollback(term_T *term)
792{
793 int i;
794
795 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
796 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
797 ga_clear(&term->tl_scrollback);
798}
799
800/*
801 * Free a terminal and everything it refers to.
802 * Kills the job if there is one.
803 * Called when wiping out a buffer.
804 */
805 void
806free_terminal(buf_T *buf)
807{
808 term_T *term = buf->b_term;
809 term_T *tp;
810
811 if (term == NULL)
812 return;
813 if (first_term == term)
814 first_term = term->tl_next;
815 else
816 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
817 if (tp->tl_next == term)
818 {
819 tp->tl_next = term->tl_next;
820 break;
821 }
822
823 if (term->tl_job != NULL)
824 {
825 if (term->tl_job->jv_status != JOB_ENDED
826 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100827 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 job_stop(term->tl_job, NULL, "kill");
829 job_unref(term->tl_job);
830 }
831
832 free_scrollback(term);
833
834 term_free_vterm(term);
835 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100836#ifdef FEAT_SESSION
837 vim_free(term->tl_command);
838#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100839 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 vim_free(term->tl_status_text);
841 vim_free(term->tl_opencmd);
842 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200843#ifdef WIN3264
844 if (term->tl_out_fd != NULL)
845 fclose(term->tl_out_fd);
846#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100847 if (desired_cursor_color == term->tl_cursor_color)
848 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200849 vim_free(term->tl_cursor_color);
850 vim_free(term);
851 buf->b_term = NULL;
852 if (in_terminal_loop == term)
853 in_terminal_loop = NULL;
854}
855
856/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100857 * Get the part that is connected to the tty. Normally this is PART_IN, but
858 * when writing buffer lines to the job it can be another. This makes it
859 * possible to do "1,5term vim -".
860 */
861 static ch_part_T
862get_tty_part(term_T *term)
863{
864#ifdef UNIX
865 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
866 int i;
867
868 for (i = 0; i < 3; ++i)
869 {
870 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
871
872 if (isatty(fd))
873 return parts[i];
874 }
875#endif
876 return PART_IN;
877}
878
879/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880 * Write job output "msg[len]" to the vterm.
881 */
882 static void
883term_write_job_output(term_T *term, char_u *msg, size_t len)
884{
885 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100886 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100888 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100890 /* flush vterm buffer when vterm responded to control sequence */
891 if (prevlen != vterm_output_get_buffer_current(vterm))
892 {
893 char buf[KEY_BUF_LEN];
894 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
895
896 if (curlen > 0)
897 channel_send(term->tl_job->jv_channel, get_tty_part(term),
898 (char_u *)buf, (int)curlen, NULL);
899 }
900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901 /* this invokes the damage callbacks */
902 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
903}
904
905 static void
906update_cursor(term_T *term, int redraw)
907{
908 if (term->tl_normal_mode)
909 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100910#ifdef FEAT_GUI
911 if (term->tl_system)
912 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
913 term->tl_cursor_pos.col);
914 else
915#endif
916 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200917 if (redraw)
918 {
919 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
920 cursor_on();
921 out_flush();
922#ifdef FEAT_GUI
923 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100924 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200925 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100926 gui_mch_flush();
927 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200928#endif
929 }
930}
931
932/*
933 * Invoked when "msg" output from a job was received. Write it to the terminal
934 * of "buffer".
935 */
936 void
937write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
938{
939 size_t len = STRLEN(msg);
940 term_T *term = buffer->b_term;
941
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200942#ifdef WIN3264
943 /* Win32: Cannot redirect output of the job, intercept it here and write to
944 * the file. */
945 if (term->tl_out_fd != NULL)
946 {
947 ch_log(channel, "Writing %d bytes to output file", (int)len);
948 fwrite(msg, len, 1, term->tl_out_fd);
949 return;
950 }
951#endif
952
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200953 if (term->tl_vterm == NULL)
954 {
955 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
956 return;
957 }
958 ch_log(channel, "writing %d bytes to terminal", (int)len);
959 term_write_job_output(term, msg, len);
960
Bram Moolenaar13568252018-03-16 20:46:58 +0100961#ifdef FEAT_GUI
962 if (term->tl_system)
963 {
964 /* show system output, scrolling up the screen as needed */
965 update_system_term(term);
966 update_cursor(term, TRUE);
967 }
968 else
969#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200970 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
971 * contents, thus no screen update is needed. */
972 if (!term->tl_normal_mode)
973 {
974 /* TODO: only update once in a while. */
975 ch_log(term->tl_job->jv_channel, "updating screen");
976 if (buffer == curbuf)
977 {
978 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200979 /* update_screen() can be slow, check the terminal wasn't closed
980 * already */
981 if (buffer == curbuf && curbuf->b_term != NULL)
982 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200983 }
984 else
985 redraw_after_callback(TRUE);
986 }
987}
988
989/*
990 * Send a mouse position and click to the vterm
991 */
992 static int
993term_send_mouse(VTerm *vterm, int button, int pressed)
994{
995 VTermModifier mod = VTERM_MOD_NONE;
996
997 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200998 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100999 if (button != 0)
1000 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001001 return TRUE;
1002}
1003
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001004static int enter_mouse_col = -1;
1005static int enter_mouse_row = -1;
1006
1007/*
1008 * Handle a mouse click, drag or release.
1009 * Return TRUE when a mouse event is sent to the terminal.
1010 */
1011 static int
1012term_mouse_click(VTerm *vterm, int key)
1013{
1014#if defined(FEAT_CLIPBOARD)
1015 /* For modeless selection mouse drag and release events are ignored, unless
1016 * they are preceded with a mouse down event */
1017 static int ignore_drag_release = TRUE;
1018 VTermMouseState mouse_state;
1019
1020 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1021 if (mouse_state.flags == 0)
1022 {
1023 /* Terminal is not using the mouse, use modeless selection. */
1024 switch (key)
1025 {
1026 case K_LEFTDRAG:
1027 case K_LEFTRELEASE:
1028 case K_RIGHTDRAG:
1029 case K_RIGHTRELEASE:
1030 /* Ignore drag and release events when the button-down wasn't
1031 * seen before. */
1032 if (ignore_drag_release)
1033 {
1034 int save_mouse_col, save_mouse_row;
1035
1036 if (enter_mouse_col < 0)
1037 break;
1038
1039 /* mouse click in the window gave us focus, handle that
1040 * click now */
1041 save_mouse_col = mouse_col;
1042 save_mouse_row = mouse_row;
1043 mouse_col = enter_mouse_col;
1044 mouse_row = enter_mouse_row;
1045 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1046 mouse_col = save_mouse_col;
1047 mouse_row = save_mouse_row;
1048 }
1049 /* FALLTHROUGH */
1050 case K_LEFTMOUSE:
1051 case K_RIGHTMOUSE:
1052 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1053 ignore_drag_release = TRUE;
1054 else
1055 ignore_drag_release = FALSE;
1056 /* Should we call mouse_has() here? */
1057 if (clip_star.available)
1058 {
1059 int button, is_click, is_drag;
1060
1061 button = get_mouse_button(KEY2TERMCAP1(key),
1062 &is_click, &is_drag);
1063 if (mouse_model_popup() && button == MOUSE_LEFT
1064 && (mod_mask & MOD_MASK_SHIFT))
1065 {
1066 /* Translate shift-left to right button. */
1067 button = MOUSE_RIGHT;
1068 mod_mask &= ~MOD_MASK_SHIFT;
1069 }
1070 clip_modeless(button, is_click, is_drag);
1071 }
1072 break;
1073
1074 case K_MIDDLEMOUSE:
1075 if (clip_star.available)
1076 insert_reg('*', TRUE);
1077 break;
1078 }
1079 enter_mouse_col = -1;
1080 return FALSE;
1081 }
1082#endif
1083 enter_mouse_col = -1;
1084
1085 switch (key)
1086 {
1087 case K_LEFTMOUSE:
1088 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1089 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1090 case K_LEFTRELEASE:
1091 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1092 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1093 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1094 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1095 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1096 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1097 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1098 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1099 }
1100 return TRUE;
1101}
1102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001103/*
1104 * Convert typed key "c" into bytes to send to the job.
1105 * Return the number of bytes in "buf".
1106 */
1107 static int
1108term_convert_key(term_T *term, int c, char *buf)
1109{
1110 VTerm *vterm = term->tl_vterm;
1111 VTermKey key = VTERM_KEY_NONE;
1112 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001113 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001114
1115 switch (c)
1116 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001117 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1118
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001119 /* don't use VTERM_KEY_BACKSPACE, it always
1120 * becomes 0x7f DEL */
1121 case K_BS: c = term_backspace_char; break;
1122
1123 case ESC: key = VTERM_KEY_ESCAPE; break;
1124 case K_DEL: key = VTERM_KEY_DEL; break;
1125 case K_DOWN: key = VTERM_KEY_DOWN; break;
1126 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1127 key = VTERM_KEY_DOWN; break;
1128 case K_END: key = VTERM_KEY_END; break;
1129 case K_S_END: mod = VTERM_MOD_SHIFT;
1130 key = VTERM_KEY_END; break;
1131 case K_C_END: mod = VTERM_MOD_CTRL;
1132 key = VTERM_KEY_END; break;
1133 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1134 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1135 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1136 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1137 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1138 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1139 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1140 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1141 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1142 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1143 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1144 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1145 case K_HOME: key = VTERM_KEY_HOME; break;
1146 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1147 key = VTERM_KEY_HOME; break;
1148 case K_C_HOME: mod = VTERM_MOD_CTRL;
1149 key = VTERM_KEY_HOME; break;
1150 case K_INS: key = VTERM_KEY_INS; break;
1151 case K_K0: key = VTERM_KEY_KP_0; break;
1152 case K_K1: key = VTERM_KEY_KP_1; break;
1153 case K_K2: key = VTERM_KEY_KP_2; break;
1154 case K_K3: key = VTERM_KEY_KP_3; break;
1155 case K_K4: key = VTERM_KEY_KP_4; break;
1156 case K_K5: key = VTERM_KEY_KP_5; break;
1157 case K_K6: key = VTERM_KEY_KP_6; break;
1158 case K_K7: key = VTERM_KEY_KP_7; break;
1159 case K_K8: key = VTERM_KEY_KP_8; break;
1160 case K_K9: key = VTERM_KEY_KP_9; break;
1161 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1162 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1163 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1164 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1165 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1166 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1167 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1168 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1169 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1170 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1171 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1172 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1173 case K_LEFT: key = VTERM_KEY_LEFT; break;
1174 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1175 key = VTERM_KEY_LEFT; break;
1176 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1177 key = VTERM_KEY_LEFT; break;
1178 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1179 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1180 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1181 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1182 key = VTERM_KEY_RIGHT; break;
1183 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1184 key = VTERM_KEY_RIGHT; break;
1185 case K_UP: key = VTERM_KEY_UP; break;
1186 case K_S_UP: mod = VTERM_MOD_SHIFT;
1187 key = VTERM_KEY_UP; break;
1188 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001189 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1190 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001191
Bram Moolenaara42ad572017-11-16 13:08:04 +01001192 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1193 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001194 case K_MOUSELEFT: /* TODO */ return 0;
1195 case K_MOUSERIGHT: /* TODO */ return 0;
1196
1197 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001198 case K_LEFTMOUSE_NM:
1199 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001201 case K_LEFTRELEASE_NM:
1202 case K_MOUSEMOVE:
1203 case K_MIDDLEMOUSE:
1204 case K_MIDDLEDRAG:
1205 case K_MIDDLERELEASE:
1206 case K_RIGHTMOUSE:
1207 case K_RIGHTDRAG:
1208 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1209 return 0;
1210 other = TRUE;
1211 break;
1212
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001213 case K_X1MOUSE: /* TODO */ return 0;
1214 case K_X1DRAG: /* TODO */ return 0;
1215 case K_X1RELEASE: /* TODO */ return 0;
1216 case K_X2MOUSE: /* TODO */ return 0;
1217 case K_X2DRAG: /* TODO */ return 0;
1218 case K_X2RELEASE: /* TODO */ return 0;
1219
1220 case K_IGNORE: return 0;
1221 case K_NOP: return 0;
1222 case K_UNDO: return 0;
1223 case K_HELP: return 0;
1224 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1225 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1226 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1227 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1228 case K_SELECT: return 0;
1229#ifdef FEAT_GUI
1230 case K_VER_SCROLLBAR: return 0;
1231 case K_HOR_SCROLLBAR: return 0;
1232#endif
1233#ifdef FEAT_GUI_TABLINE
1234 case K_TABLINE: return 0;
1235 case K_TABMENU: return 0;
1236#endif
1237#ifdef FEAT_NETBEANS_INTG
1238 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1239#endif
1240#ifdef FEAT_DND
1241 case K_DROP: return 0;
1242#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001243 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001244 case K_PS: vterm_keyboard_start_paste(vterm);
1245 other = TRUE;
1246 break;
1247 case K_PE: vterm_keyboard_end_paste(vterm);
1248 other = TRUE;
1249 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001250 }
1251
1252 /*
1253 * Convert special keys to vterm keys:
1254 * - Write keys to vterm: vterm_keyboard_key()
1255 * - Write output to channel.
1256 * TODO: use mod_mask
1257 */
1258 if (key != VTERM_KEY_NONE)
1259 /* Special key, let vterm convert it. */
1260 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001261 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001262 /* Normal character, let vterm convert it. */
1263 vterm_keyboard_unichar(vterm, c, mod);
1264
1265 /* Read back the converted escape sequence. */
1266 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1267}
1268
1269/*
1270 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001271 * If "check_job_status" is TRUE update the job status.
1272 */
1273 static int
1274term_job_running_check(term_T *term, int check_job_status)
1275{
1276 /* Also consider the job finished when the channel is closed, to avoid a
1277 * race condition when updating the title. */
1278 if (term != NULL
1279 && term->tl_job != NULL
1280 && channel_is_open(term->tl_job->jv_channel))
1281 {
1282 if (check_job_status)
1283 job_status(term->tl_job);
1284 return (term->tl_job->jv_status == JOB_STARTED
1285 || term->tl_job->jv_channel->ch_keep_open);
1286 }
1287 return FALSE;
1288}
1289
1290/*
1291 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 */
1293 int
1294term_job_running(term_T *term)
1295{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001296 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297}
1298
1299/*
1300 * Return TRUE if "term" has an active channel and used ":term NONE".
1301 */
1302 int
1303term_none_open(term_T *term)
1304{
1305 /* Also consider the job finished when the channel is closed, to avoid a
1306 * race condition when updating the title. */
1307 return term != NULL
1308 && term->tl_job != NULL
1309 && channel_is_open(term->tl_job->jv_channel)
1310 && term->tl_job->jv_channel->ch_keep_open;
1311}
1312
1313/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001314 * Used when exiting: kill the job in "buf" if so desired.
1315 * Return OK when the job finished.
1316 * Return FAIL when the job is still running.
1317 */
1318 int
1319term_try_stop_job(buf_T *buf)
1320{
1321 int count;
1322 char *how = (char *)buf->b_term->tl_kill;
1323
1324#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1325 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1326 {
1327 char_u buff[DIALOG_MSG_SIZE];
1328 int ret;
1329
1330 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1331 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1332 if (ret == VIM_YES)
1333 how = "kill";
1334 else if (ret == VIM_CANCEL)
1335 return FAIL;
1336 }
1337#endif
1338 if (how == NULL || *how == NUL)
1339 return FAIL;
1340
1341 job_stop(buf->b_term->tl_job, NULL, how);
1342
1343 /* wait for up to a second for the job to die */
1344 for (count = 0; count < 100; ++count)
1345 {
1346 /* buffer, terminal and job may be cleaned up while waiting */
1347 if (!buf_valid(buf)
1348 || buf->b_term == NULL
1349 || buf->b_term->tl_job == NULL)
1350 return OK;
1351
1352 /* call job_status() to update jv_status */
1353 job_status(buf->b_term->tl_job);
1354 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1355 return OK;
1356 ui_delay(10L, FALSE);
1357 mch_check_messages();
1358 parse_queued_messages();
1359 }
1360 return FAIL;
1361}
1362
1363/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001364 * Add the last line of the scrollback buffer to the buffer in the window.
1365 */
1366 static void
1367add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1368{
1369 buf_T *buf = term->tl_buffer;
1370 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1371 linenr_T lnum = buf->b_ml.ml_line_count;
1372
1373#ifdef WIN3264
1374 if (!enc_utf8 && enc_codepage > 0)
1375 {
1376 WCHAR *ret = NULL;
1377 int length = 0;
1378
1379 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1380 &ret, &length);
1381 if (ret != NULL)
1382 {
1383 WideCharToMultiByte_alloc(enc_codepage, 0,
1384 ret, length, (char **)&text, &len, 0, 0);
1385 vim_free(ret);
1386 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1387 vim_free(text);
1388 }
1389 }
1390 else
1391#endif
1392 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1393 if (empty)
1394 {
1395 /* Delete the empty line that was in the empty buffer. */
1396 curbuf = buf;
1397 ml_delete(1, FALSE);
1398 curbuf = curwin->w_buffer;
1399 }
1400}
1401
1402 static void
1403cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1404{
1405 attr->width = cell->width;
1406 attr->attrs = cell->attrs;
1407 attr->fg = cell->fg;
1408 attr->bg = cell->bg;
1409}
1410
1411 static int
1412equal_celattr(cellattr_T *a, cellattr_T *b)
1413{
1414 /* Comparing the colors should be sufficient. */
1415 return a->fg.red == b->fg.red
1416 && a->fg.green == b->fg.green
1417 && a->fg.blue == b->fg.blue
1418 && a->bg.red == b->bg.red
1419 && a->bg.green == b->bg.green
1420 && a->bg.blue == b->bg.blue;
1421}
1422
Bram Moolenaard96ff162018-02-18 22:13:29 +01001423/*
1424 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1425 * line at this position. Otherwise at the end.
1426 */
1427 static int
1428add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1429{
1430 if (ga_grow(&term->tl_scrollback, 1) == OK)
1431 {
1432 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1433 + term->tl_scrollback.ga_len;
1434
1435 if (lnum > 0)
1436 {
1437 int i;
1438
1439 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1440 {
1441 *line = *(line - 1);
1442 --line;
1443 }
1444 }
1445 line->sb_cols = 0;
1446 line->sb_cells = NULL;
1447 line->sb_fill_attr = *fill_attr;
1448 ++term->tl_scrollback.ga_len;
1449 return OK;
1450 }
1451 return FALSE;
1452}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001453
1454/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001455 * Remove the terminal contents from the scrollback and the buffer.
1456 * Used before adding a new scrollback line or updating the buffer for lines
1457 * displayed in the terminal.
1458 */
1459 static void
1460cleanup_scrollback(term_T *term)
1461{
1462 sb_line_T *line;
1463 garray_T *gap;
1464
1465 gap = &term->tl_scrollback;
1466 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1467 && gap->ga_len > 0)
1468 {
1469 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1470 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1471 vim_free(line->sb_cells);
1472 --gap->ga_len;
1473 }
1474 check_cursor();
1475}
1476
1477/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001478 * Add the current lines of the terminal to scrollback and to the buffer.
1479 * Called after the job has ended and when switching to Terminal-Normal mode.
1480 */
1481 static void
1482move_terminal_to_buffer(term_T *term)
1483{
1484 win_T *wp;
1485 int len;
1486 int lines_skipped = 0;
1487 VTermPos pos;
1488 VTermScreenCell cell;
1489 cellattr_T fill_attr, new_fill_attr;
1490 cellattr_T *p;
1491 VTermScreen *screen;
1492
1493 if (term->tl_vterm == NULL)
1494 return;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001495
1496 /* Nothing to do if the buffer already has the lines and nothing was
1497 * changed. */
1498 if (!term->tl_dirty_snapshot
1499 && curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled)
1500 return;
1501
1502 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1503 "Adding terminal window snapshot to buffer");
1504
1505 /* First remove the lines that were appended before, they might be
1506 * outdated. */
1507 cleanup_scrollback(term);
1508
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001509 screen = vterm_obtain_screen(term->tl_vterm);
1510 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001511 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1512 {
1513 len = 0;
1514 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1515 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1516 && cell.chars[0] != NUL)
1517 {
1518 len = pos.col + 1;
1519 new_fill_attr = term->tl_default_color;
1520 }
1521 else
1522 /* Assume the last attr is the filler attr. */
1523 cell2cellattr(&cell, &new_fill_attr);
1524
1525 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1526 ++lines_skipped;
1527 else
1528 {
1529 while (lines_skipped > 0)
1530 {
1531 /* Line was skipped, add an empty line. */
1532 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001533 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001534 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001535 }
1536
1537 if (len == 0)
1538 p = NULL;
1539 else
1540 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1541 if ((p != NULL || len == 0)
1542 && ga_grow(&term->tl_scrollback, 1) == OK)
1543 {
1544 garray_T ga;
1545 int width;
1546 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1547 + term->tl_scrollback.ga_len;
1548
1549 ga_init2(&ga, 1, 100);
1550 for (pos.col = 0; pos.col < len; pos.col += width)
1551 {
1552 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1553 {
1554 width = 1;
1555 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1556 if (ga_grow(&ga, 1) == OK)
1557 ga.ga_len += utf_char2bytes(' ',
1558 (char_u *)ga.ga_data + ga.ga_len);
1559 }
1560 else
1561 {
1562 width = cell.width;
1563
1564 cell2cellattr(&cell, &p[pos.col]);
1565
1566 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1567 {
1568 int i;
1569 int c;
1570
1571 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1572 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1573 (char_u *)ga.ga_data + ga.ga_len);
1574 }
1575 }
1576 }
1577 line->sb_cols = len;
1578 line->sb_cells = p;
1579 line->sb_fill_attr = new_fill_attr;
1580 fill_attr = new_fill_attr;
1581 ++term->tl_scrollback.ga_len;
1582
1583 if (ga_grow(&ga, 1) == FAIL)
1584 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1585 else
1586 {
1587 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1588 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1589 }
1590 ga_clear(&ga);
1591 }
1592 else
1593 vim_free(p);
1594 }
1595 }
1596
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001597 term->tl_dirty_snapshot = FALSE;
1598#ifdef FEAT_TIMERS
1599 term->tl_timer_set = FALSE;
1600#endif
1601
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001602 /* Obtain the current background color. */
1603 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1604 &term->tl_default_color.fg, &term->tl_default_color.bg);
1605
1606 FOR_ALL_WINDOWS(wp)
1607 {
1608 if (wp->w_buffer == term->tl_buffer)
1609 {
1610 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1611 wp->w_cursor.col = 0;
1612 wp->w_valid = 0;
1613 if (wp->w_cursor.lnum >= wp->w_height)
1614 {
1615 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1616
1617 if (wp->w_topline < min_topline)
1618 wp->w_topline = min_topline;
1619 }
1620 redraw_win_later(wp, NOT_VALID);
1621 }
1622 }
1623}
1624
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001625#if defined(FEAT_TIMERS) || defined(PROTO)
1626/*
1627 * Check if any terminal timer expired. If so, copy text from the terminal to
1628 * the buffer.
1629 * Return the time until the next timer will expire.
1630 */
1631 int
1632term_check_timers(int next_due_arg, proftime_T *now)
1633{
1634 term_T *term;
1635 int next_due = next_due_arg;
1636
1637 for (term = first_term; term != NULL; term = term->tl_next)
1638 {
1639 if (term->tl_timer_set && !term->tl_normal_mode)
1640 {
1641 long this_due = proftime_time_left(&term->tl_timer_due, now);
1642
1643 if (this_due <= 1)
1644 {
1645 term->tl_timer_set = FALSE;
1646 move_terminal_to_buffer(term);
1647 }
1648 else if (next_due == -1 || next_due > this_due)
1649 next_due = this_due;
1650 }
1651 }
1652
1653 return next_due;
1654}
1655#endif
1656
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001657 static void
1658set_terminal_mode(term_T *term, int normal_mode)
1659{
1660 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001661 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001662 if (term->tl_buffer == curbuf)
1663 maketitle();
1664}
1665
1666/*
1667 * Called after the job if finished and Terminal mode is not active:
1668 * Move the vterm contents into the scrollback buffer and free the vterm.
1669 */
1670 static void
1671cleanup_vterm(term_T *term)
1672{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001673 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001674 move_terminal_to_buffer(term);
1675 term_free_vterm(term);
1676 set_terminal_mode(term, FALSE);
1677}
1678
1679/*
1680 * Switch from Terminal-Job mode to Terminal-Normal mode.
1681 * Suspends updating the terminal window.
1682 */
1683 static void
1684term_enter_normal_mode(void)
1685{
1686 term_T *term = curbuf->b_term;
1687
1688 /* Append the current terminal contents to the buffer. */
1689 move_terminal_to_buffer(term);
1690
1691 set_terminal_mode(term, TRUE);
1692
1693 /* Move the window cursor to the position of the cursor in the
1694 * terminal. */
1695 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1696 + term->tl_cursor_pos.row + 1;
1697 check_cursor();
1698 coladvance(term->tl_cursor_pos.col);
1699
1700 /* Display the same lines as in the terminal. */
1701 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1702}
1703
1704/*
1705 * Returns TRUE if the current window contains a terminal and we are in
1706 * Terminal-Normal mode.
1707 */
1708 int
1709term_in_normal_mode(void)
1710{
1711 term_T *term = curbuf->b_term;
1712
1713 return term != NULL && term->tl_normal_mode;
1714}
1715
1716/*
1717 * Switch from Terminal-Normal mode to Terminal-Job mode.
1718 * Restores updating the terminal window.
1719 */
1720 void
1721term_enter_job_mode()
1722{
1723 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724
1725 set_terminal_mode(term, FALSE);
1726
1727 if (term->tl_channel_closed)
1728 cleanup_vterm(term);
1729 redraw_buf_and_status_later(curbuf, NOT_VALID);
1730}
1731
1732/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001733 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 * Note: while waiting a terminal may be closed and freed if the channel is
1735 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 */
1737 static int
1738term_vgetc()
1739{
1740 int c;
1741 int save_State = State;
1742
1743 State = TERMINAL;
1744 got_int = FALSE;
1745#ifdef WIN3264
1746 ctrl_break_was_pressed = FALSE;
1747#endif
1748 c = vgetc();
1749 got_int = FALSE;
1750 State = save_State;
1751 return c;
1752}
1753
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001754static int mouse_was_outside = FALSE;
1755
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001756/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757 * Send keys to terminal.
1758 * Return FAIL when the key needs to be handled in Normal mode.
1759 * Return OK when the key was dropped or sent to the terminal.
1760 */
1761 int
1762send_keys_to_term(term_T *term, int c, int typed)
1763{
1764 char msg[KEY_BUF_LEN];
1765 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001766 int dragging_outside = FALSE;
1767
1768 /* Catch keys that need to be handled as in Normal mode. */
1769 switch (c)
1770 {
1771 case NUL:
1772 case K_ZERO:
1773 if (typed)
1774 stuffcharReadbuff(c);
1775 return FAIL;
1776
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001777 case K_TABLINE:
1778 stuffcharReadbuff(c);
1779 return FAIL;
1780
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001781 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001782 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001783 return FAIL;
1784
1785 case K_LEFTDRAG:
1786 case K_MIDDLEDRAG:
1787 case K_RIGHTDRAG:
1788 case K_X1DRAG:
1789 case K_X2DRAG:
1790 dragging_outside = mouse_was_outside;
1791 /* FALLTHROUGH */
1792 case K_LEFTMOUSE:
1793 case K_LEFTMOUSE_NM:
1794 case K_LEFTRELEASE:
1795 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001796 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001797 case K_MIDDLEMOUSE:
1798 case K_MIDDLERELEASE:
1799 case K_RIGHTMOUSE:
1800 case K_RIGHTRELEASE:
1801 case K_X1MOUSE:
1802 case K_X1RELEASE:
1803 case K_X2MOUSE:
1804 case K_X2RELEASE:
1805
1806 case K_MOUSEUP:
1807 case K_MOUSEDOWN:
1808 case K_MOUSELEFT:
1809 case K_MOUSERIGHT:
1810 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001811 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001812 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001813 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001814 || dragging_outside)
1815 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001816 /* click or scroll outside the current window or on status line
1817 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001818 if (typed)
1819 {
1820 stuffcharReadbuff(c);
1821 mouse_was_outside = TRUE;
1822 }
1823 return FAIL;
1824 }
1825 }
1826 if (typed)
1827 mouse_was_outside = FALSE;
1828
1829 /* Convert the typed key to a sequence of bytes for the job. */
1830 len = term_convert_key(term, c, msg);
1831 if (len > 0)
1832 /* TODO: if FAIL is returned, stop? */
1833 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1834 (char_u *)msg, (int)len, NULL);
1835
1836 return OK;
1837}
1838
1839 static void
1840position_cursor(win_T *wp, VTermPos *pos)
1841{
1842 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1843 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1844 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1845}
1846
1847/*
1848 * Handle CTRL-W "": send register contents to the job.
1849 */
1850 static void
1851term_paste_register(int prev_c UNUSED)
1852{
1853 int c;
1854 list_T *l;
1855 listitem_T *item;
1856 long reglen = 0;
1857 int type;
1858
1859#ifdef FEAT_CMDL_INFO
1860 if (add_to_showcmd(prev_c))
1861 if (add_to_showcmd('"'))
1862 out_flush();
1863#endif
1864 c = term_vgetc();
1865#ifdef FEAT_CMDL_INFO
1866 clear_showcmd();
1867#endif
1868 if (!term_use_loop())
1869 /* job finished while waiting for a character */
1870 return;
1871
1872 /* CTRL-W "= prompt for expression to evaluate. */
1873 if (c == '=' && get_expr_register() != '=')
1874 return;
1875 if (!term_use_loop())
1876 /* job finished while waiting for a character */
1877 return;
1878
1879 l = (list_T *)get_reg_contents(c, GREG_LIST);
1880 if (l != NULL)
1881 {
1882 type = get_reg_type(c, &reglen);
1883 for (item = l->lv_first; item != NULL; item = item->li_next)
1884 {
1885 char_u *s = get_tv_string(&item->li_tv);
1886#ifdef WIN3264
1887 char_u *tmp = s;
1888
1889 if (!enc_utf8 && enc_codepage > 0)
1890 {
1891 WCHAR *ret = NULL;
1892 int length = 0;
1893
1894 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1895 (int)STRLEN(s), &ret, &length);
1896 if (ret != NULL)
1897 {
1898 WideCharToMultiByte_alloc(CP_UTF8, 0,
1899 ret, length, (char **)&s, &length, 0, 0);
1900 vim_free(ret);
1901 }
1902 }
1903#endif
1904 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1905 s, (int)STRLEN(s), NULL);
1906#ifdef WIN3264
1907 if (tmp != s)
1908 vim_free(s);
1909#endif
1910
1911 if (item->li_next != NULL || type == MLINE)
1912 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1913 (char_u *)"\r", 1, NULL);
1914 }
1915 list_free(l);
1916 }
1917}
1918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001919/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001920 * Return TRUE when waiting for a character in the terminal, the cursor of the
1921 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001922 */
1923 int
1924terminal_is_active()
1925{
1926 return in_terminal_loop != NULL;
1927}
1928
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001929#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001930 cursorentry_T *
1931term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1932{
1933 term_T *term = in_terminal_loop;
1934 static cursorentry_T entry;
1935
1936 vim_memset(&entry, 0, sizeof(entry));
1937 entry.shape = entry.mshape =
1938 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1939 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1940 SHAPE_BLOCK;
1941 entry.percentage = 20;
1942 if (term->tl_cursor_blink)
1943 {
1944 entry.blinkwait = 700;
1945 entry.blinkon = 400;
1946 entry.blinkoff = 250;
1947 }
1948 *fg = gui.back_pixel;
1949 if (term->tl_cursor_color == NULL)
1950 *bg = gui.norm_pixel;
1951 else
1952 *bg = color_name2handle(term->tl_cursor_color);
1953 entry.name = "n";
1954 entry.used_for = SHAPE_CURSOR;
1955
1956 return &entry;
1957}
1958#endif
1959
Bram Moolenaard317b382018-02-08 22:33:31 +01001960 static void
1961may_output_cursor_props(void)
1962{
1963 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1964 || last_set_cursor_shape != desired_cursor_shape
1965 || last_set_cursor_blink != desired_cursor_blink)
1966 {
1967 last_set_cursor_color = desired_cursor_color;
1968 last_set_cursor_shape = desired_cursor_shape;
1969 last_set_cursor_blink = desired_cursor_blink;
1970 term_cursor_color(desired_cursor_color);
1971 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1972 /* this will restore the initial cursor style, if possible */
1973 ui_cursor_shape_forced(TRUE);
1974 else
1975 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1976 }
1977}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001978
Bram Moolenaard317b382018-02-08 22:33:31 +01001979/*
1980 * Set the cursor color and shape, if not last set to these.
1981 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 static void
1983may_set_cursor_props(term_T *term)
1984{
1985#ifdef FEAT_GUI
1986 /* For the GUI the cursor properties are obtained with
1987 * term_get_cursor_shape(). */
1988 if (gui.in_use)
1989 return;
1990#endif
1991 if (in_terminal_loop == term)
1992 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001994 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001996 desired_cursor_color = (char_u *)"";
1997 desired_cursor_shape = term->tl_cursor_shape;
1998 desired_cursor_blink = term->tl_cursor_blink;
1999 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000 }
2001}
2002
Bram Moolenaard317b382018-02-08 22:33:31 +01002003/*
2004 * Reset the desired cursor properties and restore them when needed.
2005 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002007prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008{
2009#ifdef FEAT_GUI
2010 if (gui.in_use)
2011 return;
2012#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002013 desired_cursor_color = (char_u *)"";
2014 desired_cursor_shape = -1;
2015 desired_cursor_blink = -1;
2016 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002017}
2018
2019/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002020 * Returns TRUE if the current window contains a terminal and we are sending
2021 * keys to the job.
2022 * If "check_job_status" is TRUE update the job status.
2023 */
2024 static int
2025term_use_loop_check(int check_job_status)
2026{
2027 term_T *term = curbuf->b_term;
2028
2029 return term != NULL
2030 && !term->tl_normal_mode
2031 && term->tl_vterm != NULL
2032 && term_job_running_check(term, check_job_status);
2033}
2034
2035/*
2036 * Returns TRUE if the current window contains a terminal and we are sending
2037 * keys to the job.
2038 */
2039 int
2040term_use_loop(void)
2041{
2042 return term_use_loop_check(FALSE);
2043}
2044
2045/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002046 * Called when entering a window with the mouse. If this is a terminal window
2047 * we may want to change state.
2048 */
2049 void
2050term_win_entered()
2051{
2052 term_T *term = curbuf->b_term;
2053
2054 if (term != NULL)
2055 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002056 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002057 {
2058 reset_VIsual_and_resel();
2059 if (State & INSERT)
2060 stop_insert_mode = TRUE;
2061 }
2062 mouse_was_outside = FALSE;
2063 enter_mouse_col = mouse_col;
2064 enter_mouse_row = mouse_row;
2065 }
2066}
2067
2068/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002069 * Wait for input and send it to the job.
2070 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2071 * when there is no more typahead.
2072 * Return when the start of a CTRL-W command is typed or anything else that
2073 * should be handled as a Normal mode command.
2074 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2075 * the terminal was closed.
2076 */
2077 int
2078terminal_loop(int blocking)
2079{
2080 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002081 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002082 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002083#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002084 int tty_fd = curbuf->b_term->tl_job->jv_channel
2085 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002086#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002087 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002088
2089 /* Remember the terminal we are sending keys to. However, the terminal
2090 * might be closed while waiting for a character, e.g. typing "exit" in a
2091 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2092 * stored reference. */
2093 in_terminal_loop = curbuf->b_term;
2094
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002095 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002096 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002097 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2098 may_set_cursor_props(curbuf->b_term);
2099
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002100 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002101 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002102#ifdef FEAT_GUI
2103 if (!curbuf->b_term->tl_system)
2104#endif
2105 /* TODO: skip screen update when handling a sequence of keys. */
2106 /* Repeat redrawing in case a message is received while redrawing.
2107 */
2108 while (must_redraw != 0)
2109 if (update_screen(0) == FAIL)
2110 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002111 if (!term_use_loop_check(TRUE))
2112 /* job finished while redrawing */
2113 break;
2114
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002115 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002116 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117
2118 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002119 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002120 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002121 /* Job finished while waiting for a character. Push back the
2122 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002123 if (c != K_IGNORE)
2124 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002125 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002126 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002127 if (c == K_IGNORE)
2128 continue;
2129
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002130#ifdef UNIX
2131 /*
2132 * The shell or another program may change the tty settings. Getting
2133 * them for every typed character is a bit of overhead, but it's needed
2134 * for the first character typed, e.g. when Vim starts in a shell.
2135 */
2136 if (isatty(tty_fd))
2137 {
2138 ttyinfo_T info;
2139
2140 /* Get the current backspace character of the pty. */
2141 if (get_tty_info(tty_fd, &info) == OK)
2142 term_backspace_char = info.backspace;
2143 }
2144#endif
2145
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002146#ifdef WIN3264
2147 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2148 * Use CTRL-BREAK to kill the job. */
2149 if (ctrl_break_was_pressed)
2150 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2151#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002152 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002153 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002154 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002155#ifdef FEAT_GUI
2156 && !curbuf->b_term->tl_system
2157#endif
2158 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 {
2160 int prev_c = c;
2161
2162#ifdef FEAT_CMDL_INFO
2163 if (add_to_showcmd(c))
2164 out_flush();
2165#endif
2166 c = term_vgetc();
2167#ifdef FEAT_CMDL_INFO
2168 clear_showcmd();
2169#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002170 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 /* job finished while waiting for a character */
2172 break;
2173
2174 if (prev_c == Ctrl_BSL)
2175 {
2176 if (c == Ctrl_N)
2177 {
2178 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2179 term_enter_normal_mode();
2180 ret = FAIL;
2181 goto theend;
2182 }
2183 /* Send both keys to the terminal. */
2184 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2185 }
2186 else if (c == Ctrl_C)
2187 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002188 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002189 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2190 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002191 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002192 {
2193 /* "CTRL-W .": send CTRL-W to the job */
2194 c = Ctrl_W;
2195 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002196 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002197 {
2198 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2199 c = Ctrl_BSL;
2200 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002201 else if (c == 'N')
2202 {
2203 /* CTRL-W N : go to Terminal-Normal mode. */
2204 term_enter_normal_mode();
2205 ret = FAIL;
2206 goto theend;
2207 }
2208 else if (c == '"')
2209 {
2210 term_paste_register(prev_c);
2211 continue;
2212 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002213 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214 {
2215 stuffcharReadbuff(Ctrl_W);
2216 stuffcharReadbuff(c);
2217 ret = OK;
2218 goto theend;
2219 }
2220 }
2221# ifdef WIN3264
2222 if (!enc_utf8 && has_mbyte && c >= 0x80)
2223 {
2224 WCHAR wc;
2225 char_u mb[3];
2226
2227 mb[0] = (unsigned)c >> 8;
2228 mb[1] = c;
2229 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2230 c = wc;
2231 }
2232# endif
2233 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2234 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002235 if (c == K_MOUSEMOVE)
2236 /* We are sure to come back here, don't reset the cursor color
2237 * and shape to avoid flickering. */
2238 restore_cursor = FALSE;
2239
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002240 ret = OK;
2241 goto theend;
2242 }
2243 }
2244 ret = FAIL;
2245
2246theend:
2247 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002248 if (restore_cursor)
2249 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002250
2251 /* Move a snapshot of the screen contents to the buffer, so that completion
2252 * works in other buffers. */
2253 if (curbuf->b_term != NULL)
2254 move_terminal_to_buffer(curbuf->b_term);
2255
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 return ret;
2257}
2258
2259/*
2260 * Called when a job has finished.
2261 * This updates the title and status, but does not close the vterm, because
2262 * there might still be pending output in the channel.
2263 */
2264 void
2265term_job_ended(job_T *job)
2266{
2267 term_T *term;
2268 int did_one = FALSE;
2269
2270 for (term = first_term; term != NULL; term = term->tl_next)
2271 if (term->tl_job == job)
2272 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002273 VIM_CLEAR(term->tl_title);
2274 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 redraw_buf_and_status_later(term->tl_buffer, VALID);
2276 did_one = TRUE;
2277 }
2278 if (did_one)
2279 redraw_statuslines();
2280 if (curbuf->b_term != NULL)
2281 {
2282 if (curbuf->b_term->tl_job == job)
2283 maketitle();
2284 update_cursor(curbuf->b_term, TRUE);
2285 }
2286}
2287
2288 static void
2289may_toggle_cursor(term_T *term)
2290{
2291 if (in_terminal_loop == term)
2292 {
2293 if (term->tl_cursor_visible)
2294 cursor_on();
2295 else
2296 cursor_off();
2297 }
2298}
2299
2300/*
2301 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002302 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303 */
2304 static int
2305color2index(VTermColor *color, int fg, int *boldp)
2306{
2307 int red = color->red;
2308 int blue = color->blue;
2309 int green = color->green;
2310
Bram Moolenaar46359e12017-11-29 22:33:38 +01002311 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002312 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002313 /* First 16 colors and default: use the ANSI index, because these
2314 * colors can be redefined. */
2315 if (t_colors >= 16)
2316 return color->ansi_index;
2317 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002318 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002319 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002320 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002321 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2322 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2323 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002324 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002325 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2326 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2327 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2328 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2329 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2330 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2331 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2332 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2333 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2334 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2335 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002336 }
2337 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002338
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002339 if (t_colors >= 256)
2340 {
2341 if (red == blue && red == green)
2342 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002343 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002344 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002345 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2346 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2347 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 int i;
2349
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002350 if (red < 5)
2351 return 17; /* 00/00/00 */
2352 if (red > 245) /* ff/ff/ff */
2353 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 for (i = 0; i < 23; ++i)
2355 if (red < cutoff[i])
2356 return i + 233;
2357 return 256;
2358 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002359 {
2360 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2361 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002362
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002363 /* 216-color cube */
2364 for (ri = 0; ri < 5; ++ri)
2365 if (red < cutoff[ri])
2366 break;
2367 for (gi = 0; gi < 5; ++gi)
2368 if (green < cutoff[gi])
2369 break;
2370 for (bi = 0; bi < 5; ++bi)
2371 if (blue < cutoff[bi])
2372 break;
2373 return 17 + ri * 36 + gi * 6 + bi;
2374 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002375 }
2376 return 0;
2377}
2378
2379/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002380 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002381 */
2382 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002383vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002384{
2385 int attr = 0;
2386
2387 if (cellattrs.bold)
2388 attr |= HL_BOLD;
2389 if (cellattrs.underline)
2390 attr |= HL_UNDERLINE;
2391 if (cellattrs.italic)
2392 attr |= HL_ITALIC;
2393 if (cellattrs.strike)
2394 attr |= HL_STRIKETHROUGH;
2395 if (cellattrs.reverse)
2396 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002397 return attr;
2398}
2399
2400/*
2401 * Store Vterm attributes in "cell" from highlight flags.
2402 */
2403 static void
2404hl2vtermAttr(int attr, cellattr_T *cell)
2405{
2406 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2407 if (attr & HL_BOLD)
2408 cell->attrs.bold = 1;
2409 if (attr & HL_UNDERLINE)
2410 cell->attrs.underline = 1;
2411 if (attr & HL_ITALIC)
2412 cell->attrs.italic = 1;
2413 if (attr & HL_STRIKETHROUGH)
2414 cell->attrs.strike = 1;
2415 if (attr & HL_INVERSE)
2416 cell->attrs.reverse = 1;
2417}
2418
2419/*
2420 * Convert the attributes of a vterm cell into an attribute index.
2421 */
2422 static int
2423cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2424{
2425 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426
2427#ifdef FEAT_GUI
2428 if (gui.in_use)
2429 {
2430 guicolor_T fg, bg;
2431
2432 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2433 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2434 return get_gui_attr_idx(attr, fg, bg);
2435 }
2436 else
2437#endif
2438#ifdef FEAT_TERMGUICOLORS
2439 if (p_tgc)
2440 {
2441 guicolor_T fg, bg;
2442
2443 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2444 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2445
2446 return get_tgc_attr_idx(attr, fg, bg);
2447 }
2448 else
2449#endif
2450 {
2451 int bold = MAYBE;
2452 int fg = color2index(&cellfg, TRUE, &bold);
2453 int bg = color2index(&cellbg, FALSE, &bold);
2454
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002455 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002456 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002457 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002458 if (fg == 0 && term_default_cterm_fg >= 0)
2459 fg = term_default_cterm_fg + 1;
2460 if (bg == 0 && term_default_cterm_bg >= 0)
2461 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002462 }
2463
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 /* with 8 colors set the bold attribute to get a bright foreground */
2465 if (bold == TRUE)
2466 attr |= HL_BOLD;
2467 return get_cterm_attr_idx(attr, fg, bg);
2468 }
2469 return 0;
2470}
2471
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002472 static void
2473set_dirty_snapshot(term_T *term)
2474{
2475 term->tl_dirty_snapshot = TRUE;
2476#ifdef FEAT_TIMERS
2477 if (!term->tl_normal_mode)
2478 {
2479 /* Update the snapshot after 100 msec of not getting updates. */
2480 profile_setlimit(100L, &term->tl_timer_due);
2481 term->tl_timer_set = TRUE;
2482 }
2483#endif
2484}
2485
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 static int
2487handle_damage(VTermRect rect, void *user)
2488{
2489 term_T *term = (term_T *)user;
2490
2491 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2492 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002493 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002494 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002495 return 1;
2496}
2497
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002498 static void
2499term_scroll_up(term_T *term, int start_row, int count)
2500{
2501 win_T *wp;
2502 VTermColor fg, bg;
2503 VTermScreenCellAttrs attr;
2504 int clear_attr;
2505
2506 /* Set the color to clear lines with. */
2507 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2508 &fg, &bg);
2509 vim_memset(&attr, 0, sizeof(attr));
2510 clear_attr = cell2attr(attr, fg, bg);
2511
2512 FOR_ALL_WINDOWS(wp)
2513 {
2514 if (wp->w_buffer == term->tl_buffer)
2515 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2516 }
2517}
2518
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002519 static int
2520handle_moverect(VTermRect dest, VTermRect src, void *user)
2521{
2522 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002523 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002524
2525 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002526 * redrawing the text. But avoid doing this multiple times, postpone until
2527 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002528 if (dest.start_col == src.start_col
2529 && dest.end_col == src.end_col
2530 && dest.start_row < src.start_row)
2531 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002532 if (dest.start_row == 0)
2533 term->tl_postponed_scroll += count;
2534 else
2535 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002537
2538 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2539 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002540 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002541
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002542 /* Note sure if the scrolling will work correctly, let's do a complete
2543 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 redraw_buf_later(term->tl_buffer, NOT_VALID);
2545 return 1;
2546}
2547
2548 static int
2549handle_movecursor(
2550 VTermPos pos,
2551 VTermPos oldpos UNUSED,
2552 int visible,
2553 void *user)
2554{
2555 term_T *term = (term_T *)user;
2556 win_T *wp;
2557
2558 term->tl_cursor_pos = pos;
2559 term->tl_cursor_visible = visible;
2560
2561 FOR_ALL_WINDOWS(wp)
2562 {
2563 if (wp->w_buffer == term->tl_buffer)
2564 position_cursor(wp, &pos);
2565 }
2566 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2567 {
2568 may_toggle_cursor(term);
2569 update_cursor(term, term->tl_cursor_visible);
2570 }
2571
2572 return 1;
2573}
2574
2575 static int
2576handle_settermprop(
2577 VTermProp prop,
2578 VTermValue *value,
2579 void *user)
2580{
2581 term_T *term = (term_T *)user;
2582
2583 switch (prop)
2584 {
2585 case VTERM_PROP_TITLE:
2586 vim_free(term->tl_title);
2587 /* a blank title isn't useful, make it empty, so that "running" is
2588 * displayed */
2589 if (*skipwhite((char_u *)value->string) == NUL)
2590 term->tl_title = NULL;
2591#ifdef WIN3264
2592 else if (!enc_utf8 && enc_codepage > 0)
2593 {
2594 WCHAR *ret = NULL;
2595 int length = 0;
2596
2597 MultiByteToWideChar_alloc(CP_UTF8, 0,
2598 (char*)value->string, (int)STRLEN(value->string),
2599 &ret, &length);
2600 if (ret != NULL)
2601 {
2602 WideCharToMultiByte_alloc(enc_codepage, 0,
2603 ret, length, (char**)&term->tl_title,
2604 &length, 0, 0);
2605 vim_free(ret);
2606 }
2607 }
2608#endif
2609 else
2610 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002611 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002612 if (term == curbuf->b_term)
2613 maketitle();
2614 break;
2615
2616 case VTERM_PROP_CURSORVISIBLE:
2617 term->tl_cursor_visible = value->boolean;
2618 may_toggle_cursor(term);
2619 out_flush();
2620 break;
2621
2622 case VTERM_PROP_CURSORBLINK:
2623 term->tl_cursor_blink = value->boolean;
2624 may_set_cursor_props(term);
2625 break;
2626
2627 case VTERM_PROP_CURSORSHAPE:
2628 term->tl_cursor_shape = value->number;
2629 may_set_cursor_props(term);
2630 break;
2631
2632 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002633 if (desired_cursor_color == term->tl_cursor_color)
2634 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002635 vim_free(term->tl_cursor_color);
2636 if (*value->string == NUL)
2637 term->tl_cursor_color = NULL;
2638 else
2639 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2640 may_set_cursor_props(term);
2641 break;
2642
2643 case VTERM_PROP_ALTSCREEN:
2644 /* TODO: do anything else? */
2645 term->tl_using_altscreen = value->boolean;
2646 break;
2647
2648 default:
2649 break;
2650 }
2651 /* Always return 1, otherwise vterm doesn't store the value internally. */
2652 return 1;
2653}
2654
2655/*
2656 * The job running in the terminal resized the terminal.
2657 */
2658 static int
2659handle_resize(int rows, int cols, void *user)
2660{
2661 term_T *term = (term_T *)user;
2662 win_T *wp;
2663
2664 term->tl_rows = rows;
2665 term->tl_cols = cols;
2666 if (term->tl_vterm_size_changed)
2667 /* Size was set by vterm_set_size(), don't set the window size. */
2668 term->tl_vterm_size_changed = FALSE;
2669 else
2670 {
2671 FOR_ALL_WINDOWS(wp)
2672 {
2673 if (wp->w_buffer == term->tl_buffer)
2674 {
2675 win_setheight_win(rows, wp);
2676 win_setwidth_win(cols, wp);
2677 }
2678 }
2679 redraw_buf_later(term->tl_buffer, NOT_VALID);
2680 }
2681 return 1;
2682}
2683
2684/*
2685 * Handle a line that is pushed off the top of the screen.
2686 */
2687 static int
2688handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2689{
2690 term_T *term = (term_T *)user;
2691
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002692 /* First remove the lines that were appended before, the pushed line goes
2693 * above it. */
2694 cleanup_scrollback(term);
2695
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002696 /* If the number of lines that are stored goes over 'termscrollback' then
2697 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002698 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002699 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002700 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002701 int i;
2702
2703 curbuf = term->tl_buffer;
2704 for (i = 0; i < todo; ++i)
2705 {
2706 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2707 ml_delete(1, FALSE);
2708 }
2709 curbuf = curwin->w_buffer;
2710
2711 term->tl_scrollback.ga_len -= todo;
2712 mch_memmove(term->tl_scrollback.ga_data,
2713 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2714 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2715 }
2716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 if (ga_grow(&term->tl_scrollback, 1) == OK)
2718 {
2719 cellattr_T *p = NULL;
2720 int len = 0;
2721 int i;
2722 int c;
2723 int col;
2724 sb_line_T *line;
2725 garray_T ga;
2726 cellattr_T fill_attr = term->tl_default_color;
2727
2728 /* do not store empty cells at the end */
2729 for (i = 0; i < cols; ++i)
2730 if (cells[i].chars[0] != 0)
2731 len = i + 1;
2732 else
2733 cell2cellattr(&cells[i], &fill_attr);
2734
2735 ga_init2(&ga, 1, 100);
2736 if (len > 0)
2737 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2738 if (p != NULL)
2739 {
2740 for (col = 0; col < len; col += cells[col].width)
2741 {
2742 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2743 {
2744 ga.ga_len = 0;
2745 break;
2746 }
2747 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2748 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2749 (char_u *)ga.ga_data + ga.ga_len);
2750 cell2cellattr(&cells[col], &p[col]);
2751 }
2752 }
2753 if (ga_grow(&ga, 1) == FAIL)
2754 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2755 else
2756 {
2757 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2758 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2759 }
2760 ga_clear(&ga);
2761
2762 line = (sb_line_T *)term->tl_scrollback.ga_data
2763 + term->tl_scrollback.ga_len;
2764 line->sb_cols = len;
2765 line->sb_cells = p;
2766 line->sb_fill_attr = fill_attr;
2767 ++term->tl_scrollback.ga_len;
2768 ++term->tl_scrollback_scrolled;
2769 }
2770 return 0; /* ignored */
2771}
2772
2773static VTermScreenCallbacks screen_callbacks = {
2774 handle_damage, /* damage */
2775 handle_moverect, /* moverect */
2776 handle_movecursor, /* movecursor */
2777 handle_settermprop, /* settermprop */
2778 NULL, /* bell */
2779 handle_resize, /* resize */
2780 handle_pushline, /* sb_pushline */
2781 NULL /* sb_popline */
2782};
2783
2784/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002785 * Do the work after the channel of a terminal was closed.
2786 * Must be called only when updating_screen is FALSE.
2787 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2788 */
2789 static int
2790term_after_channel_closed(term_T *term)
2791{
2792 /* Unless in Terminal-Normal mode: clear the vterm. */
2793 if (!term->tl_normal_mode)
2794 {
2795 int fnum = term->tl_buffer->b_fnum;
2796
2797 cleanup_vterm(term);
2798
2799 if (term->tl_finish == TL_FINISH_CLOSE)
2800 {
2801 aco_save_T aco;
2802
2803 /* ++close or term_finish == "close" */
2804 ch_log(NULL, "terminal job finished, closing window");
2805 aucmd_prepbuf(&aco, term->tl_buffer);
2806 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2807 aucmd_restbuf(&aco);
2808 return TRUE;
2809 }
2810 if (term->tl_finish == TL_FINISH_OPEN
2811 && term->tl_buffer->b_nwindows == 0)
2812 {
2813 char buf[50];
2814
2815 /* TODO: use term_opencmd */
2816 ch_log(NULL, "terminal job finished, opening window");
2817 vim_snprintf(buf, sizeof(buf),
2818 term->tl_opencmd == NULL
2819 ? "botright sbuf %d"
2820 : (char *)term->tl_opencmd, fnum);
2821 do_cmdline_cmd((char_u *)buf);
2822 }
2823 else
2824 ch_log(NULL, "terminal job finished");
2825 }
2826
2827 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2828 return FALSE;
2829}
2830
2831/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002832 * Called when a channel has been closed.
2833 * If this was a channel for a terminal window then finish it up.
2834 */
2835 void
2836term_channel_closed(channel_T *ch)
2837{
2838 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002839 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840 int did_one = FALSE;
2841
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002842 for (term = first_term; term != NULL; term = next_term)
2843 {
2844 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002845 if (term->tl_job == ch->ch_job)
2846 {
2847 term->tl_channel_closed = TRUE;
2848 did_one = TRUE;
2849
Bram Moolenaard23a8232018-02-10 18:45:26 +01002850 VIM_CLEAR(term->tl_title);
2851 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002852#ifdef WIN3264
2853 if (term->tl_out_fd != NULL)
2854 {
2855 fclose(term->tl_out_fd);
2856 term->tl_out_fd = NULL;
2857 }
2858#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002860 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002861 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002862 /* Cannot open or close windows now. Can happen when
2863 * 'lazyredraw' is set. */
2864 term->tl_channel_recently_closed = TRUE;
2865 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002866 }
2867
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002868 if (term_after_channel_closed(term))
2869 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002870 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002871 }
2872
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002873 if (did_one)
2874 {
2875 redraw_statuslines();
2876
2877 /* Need to break out of vgetc(). */
2878 ins_char_typebuf(K_IGNORE);
2879 typebuf_was_filled = TRUE;
2880
2881 term = curbuf->b_term;
2882 if (term != NULL)
2883 {
2884 if (term->tl_job == ch->ch_job)
2885 maketitle();
2886 update_cursor(term, term->tl_cursor_visible);
2887 }
2888 }
2889}
2890
2891/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002892 * To be called after resetting updating_screen: handle any terminal where the
2893 * channel was closed.
2894 */
2895 void
2896term_check_channel_closed_recently()
2897{
2898 term_T *term;
2899 term_T *next_term;
2900
2901 for (term = first_term; term != NULL; term = next_term)
2902 {
2903 next_term = term->tl_next;
2904 if (term->tl_channel_recently_closed)
2905 {
2906 term->tl_channel_recently_closed = FALSE;
2907 if (term_after_channel_closed(term))
2908 // start over, the list may have changed
2909 next_term = first_term;
2910 }
2911 }
2912}
2913
2914/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002915 * Fill one screen line from a line of the terminal.
2916 * Advances "pos" to past the last column.
2917 */
2918 static void
2919term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2920{
2921 int off = screen_get_current_line_off();
2922
2923 for (pos->col = 0; pos->col < max_col; )
2924 {
2925 VTermScreenCell cell;
2926 int c;
2927
2928 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2929 vim_memset(&cell, 0, sizeof(cell));
2930
2931 c = cell.chars[0];
2932 if (c == NUL)
2933 {
2934 ScreenLines[off] = ' ';
2935 if (enc_utf8)
2936 ScreenLinesUC[off] = NUL;
2937 }
2938 else
2939 {
2940 if (enc_utf8)
2941 {
2942 int i;
2943
2944 /* composing chars */
2945 for (i = 0; i < Screen_mco
2946 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2947 {
2948 ScreenLinesC[i][off] = cell.chars[i + 1];
2949 if (cell.chars[i + 1] == 0)
2950 break;
2951 }
2952 if (c >= 0x80 || (Screen_mco > 0
2953 && ScreenLinesC[0][off] != 0))
2954 {
2955 ScreenLines[off] = ' ';
2956 ScreenLinesUC[off] = c;
2957 }
2958 else
2959 {
2960 ScreenLines[off] = c;
2961 ScreenLinesUC[off] = NUL;
2962 }
2963 }
2964#ifdef WIN3264
2965 else if (has_mbyte && c >= 0x80)
2966 {
2967 char_u mb[MB_MAXBYTES+1];
2968 WCHAR wc = c;
2969
2970 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2971 (char*)mb, 2, 0, 0) > 1)
2972 {
2973 ScreenLines[off] = mb[0];
2974 ScreenLines[off + 1] = mb[1];
2975 cell.width = mb_ptr2cells(mb);
2976 }
2977 else
2978 ScreenLines[off] = c;
2979 }
2980#endif
2981 else
2982 ScreenLines[off] = c;
2983 }
2984 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2985
2986 ++pos->col;
2987 ++off;
2988 if (cell.width == 2)
2989 {
2990 if (enc_utf8)
2991 ScreenLinesUC[off] = NUL;
2992
2993 /* don't set the second byte to NUL for a DBCS encoding, it
2994 * has been set above */
2995 if (enc_utf8 || !has_mbyte)
2996 ScreenLines[off] = NUL;
2997
2998 ++pos->col;
2999 ++off;
3000 }
3001 }
3002}
3003
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003004#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003005 static void
3006update_system_term(term_T *term)
3007{
3008 VTermPos pos;
3009 VTermScreen *screen;
3010
3011 if (term->tl_vterm == NULL)
3012 return;
3013 screen = vterm_obtain_screen(term->tl_vterm);
3014
3015 /* Scroll up to make more room for terminal lines if needed. */
3016 while (term->tl_toprow > 0
3017 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3018 {
3019 int save_p_more = p_more;
3020
3021 p_more = FALSE;
3022 msg_row = Rows - 1;
3023 msg_puts((char_u *)"\n");
3024 p_more = save_p_more;
3025 --term->tl_toprow;
3026 }
3027
3028 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3029 && pos.row < Rows; ++pos.row)
3030 {
3031 if (pos.row < term->tl_rows)
3032 {
3033 int max_col = MIN(Columns, term->tl_cols);
3034
3035 term_line2screenline(screen, &pos, max_col);
3036 }
3037 else
3038 pos.col = 0;
3039
3040 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3041 }
3042
3043 term->tl_dirty_row_start = MAX_ROW;
3044 term->tl_dirty_row_end = 0;
3045 update_cursor(term, TRUE);
3046}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003047#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003048
3049/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003050 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3051 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003052 * Terminal-Normal mode.
3053 */
3054 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003055term_do_update_window(win_T *wp)
3056{
3057 term_T *term = wp->w_buffer->b_term;
3058
3059 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3060}
3061
3062/*
3063 * Called to update a window that contains an active terminal.
3064 */
3065 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003066term_update_window(win_T *wp)
3067{
3068 term_T *term = wp->w_buffer->b_term;
3069 VTerm *vterm;
3070 VTermScreen *screen;
3071 VTermState *state;
3072 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003073 int rows, cols;
3074 int newrows, newcols;
3075 int minsize;
3076 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003077
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 vterm = term->tl_vterm;
3079 screen = vterm_obtain_screen(vterm);
3080 state = vterm_obtain_state(vterm);
3081
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003082 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3083 * SOME_VALID only redraw what was marked dirty. */
3084 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003085 {
3086 term->tl_dirty_row_start = 0;
3087 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003088
3089 if (term->tl_postponed_scroll > 0
3090 && term->tl_postponed_scroll < term->tl_rows / 3)
3091 /* Scrolling is usually faster than redrawing, when there are only
3092 * a few lines to scroll. */
3093 term_scroll_up(term, 0, term->tl_postponed_scroll);
3094 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003095 }
3096
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097 /*
3098 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003099 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003100 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003101 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102
Bram Moolenaar498c2562018-04-15 23:45:15 +02003103 newrows = 99999;
3104 newcols = 99999;
3105 FOR_ALL_WINDOWS(twp)
3106 {
3107 /* When more than one window shows the same terminal, use the
3108 * smallest size. */
3109 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003111 newrows = MIN(newrows, twp->w_height);
3112 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003113 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003114 }
3115 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3116 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3117
3118 if (term->tl_rows != newrows || term->tl_cols != newcols)
3119 {
3120
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003121
3122 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003123 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003125 newrows);
3126 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127 }
3128
3129 /* The cursor may have been moved when resizing. */
3130 vterm_state_get_cursorpos(state, &pos);
3131 position_cursor(wp, &pos);
3132
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003133 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3134 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003135 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003136 if (pos.row < term->tl_rows)
3137 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003138 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139
Bram Moolenaar13568252018-03-16 20:46:58 +01003140 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003141 }
3142 else
3143 pos.col = 0;
3144
Bram Moolenaarf118d482018-03-13 13:14:00 +01003145 screen_line(wp->w_winrow + pos.row
3146#ifdef FEAT_MENU
3147 + winbar_height(wp)
3148#endif
3149 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003150 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003151 term->tl_dirty_row_start = MAX_ROW;
3152 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153}
3154
3155/*
3156 * Return TRUE if "wp" is a terminal window where the job has finished.
3157 */
3158 int
3159term_is_finished(buf_T *buf)
3160{
3161 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3162}
3163
3164/*
3165 * Return TRUE if "wp" is a terminal window where the job has finished or we
3166 * are in Terminal-Normal mode, thus we show the buffer contents.
3167 */
3168 int
3169term_show_buffer(buf_T *buf)
3170{
3171 term_T *term = buf->b_term;
3172
3173 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3174}
3175
3176/*
3177 * The current buffer is going to be changed. If there is terminal
3178 * highlighting remove it now.
3179 */
3180 void
3181term_change_in_curbuf(void)
3182{
3183 term_T *term = curbuf->b_term;
3184
3185 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3186 {
3187 free_scrollback(term);
3188 redraw_buf_later(term->tl_buffer, NOT_VALID);
3189
3190 /* The buffer is now like a normal buffer, it cannot be easily
3191 * abandoned when changed. */
3192 set_string_option_direct((char_u *)"buftype", -1,
3193 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3194 }
3195}
3196
3197/*
3198 * Get the screen attribute for a position in the buffer.
3199 * Use a negative "col" to get the filler background color.
3200 */
3201 int
3202term_get_attr(buf_T *buf, linenr_T lnum, int col)
3203{
3204 term_T *term = buf->b_term;
3205 sb_line_T *line;
3206 cellattr_T *cellattr;
3207
3208 if (lnum > term->tl_scrollback.ga_len)
3209 cellattr = &term->tl_default_color;
3210 else
3211 {
3212 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3213 if (col < 0 || col >= line->sb_cols)
3214 cellattr = &line->sb_fill_attr;
3215 else
3216 cellattr = line->sb_cells + col;
3217 }
3218 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3219}
3220
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003221/*
3222 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003223 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003224 */
3225 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003226cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003227{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003228 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003229}
3230
3231/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003232 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003233 */
3234 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003235init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003237 VTermColor *fg, *bg;
3238 int fgval, bgval;
3239 int id;
3240
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003241 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3242 term->tl_default_color.width = 1;
3243 fg = &term->tl_default_color.fg;
3244 bg = &term->tl_default_color.bg;
3245
3246 /* Vterm uses a default black background. Set it to white when
3247 * 'background' is "light". */
3248 if (*p_bg == 'l')
3249 {
3250 fgval = 0;
3251 bgval = 255;
3252 }
3253 else
3254 {
3255 fgval = 255;
3256 bgval = 0;
3257 }
3258 fg->red = fg->green = fg->blue = fgval;
3259 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003260 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003261
3262 /* The "Terminal" highlight group overrules the defaults. */
3263 id = syn_name2id((char_u *)"Terminal");
3264
Bram Moolenaar46359e12017-11-29 22:33:38 +01003265 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003266#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3267 if (0
3268# ifdef FEAT_GUI
3269 || gui.in_use
3270# endif
3271# ifdef FEAT_TERMGUICOLORS
3272 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003273# ifdef FEAT_VTP
3274 /* Finally get INVALCOLOR on this execution path */
3275 || (!p_tgc && t_colors >= 256)
3276# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003277# endif
3278 )
3279 {
3280 guicolor_T fg_rgb = INVALCOLOR;
3281 guicolor_T bg_rgb = INVALCOLOR;
3282
3283 if (id != 0)
3284 syn_id2colors(id, &fg_rgb, &bg_rgb);
3285
3286# ifdef FEAT_GUI
3287 if (gui.in_use)
3288 {
3289 if (fg_rgb == INVALCOLOR)
3290 fg_rgb = gui.norm_pixel;
3291 if (bg_rgb == INVALCOLOR)
3292 bg_rgb = gui.back_pixel;
3293 }
3294# ifdef FEAT_TERMGUICOLORS
3295 else
3296# endif
3297# endif
3298# ifdef FEAT_TERMGUICOLORS
3299 {
3300 if (fg_rgb == INVALCOLOR)
3301 fg_rgb = cterm_normal_fg_gui_color;
3302 if (bg_rgb == INVALCOLOR)
3303 bg_rgb = cterm_normal_bg_gui_color;
3304 }
3305# endif
3306 if (fg_rgb != INVALCOLOR)
3307 {
3308 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3309
3310 fg->red = (unsigned)(rgb >> 16);
3311 fg->green = (unsigned)(rgb >> 8) & 255;
3312 fg->blue = (unsigned)rgb & 255;
3313 }
3314 if (bg_rgb != INVALCOLOR)
3315 {
3316 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3317
3318 bg->red = (unsigned)(rgb >> 16);
3319 bg->green = (unsigned)(rgb >> 8) & 255;
3320 bg->blue = (unsigned)rgb & 255;
3321 }
3322 }
3323 else
3324#endif
3325 if (id != 0 && t_colors >= 16)
3326 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003327 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003328 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003329 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003330 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003331 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332 else
3333 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003334#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003336#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003337
3338 /* In an MS-Windows console we know the normal colors. */
3339 if (cterm_normal_fg_color > 0)
3340 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003341 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003342# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003343 tmp = fg->red;
3344 fg->red = fg->blue;
3345 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003346# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003348# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003349 else
3350 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003351# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003352
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003353 if (cterm_normal_bg_color > 0)
3354 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003355 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003356# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 tmp = bg->red;
3358 bg->red = bg->blue;
3359 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003360# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003362# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003363 else
3364 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003365# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003366 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003367}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003368
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003369#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3370/*
3371 * Set the 16 ANSI colors from array of RGB values
3372 */
3373 static void
3374set_vterm_palette(VTerm *vterm, long_u *rgb)
3375{
3376 int index = 0;
3377 VTermState *state = vterm_obtain_state(vterm);
3378 for (; index < 16; index++)
3379 {
3380 VTermColor color;
3381 color.red = (unsigned)(rgb[index] >> 16);
3382 color.green = (unsigned)(rgb[index] >> 8) & 255;
3383 color.blue = (unsigned)rgb[index] & 255;
3384 vterm_state_set_palette_color(state, index, &color);
3385 }
3386}
3387
3388/*
3389 * Set the ANSI color palette from a list of colors
3390 */
3391 static int
3392set_ansi_colors_list(VTerm *vterm, list_T *list)
3393{
3394 int n = 0;
3395 long_u rgb[16];
3396 listitem_T *li = list->lv_first;
3397
3398 for (; li != NULL && n < 16; li = li->li_next, n++)
3399 {
3400 char_u *color_name;
3401 guicolor_T guicolor;
3402
3403 color_name = get_tv_string_chk(&li->li_tv);
3404 if (color_name == NULL)
3405 return FAIL;
3406
3407 guicolor = GUI_GET_COLOR(color_name);
3408 if (guicolor == INVALCOLOR)
3409 return FAIL;
3410
3411 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3412 }
3413
3414 if (n != 16 || li != NULL)
3415 return FAIL;
3416
3417 set_vterm_palette(vterm, rgb);
3418
3419 return OK;
3420}
3421
3422/*
3423 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3424 */
3425 static void
3426init_vterm_ansi_colors(VTerm *vterm)
3427{
3428 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3429
3430 if (var != NULL
3431 && (var->di_tv.v_type != VAR_LIST
3432 || var->di_tv.vval.v_list == NULL
3433 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3434 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3435}
3436#endif
3437
Bram Moolenaar52acb112018-03-18 19:20:22 +01003438/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003439 * Handles a "drop" command from the job in the terminal.
3440 * "item" is the file name, "item->li_next" may have options.
3441 */
3442 static void
3443handle_drop_command(listitem_T *item)
3444{
3445 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003446 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003447 int bufnr;
3448 win_T *wp;
3449 tabpage_T *tp;
3450 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003451 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003452
3453 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3454 FOR_ALL_TAB_WINDOWS(tp, wp)
3455 {
3456 if (wp->w_buffer->b_fnum == bufnr)
3457 {
3458 /* buffer is in a window already, go there */
3459 goto_tabpage_win(tp, wp);
3460 return;
3461 }
3462 }
3463
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003464 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003465
3466 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3467 && opt_item->li_tv.vval.v_dict != NULL)
3468 {
3469 dict_T *dict = opt_item->li_tv.vval.v_dict;
3470 char_u *p;
3471
3472 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3473 if (p == NULL)
3474 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3475 if (p != NULL)
3476 {
3477 if (check_ff_value(p) == FAIL)
3478 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3479 else
3480 ea.force_ff = *p;
3481 }
3482 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3483 if (p == NULL)
3484 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3485 if (p != NULL)
3486 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003487 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003488 if (ea.cmd != NULL)
3489 {
3490 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3491 ea.force_enc = 11;
3492 tofree = ea.cmd;
3493 }
3494 }
3495
3496 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3497 if (p != NULL)
3498 get_bad_opt(p, &ea);
3499
3500 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3501 ea.force_bin = FORCE_BIN;
3502 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3503 ea.force_bin = FORCE_BIN;
3504 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3505 ea.force_bin = FORCE_NOBIN;
3506 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3507 ea.force_bin = FORCE_NOBIN;
3508 }
3509
3510 /* open in new window, like ":split fname" */
3511 if (ea.cmd == NULL)
3512 ea.cmd = (char_u *)"split";
3513 ea.arg = fname;
3514 ea.cmdidx = CMD_split;
3515 ex_splitview(&ea);
3516
3517 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003518}
3519
3520/*
3521 * Handles a function call from the job running in a terminal.
3522 * "item" is the function name, "item->li_next" has the arguments.
3523 */
3524 static void
3525handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3526{
3527 char_u *func;
3528 typval_T argvars[2];
3529 typval_T rettv;
3530 int doesrange;
3531
3532 if (item->li_next == NULL)
3533 {
3534 ch_log(channel, "Missing function arguments for call");
3535 return;
3536 }
3537 func = get_tv_string(&item->li_tv);
3538
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003539 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003540 {
3541 ch_log(channel, "Invalid function name: %s", func);
3542 return;
3543 }
3544
3545 argvars[0].v_type = VAR_NUMBER;
3546 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3547 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003548 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003549 2, argvars, /* argv_func */ NULL,
3550 /* firstline */ 1, /* lastline */ 1,
3551 &doesrange, /* evaluate */ TRUE,
3552 /* partial */ NULL, /* selfdict */ NULL) == OK)
3553 {
3554 clear_tv(&rettv);
3555 ch_log(channel, "Function %s called", func);
3556 }
3557 else
3558 ch_log(channel, "Calling function %s failed", func);
3559}
3560
3561/*
3562 * Called by libvterm when it cannot recognize an OSC sequence.
3563 * We recognize a terminal API command.
3564 */
3565 static int
3566parse_osc(const char *command, size_t cmdlen, void *user)
3567{
3568 term_T *term = (term_T *)user;
3569 js_read_T reader;
3570 typval_T tv;
3571 channel_T *channel = term->tl_job == NULL ? NULL
3572 : term->tl_job->jv_channel;
3573
3574 /* We recognize only OSC 5 1 ; {command} */
3575 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3576 return 0; /* not handled */
3577
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003578 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003579 if (reader.js_buf == NULL)
3580 return 1;
3581 reader.js_fill = NULL;
3582 reader.js_used = 0;
3583 if (json_decode(&reader, &tv, 0) == OK
3584 && tv.v_type == VAR_LIST
3585 && tv.vval.v_list != NULL)
3586 {
3587 listitem_T *item = tv.vval.v_list->lv_first;
3588
3589 if (item == NULL)
3590 ch_log(channel, "Missing command");
3591 else
3592 {
3593 char_u *cmd = get_tv_string(&item->li_tv);
3594
Bram Moolenaara997b452018-04-17 23:24:06 +02003595 /* Make sure an invoked command doesn't delete the buffer (and the
3596 * terminal) under our fingers. */
3597 ++term->tl_buffer->b_locked;
3598
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003599 item = item->li_next;
3600 if (item == NULL)
3601 ch_log(channel, "Missing argument for %s", cmd);
3602 else if (STRCMP(cmd, "drop") == 0)
3603 handle_drop_command(item);
3604 else if (STRCMP(cmd, "call") == 0)
3605 handle_call_command(term, channel, item);
3606 else
3607 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003608 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003609 }
3610 }
3611 else
3612 ch_log(channel, "Invalid JSON received");
3613
3614 vim_free(reader.js_buf);
3615 clear_tv(&tv);
3616 return 1;
3617}
3618
3619static VTermParserCallbacks parser_fallbacks = {
3620 NULL, /* text */
3621 NULL, /* control */
3622 NULL, /* escape */
3623 NULL, /* csi */
3624 parse_osc, /* osc */
3625 NULL, /* dcs */
3626 NULL /* resize */
3627};
3628
3629/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003630 * Use Vim's allocation functions for vterm so profiling works.
3631 */
3632 static void *
3633vterm_malloc(size_t size, void *data UNUSED)
3634{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003635 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003636}
3637
3638 static void
3639vterm_memfree(void *ptr, void *data UNUSED)
3640{
3641 vim_free(ptr);
3642}
3643
3644static VTermAllocatorFunctions vterm_allocator = {
3645 &vterm_malloc,
3646 &vterm_memfree
3647};
3648
3649/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003650 * Create a new vterm and initialize it.
3651 */
3652 static void
3653create_vterm(term_T *term, int rows, int cols)
3654{
3655 VTerm *vterm;
3656 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003657 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003658 VTermValue value;
3659
Bram Moolenaar756ef112018-04-10 12:04:27 +02003660 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003661 term->tl_vterm = vterm;
3662 screen = vterm_obtain_screen(vterm);
3663 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3664 /* TODO: depends on 'encoding'. */
3665 vterm_set_utf8(vterm, 1);
3666
3667 init_default_colors(term);
3668
3669 vterm_state_set_default_colors(
3670 vterm_obtain_state(vterm),
3671 &term->tl_default_color.fg,
3672 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003673
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003674 if (t_colors >= 16)
3675 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3676
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677 /* Required to initialize most things. */
3678 vterm_screen_reset(screen, 1 /* hard */);
3679
3680 /* Allow using alternate screen. */
3681 vterm_screen_enable_altscreen(screen, 1);
3682
3683 /* For unix do not use a blinking cursor. In an xterm this causes the
3684 * cursor to blink if it's blinking in the xterm.
3685 * For Windows we respect the system wide setting. */
3686#ifdef WIN3264
3687 if (GetCaretBlinkTime() == INFINITE)
3688 value.boolean = 0;
3689 else
3690 value.boolean = 1;
3691#else
3692 value.boolean = 0;
3693#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003694 state = vterm_obtain_state(vterm);
3695 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3696 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003697}
3698
3699/*
3700 * Return the text to show for the buffer name and status.
3701 */
3702 char_u *
3703term_get_status_text(term_T *term)
3704{
3705 if (term->tl_status_text == NULL)
3706 {
3707 char_u *txt;
3708 size_t len;
3709
3710 if (term->tl_normal_mode)
3711 {
3712 if (term_job_running(term))
3713 txt = (char_u *)_("Terminal");
3714 else
3715 txt = (char_u *)_("Terminal-finished");
3716 }
3717 else if (term->tl_title != NULL)
3718 txt = term->tl_title;
3719 else if (term_none_open(term))
3720 txt = (char_u *)_("active");
3721 else if (term_job_running(term))
3722 txt = (char_u *)_("running");
3723 else
3724 txt = (char_u *)_("finished");
3725 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3726 term->tl_status_text = alloc((int)len);
3727 if (term->tl_status_text != NULL)
3728 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3729 term->tl_buffer->b_fname, txt);
3730 }
3731 return term->tl_status_text;
3732}
3733
3734/*
3735 * Mark references in jobs of terminals.
3736 */
3737 int
3738set_ref_in_term(int copyID)
3739{
3740 int abort = FALSE;
3741 term_T *term;
3742 typval_T tv;
3743
3744 for (term = first_term; term != NULL; term = term->tl_next)
3745 if (term->tl_job != NULL)
3746 {
3747 tv.v_type = VAR_JOB;
3748 tv.vval.v_job = term->tl_job;
3749 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3750 }
3751 return abort;
3752}
3753
3754/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003755 * Cache "Terminal" highlight group colors.
3756 */
3757 void
3758set_terminal_default_colors(int cterm_fg, int cterm_bg)
3759{
3760 term_default_cterm_fg = cterm_fg - 1;
3761 term_default_cterm_bg = cterm_bg - 1;
3762}
3763
3764/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003765 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003766 * Returns NULL when the buffer is not for a terminal window and logs a message
3767 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003768 */
3769 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003770term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003771{
3772 buf_T *buf;
3773
3774 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3775 ++emsg_off;
3776 buf = get_buf_tv(&argvars[0], FALSE);
3777 --emsg_off;
3778 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003779 {
3780 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003781 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003782 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003783 return buf;
3784}
3785
Bram Moolenaard96ff162018-02-18 22:13:29 +01003786 static int
3787same_color(VTermColor *a, VTermColor *b)
3788{
3789 return a->red == b->red
3790 && a->green == b->green
3791 && a->blue == b->blue
3792 && a->ansi_index == b->ansi_index;
3793}
3794
3795 static void
3796dump_term_color(FILE *fd, VTermColor *color)
3797{
3798 fprintf(fd, "%02x%02x%02x%d",
3799 (int)color->red, (int)color->green, (int)color->blue,
3800 (int)color->ansi_index);
3801}
3802
3803/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003804 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003805 *
3806 * Each screen cell in full is:
3807 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3808 * {characters} is a space for an empty cell
3809 * For a double-width character "+" is changed to "*" and the next cell is
3810 * skipped.
3811 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3812 * when "&" use the same as the previous cell.
3813 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3814 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3815 * {color-idx} is a number from 0 to 255
3816 *
3817 * Screen cell with same width, attributes and color as the previous one:
3818 * |{characters}
3819 *
3820 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3821 *
3822 * Repeating the previous screen cell:
3823 * @{count}
3824 */
3825 void
3826f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3827{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003828 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003829 term_T *term;
3830 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003831 int max_height = 0;
3832 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003833 stat_T st;
3834 FILE *fd;
3835 VTermPos pos;
3836 VTermScreen *screen;
3837 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003838 VTermState *state;
3839 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003840
3841 if (check_restricted() || check_secure())
3842 return;
3843 if (buf == NULL)
3844 return;
3845 term = buf->b_term;
3846
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003847 if (argvars[2].v_type != VAR_UNKNOWN)
3848 {
3849 dict_T *d;
3850
3851 if (argvars[2].v_type != VAR_DICT)
3852 {
3853 EMSG(_(e_dictreq));
3854 return;
3855 }
3856 d = argvars[2].vval.v_dict;
3857 if (d != NULL)
3858 {
3859 max_height = get_dict_number(d, (char_u *)"rows");
3860 max_width = get_dict_number(d, (char_u *)"columns");
3861 }
3862 }
3863
Bram Moolenaard96ff162018-02-18 22:13:29 +01003864 fname = get_tv_string_chk(&argvars[1]);
3865 if (fname == NULL)
3866 return;
3867 if (mch_stat((char *)fname, &st) >= 0)
3868 {
3869 EMSG2(_("E953: File exists: %s"), fname);
3870 return;
3871 }
3872
Bram Moolenaard96ff162018-02-18 22:13:29 +01003873 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3874 {
3875 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3876 return;
3877 }
3878
3879 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3880
3881 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003882 state = vterm_obtain_state(term->tl_vterm);
3883 vterm_state_get_cursorpos(state, &cursor_pos);
3884
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003885 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3886 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003887 {
3888 int repeat = 0;
3889
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003890 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3891 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003892 {
3893 VTermScreenCell cell;
3894 int same_attr;
3895 int same_chars = TRUE;
3896 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003897 int is_cursor_pos = (pos.col == cursor_pos.col
3898 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003899
3900 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3901 vim_memset(&cell, 0, sizeof(cell));
3902
3903 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3904 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003905 int c = cell.chars[i];
3906 int pc = prev_cell.chars[i];
3907
3908 /* For the first character NUL is the same as space. */
3909 if (i == 0)
3910 {
3911 c = (c == NUL) ? ' ' : c;
3912 pc = (pc == NUL) ? ' ' : pc;
3913 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003914 if (cell.chars[i] != prev_cell.chars[i])
3915 same_chars = FALSE;
3916 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3917 break;
3918 }
3919 same_attr = vtermAttr2hl(cell.attrs)
3920 == vtermAttr2hl(prev_cell.attrs)
3921 && same_color(&cell.fg, &prev_cell.fg)
3922 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003923 if (same_chars && cell.width == prev_cell.width && same_attr
3924 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003925 {
3926 ++repeat;
3927 }
3928 else
3929 {
3930 if (repeat > 0)
3931 {
3932 fprintf(fd, "@%d", repeat);
3933 repeat = 0;
3934 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003935 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003936
3937 if (cell.chars[0] == NUL)
3938 fputs(" ", fd);
3939 else
3940 {
3941 char_u charbuf[10];
3942 int len;
3943
3944 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3945 && cell.chars[i] != NUL; ++i)
3946 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003947 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003948 fwrite(charbuf, len, 1, fd);
3949 }
3950 }
3951
3952 /* When only the characters differ we don't write anything, the
3953 * following "|", "@" or NL will indicate using the same
3954 * attributes. */
3955 if (cell.width != prev_cell.width || !same_attr)
3956 {
3957 if (cell.width == 2)
3958 {
3959 fputs("*", fd);
3960 ++pos.col;
3961 }
3962 else
3963 fputs("+", fd);
3964
3965 if (same_attr)
3966 {
3967 fputs("&", fd);
3968 }
3969 else
3970 {
3971 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3972 if (same_color(&cell.fg, &prev_cell.fg))
3973 fputs("&", fd);
3974 else
3975 {
3976 fputs("#", fd);
3977 dump_term_color(fd, &cell.fg);
3978 }
3979 if (same_color(&cell.bg, &prev_cell.bg))
3980 fputs("&", fd);
3981 else
3982 {
3983 fputs("#", fd);
3984 dump_term_color(fd, &cell.bg);
3985 }
3986 }
3987 }
3988
3989 prev_cell = cell;
3990 }
3991 }
3992 if (repeat > 0)
3993 fprintf(fd, "@%d", repeat);
3994 fputs("\n", fd);
3995 }
3996
3997 fclose(fd);
3998}
3999
4000/*
4001 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4002 */
4003 static void
4004dump_is_corrupt(garray_T *gap)
4005{
4006 ga_concat(gap, (char_u *)"CORRUPT");
4007}
4008
4009 static void
4010append_cell(garray_T *gap, cellattr_T *cell)
4011{
4012 if (ga_grow(gap, 1) == OK)
4013 {
4014 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4015 ++gap->ga_len;
4016 }
4017}
4018
4019/*
4020 * Read the dump file from "fd" and append lines to the current buffer.
4021 * Return the cell width of the longest line.
4022 */
4023 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004024read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004025{
4026 int c;
4027 garray_T ga_text;
4028 garray_T ga_cell;
4029 char_u *prev_char = NULL;
4030 int attr = 0;
4031 cellattr_T cell;
4032 term_T *term = curbuf->b_term;
4033 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004034 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004035
4036 ga_init2(&ga_text, 1, 90);
4037 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4038 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004039 cursor_pos->row = -1;
4040 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004041
4042 c = fgetc(fd);
4043 for (;;)
4044 {
4045 if (c == EOF)
4046 break;
4047 if (c == '\n')
4048 {
4049 /* End of a line: append it to the buffer. */
4050 if (ga_text.ga_data == NULL)
4051 dump_is_corrupt(&ga_text);
4052 if (ga_grow(&term->tl_scrollback, 1) == OK)
4053 {
4054 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4055 + term->tl_scrollback.ga_len;
4056
4057 if (max_cells < ga_cell.ga_len)
4058 max_cells = ga_cell.ga_len;
4059 line->sb_cols = ga_cell.ga_len;
4060 line->sb_cells = ga_cell.ga_data;
4061 line->sb_fill_attr = term->tl_default_color;
4062 ++term->tl_scrollback.ga_len;
4063 ga_init(&ga_cell);
4064
4065 ga_append(&ga_text, NUL);
4066 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4067 ga_text.ga_len, FALSE);
4068 }
4069 else
4070 ga_clear(&ga_cell);
4071 ga_text.ga_len = 0;
4072
4073 c = fgetc(fd);
4074 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004075 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004076 {
4077 int prev_len = ga_text.ga_len;
4078
Bram Moolenaar9271d052018-02-25 21:39:46 +01004079 if (c == '>')
4080 {
4081 if (cursor_pos->row != -1)
4082 dump_is_corrupt(&ga_text); /* duplicate cursor */
4083 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4084 cursor_pos->col = ga_cell.ga_len;
4085 }
4086
Bram Moolenaard96ff162018-02-18 22:13:29 +01004087 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4088 c = fgetc(fd);
4089 if (c != EOF)
4090 ga_append(&ga_text, c);
4091 for (;;)
4092 {
4093 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004094 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004095 || c == EOF || c == '\n')
4096 break;
4097 ga_append(&ga_text, c);
4098 }
4099
4100 /* save the character for repeating it */
4101 vim_free(prev_char);
4102 if (ga_text.ga_data != NULL)
4103 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4104 ga_text.ga_len - prev_len);
4105
Bram Moolenaar9271d052018-02-25 21:39:46 +01004106 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004107 {
4108 /* use all attributes from previous cell */
4109 }
4110 else if (c == '+' || c == '*')
4111 {
4112 int is_bg;
4113
4114 cell.width = c == '+' ? 1 : 2;
4115
4116 c = fgetc(fd);
4117 if (c == '&')
4118 {
4119 /* use same attr as previous cell */
4120 c = fgetc(fd);
4121 }
4122 else if (isdigit(c))
4123 {
4124 /* get the decimal attribute */
4125 attr = 0;
4126 while (isdigit(c))
4127 {
4128 attr = attr * 10 + (c - '0');
4129 c = fgetc(fd);
4130 }
4131 hl2vtermAttr(attr, &cell);
4132 }
4133 else
4134 dump_is_corrupt(&ga_text);
4135
4136 /* is_bg == 0: fg, is_bg == 1: bg */
4137 for (is_bg = 0; is_bg <= 1; ++is_bg)
4138 {
4139 if (c == '&')
4140 {
4141 /* use same color as previous cell */
4142 c = fgetc(fd);
4143 }
4144 else if (c == '#')
4145 {
4146 int red, green, blue, index = 0;
4147
4148 c = fgetc(fd);
4149 red = hex2nr(c);
4150 c = fgetc(fd);
4151 red = (red << 4) + hex2nr(c);
4152 c = fgetc(fd);
4153 green = hex2nr(c);
4154 c = fgetc(fd);
4155 green = (green << 4) + hex2nr(c);
4156 c = fgetc(fd);
4157 blue = hex2nr(c);
4158 c = fgetc(fd);
4159 blue = (blue << 4) + hex2nr(c);
4160 c = fgetc(fd);
4161 if (!isdigit(c))
4162 dump_is_corrupt(&ga_text);
4163 while (isdigit(c))
4164 {
4165 index = index * 10 + (c - '0');
4166 c = fgetc(fd);
4167 }
4168
4169 if (is_bg)
4170 {
4171 cell.bg.red = red;
4172 cell.bg.green = green;
4173 cell.bg.blue = blue;
4174 cell.bg.ansi_index = index;
4175 }
4176 else
4177 {
4178 cell.fg.red = red;
4179 cell.fg.green = green;
4180 cell.fg.blue = blue;
4181 cell.fg.ansi_index = index;
4182 }
4183 }
4184 else
4185 dump_is_corrupt(&ga_text);
4186 }
4187 }
4188 else
4189 dump_is_corrupt(&ga_text);
4190
4191 append_cell(&ga_cell, &cell);
4192 }
4193 else if (c == '@')
4194 {
4195 if (prev_char == NULL)
4196 dump_is_corrupt(&ga_text);
4197 else
4198 {
4199 int count = 0;
4200
4201 /* repeat previous character, get the count */
4202 for (;;)
4203 {
4204 c = fgetc(fd);
4205 if (!isdigit(c))
4206 break;
4207 count = count * 10 + (c - '0');
4208 }
4209
4210 while (count-- > 0)
4211 {
4212 ga_concat(&ga_text, prev_char);
4213 append_cell(&ga_cell, &cell);
4214 }
4215 }
4216 }
4217 else
4218 {
4219 dump_is_corrupt(&ga_text);
4220 c = fgetc(fd);
4221 }
4222 }
4223
4224 if (ga_text.ga_len > 0)
4225 {
4226 /* trailing characters after last NL */
4227 dump_is_corrupt(&ga_text);
4228 ga_append(&ga_text, NUL);
4229 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4230 ga_text.ga_len, FALSE);
4231 }
4232
4233 ga_clear(&ga_text);
4234 vim_free(prev_char);
4235
4236 return max_cells;
4237}
4238
4239/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004240 * Return an allocated string with at least "text_width" "=" characters and
4241 * "fname" inserted in the middle.
4242 */
4243 static char_u *
4244get_separator(int text_width, char_u *fname)
4245{
4246 int width = MAX(text_width, curwin->w_width);
4247 char_u *textline;
4248 int fname_size;
4249 char_u *p = fname;
4250 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004251 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004252
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004253 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004254 if (textline == NULL)
4255 return NULL;
4256
4257 fname_size = vim_strsize(fname);
4258 if (fname_size < width - 8)
4259 {
4260 /* enough room, don't use the full window width */
4261 width = MAX(text_width, fname_size + 8);
4262 }
4263 else if (fname_size > width - 8)
4264 {
4265 /* full name doesn't fit, use only the tail */
4266 p = gettail(fname);
4267 fname_size = vim_strsize(p);
4268 }
4269 /* skip characters until the name fits */
4270 while (fname_size > width - 8)
4271 {
4272 p += (*mb_ptr2len)(p);
4273 fname_size = vim_strsize(p);
4274 }
4275
4276 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4277 textline[i] = '=';
4278 textline[i++] = ' ';
4279
4280 STRCPY(textline + i, p);
4281 off = STRLEN(textline);
4282 textline[off] = ' ';
4283 for (i = 1; i < (width - fname_size) / 2; ++i)
4284 textline[off + i] = '=';
4285 textline[off + i] = NUL;
4286
4287 return textline;
4288}
4289
4290/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004291 * Common for "term_dumpdiff()" and "term_dumpload()".
4292 */
4293 static void
4294term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4295{
4296 jobopt_T opt;
4297 buf_T *buf;
4298 char_u buf1[NUMBUFLEN];
4299 char_u buf2[NUMBUFLEN];
4300 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004301 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004302 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004303 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004304 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004305 char_u *textline = NULL;
4306
4307 /* First open the files. If this fails bail out. */
4308 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4309 if (do_diff)
4310 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4311 if (fname1 == NULL || (do_diff && fname2 == NULL))
4312 {
4313 EMSG(_(e_invarg));
4314 return;
4315 }
4316 fd1 = mch_fopen((char *)fname1, READBIN);
4317 if (fd1 == NULL)
4318 {
4319 EMSG2(_(e_notread), fname1);
4320 return;
4321 }
4322 if (do_diff)
4323 {
4324 fd2 = mch_fopen((char *)fname2, READBIN);
4325 if (fd2 == NULL)
4326 {
4327 fclose(fd1);
4328 EMSG2(_(e_notread), fname2);
4329 return;
4330 }
4331 }
4332
4333 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004334 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4335 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4336 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4337 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4338 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004339
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004340 if (opt.jo_term_name == NULL)
4341 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004342 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004343
Bram Moolenaarb571c632018-03-21 22:27:59 +01004344 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004345 if (fname_tofree != NULL)
4346 {
4347 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4348 opt.jo_term_name = fname_tofree;
4349 }
4350 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004351
Bram Moolenaar13568252018-03-16 20:46:58 +01004352 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004353 if (buf != NULL && buf->b_term != NULL)
4354 {
4355 int i;
4356 linenr_T bot_lnum;
4357 linenr_T lnum;
4358 term_T *term = buf->b_term;
4359 int width;
4360 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004361 VTermPos cursor_pos1;
4362 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004363
Bram Moolenaar52acb112018-03-18 19:20:22 +01004364 init_default_colors(term);
4365
Bram Moolenaard96ff162018-02-18 22:13:29 +01004366 rettv->vval.v_number = buf->b_fnum;
4367
4368 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004369 width = read_dump_file(fd1, &cursor_pos1);
4370
4371 /* position the cursor */
4372 if (cursor_pos1.row >= 0)
4373 {
4374 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4375 coladvance(cursor_pos1.col);
4376 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004377
4378 /* Delete the empty line that was in the empty buffer. */
4379 ml_delete(1, FALSE);
4380
4381 /* For term_dumpload() we are done here. */
4382 if (!do_diff)
4383 goto theend;
4384
4385 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4386
Bram Moolenaar4a696342018-04-05 18:45:26 +02004387 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004388 if (textline == NULL)
4389 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004390 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4391 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4392 vim_free(textline);
4393
4394 textline = get_separator(width, fname2);
4395 if (textline == NULL)
4396 goto theend;
4397 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4398 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004399 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004400
4401 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004402 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004403 if (width2 > width)
4404 {
4405 vim_free(textline);
4406 textline = alloc(width2 + 1);
4407 if (textline == NULL)
4408 goto theend;
4409 width = width2;
4410 textline[width] = NUL;
4411 }
4412 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4413
4414 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4415 {
4416 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4417 {
4418 /* bottom part has fewer rows, fill with "-" */
4419 for (i = 0; i < width; ++i)
4420 textline[i] = '-';
4421 }
4422 else
4423 {
4424 char_u *line1;
4425 char_u *line2;
4426 char_u *p1;
4427 char_u *p2;
4428 int col;
4429 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4430 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4431 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4432 ->sb_cells;
4433
4434 /* Make a copy, getting the second line will invalidate it. */
4435 line1 = vim_strsave(ml_get(lnum));
4436 if (line1 == NULL)
4437 break;
4438 p1 = line1;
4439
4440 line2 = ml_get(lnum + bot_lnum);
4441 p2 = line2;
4442 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4443 {
4444 int len1 = utfc_ptr2len(p1);
4445 int len2 = utfc_ptr2len(p2);
4446
4447 textline[col] = ' ';
4448 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004449 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004450 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004451 else if (lnum == cursor_pos1.row + 1
4452 && col == cursor_pos1.col
4453 && (cursor_pos1.row != cursor_pos2.row
4454 || cursor_pos1.col != cursor_pos2.col))
4455 /* cursor in first but not in second */
4456 textline[col] = '>';
4457 else if (lnum == cursor_pos2.row + 1
4458 && col == cursor_pos2.col
4459 && (cursor_pos1.row != cursor_pos2.row
4460 || cursor_pos1.col != cursor_pos2.col))
4461 /* cursor in second but not in first */
4462 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004463 else if (cellattr1 != NULL && cellattr2 != NULL)
4464 {
4465 if ((cellattr1 + col)->width
4466 != (cellattr2 + col)->width)
4467 textline[col] = 'w';
4468 else if (!same_color(&(cellattr1 + col)->fg,
4469 &(cellattr2 + col)->fg))
4470 textline[col] = 'f';
4471 else if (!same_color(&(cellattr1 + col)->bg,
4472 &(cellattr2 + col)->bg))
4473 textline[col] = 'b';
4474 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4475 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4476 textline[col] = 'a';
4477 }
4478 p1 += len1;
4479 p2 += len2;
4480 /* TODO: handle different width */
4481 }
4482 vim_free(line1);
4483
4484 while (col < width)
4485 {
4486 if (*p1 == NUL && *p2 == NUL)
4487 textline[col] = '?';
4488 else if (*p1 == NUL)
4489 {
4490 textline[col] = '+';
4491 p2 += utfc_ptr2len(p2);
4492 }
4493 else
4494 {
4495 textline[col] = '-';
4496 p1 += utfc_ptr2len(p1);
4497 }
4498 ++col;
4499 }
4500 }
4501 if (add_empty_scrollback(term, &term->tl_default_color,
4502 term->tl_top_diff_rows) == OK)
4503 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4504 ++bot_lnum;
4505 }
4506
4507 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4508 {
4509 /* bottom part has more rows, fill with "+" */
4510 for (i = 0; i < width; ++i)
4511 textline[i] = '+';
4512 if (add_empty_scrollback(term, &term->tl_default_color,
4513 term->tl_top_diff_rows) == OK)
4514 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4515 ++lnum;
4516 ++bot_lnum;
4517 }
4518
4519 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004520
4521 /* looks better without wrapping */
4522 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004523 }
4524
4525theend:
4526 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004527 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004528 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004529 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004530 fclose(fd2);
4531}
4532
4533/*
4534 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4535 * bottom files.
4536 * Return FAIL when this is not possible.
4537 */
4538 int
4539term_swap_diff()
4540{
4541 term_T *term = curbuf->b_term;
4542 linenr_T line_count;
4543 linenr_T top_rows;
4544 linenr_T bot_rows;
4545 linenr_T bot_start;
4546 linenr_T lnum;
4547 char_u *p;
4548 sb_line_T *sb_line;
4549
4550 if (term == NULL
4551 || !term_is_finished(curbuf)
4552 || term->tl_top_diff_rows == 0
4553 || term->tl_scrollback.ga_len == 0)
4554 return FAIL;
4555
4556 line_count = curbuf->b_ml.ml_line_count;
4557 top_rows = term->tl_top_diff_rows;
4558 bot_rows = term->tl_bot_diff_rows;
4559 bot_start = line_count - bot_rows;
4560 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4561
4562 /* move lines from top to above the bottom part */
4563 for (lnum = 1; lnum <= top_rows; ++lnum)
4564 {
4565 p = vim_strsave(ml_get(1));
4566 if (p == NULL)
4567 return OK;
4568 ml_append(bot_start, p, 0, FALSE);
4569 ml_delete(1, FALSE);
4570 vim_free(p);
4571 }
4572
4573 /* move lines from bottom to the top */
4574 for (lnum = 1; lnum <= bot_rows; ++lnum)
4575 {
4576 p = vim_strsave(ml_get(bot_start + lnum));
4577 if (p == NULL)
4578 return OK;
4579 ml_delete(bot_start + lnum, FALSE);
4580 ml_append(lnum - 1, p, 0, FALSE);
4581 vim_free(p);
4582 }
4583
4584 if (top_rows == bot_rows)
4585 {
4586 /* rows counts are equal, can swap cell properties */
4587 for (lnum = 0; lnum < top_rows; ++lnum)
4588 {
4589 sb_line_T temp;
4590
4591 temp = *(sb_line + lnum);
4592 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4593 *(sb_line + bot_start + lnum) = temp;
4594 }
4595 }
4596 else
4597 {
4598 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4599 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4600
4601 /* need to copy cell properties into temp memory */
4602 if (temp != NULL)
4603 {
4604 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4605 mch_memmove(term->tl_scrollback.ga_data,
4606 temp + bot_start,
4607 sizeof(sb_line_T) * bot_rows);
4608 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4609 temp + top_rows,
4610 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4611 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4612 + line_count - top_rows,
4613 temp,
4614 sizeof(sb_line_T) * top_rows);
4615 vim_free(temp);
4616 }
4617 }
4618
4619 term->tl_top_diff_rows = bot_rows;
4620 term->tl_bot_diff_rows = top_rows;
4621
4622 update_screen(NOT_VALID);
4623 return OK;
4624}
4625
4626/*
4627 * "term_dumpdiff(filename, filename, options)" function
4628 */
4629 void
4630f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4631{
4632 term_load_dump(argvars, rettv, TRUE);
4633}
4634
4635/*
4636 * "term_dumpload(filename, options)" function
4637 */
4638 void
4639f_term_dumpload(typval_T *argvars, typval_T *rettv)
4640{
4641 term_load_dump(argvars, rettv, FALSE);
4642}
4643
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004644/*
4645 * "term_getaltscreen(buf)" function
4646 */
4647 void
4648f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4649{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004650 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004651
4652 if (buf == NULL)
4653 return;
4654 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4655}
4656
4657/*
4658 * "term_getattr(attr, name)" function
4659 */
4660 void
4661f_term_getattr(typval_T *argvars, typval_T *rettv)
4662{
4663 int attr;
4664 size_t i;
4665 char_u *name;
4666
4667 static struct {
4668 char *name;
4669 int attr;
4670 } attrs[] = {
4671 {"bold", HL_BOLD},
4672 {"italic", HL_ITALIC},
4673 {"underline", HL_UNDERLINE},
4674 {"strike", HL_STRIKETHROUGH},
4675 {"reverse", HL_INVERSE},
4676 };
4677
4678 attr = get_tv_number(&argvars[0]);
4679 name = get_tv_string_chk(&argvars[1]);
4680 if (name == NULL)
4681 return;
4682
4683 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4684 if (STRCMP(name, attrs[i].name) == 0)
4685 {
4686 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4687 break;
4688 }
4689}
4690
4691/*
4692 * "term_getcursor(buf)" function
4693 */
4694 void
4695f_term_getcursor(typval_T *argvars, typval_T *rettv)
4696{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004697 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004698 term_T *term;
4699 list_T *l;
4700 dict_T *d;
4701
4702 if (rettv_list_alloc(rettv) == FAIL)
4703 return;
4704 if (buf == NULL)
4705 return;
4706 term = buf->b_term;
4707
4708 l = rettv->vval.v_list;
4709 list_append_number(l, term->tl_cursor_pos.row + 1);
4710 list_append_number(l, term->tl_cursor_pos.col + 1);
4711
4712 d = dict_alloc();
4713 if (d != NULL)
4714 {
4715 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4716 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4717 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4718 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4719 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4720 ? (char_u *)"" : term->tl_cursor_color);
4721 list_append_dict(l, d);
4722 }
4723}
4724
4725/*
4726 * "term_getjob(buf)" function
4727 */
4728 void
4729f_term_getjob(typval_T *argvars, typval_T *rettv)
4730{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004731 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004732
4733 rettv->v_type = VAR_JOB;
4734 rettv->vval.v_job = NULL;
4735 if (buf == NULL)
4736 return;
4737
4738 rettv->vval.v_job = buf->b_term->tl_job;
4739 if (rettv->vval.v_job != NULL)
4740 ++rettv->vval.v_job->jv_refcount;
4741}
4742
4743 static int
4744get_row_number(typval_T *tv, term_T *term)
4745{
4746 if (tv->v_type == VAR_STRING
4747 && tv->vval.v_string != NULL
4748 && STRCMP(tv->vval.v_string, ".") == 0)
4749 return term->tl_cursor_pos.row;
4750 return (int)get_tv_number(tv) - 1;
4751}
4752
4753/*
4754 * "term_getline(buf, row)" function
4755 */
4756 void
4757f_term_getline(typval_T *argvars, typval_T *rettv)
4758{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004759 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004760 term_T *term;
4761 int row;
4762
4763 rettv->v_type = VAR_STRING;
4764 if (buf == NULL)
4765 return;
4766 term = buf->b_term;
4767 row = get_row_number(&argvars[1], term);
4768
4769 if (term->tl_vterm == NULL)
4770 {
4771 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4772
4773 /* vterm is finished, get the text from the buffer */
4774 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4775 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4776 }
4777 else
4778 {
4779 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4780 VTermRect rect;
4781 int len;
4782 char_u *p;
4783
4784 if (row < 0 || row >= term->tl_rows)
4785 return;
4786 len = term->tl_cols * MB_MAXBYTES + 1;
4787 p = alloc(len);
4788 if (p == NULL)
4789 return;
4790 rettv->vval.v_string = p;
4791
4792 rect.start_col = 0;
4793 rect.end_col = term->tl_cols;
4794 rect.start_row = row;
4795 rect.end_row = row + 1;
4796 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4797 }
4798}
4799
4800/*
4801 * "term_getscrolled(buf)" function
4802 */
4803 void
4804f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4805{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004806 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004807
4808 if (buf == NULL)
4809 return;
4810 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4811}
4812
4813/*
4814 * "term_getsize(buf)" function
4815 */
4816 void
4817f_term_getsize(typval_T *argvars, typval_T *rettv)
4818{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004819 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004820 list_T *l;
4821
4822 if (rettv_list_alloc(rettv) == FAIL)
4823 return;
4824 if (buf == NULL)
4825 return;
4826
4827 l = rettv->vval.v_list;
4828 list_append_number(l, buf->b_term->tl_rows);
4829 list_append_number(l, buf->b_term->tl_cols);
4830}
4831
4832/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004833 * "term_setsize(buf, rows, cols)" function
4834 */
4835 void
4836f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4837{
4838 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4839 term_T *term;
4840 varnumber_T rows, cols;
4841
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004842 if (buf == NULL)
4843 {
4844 EMSG(_("E955: Not a terminal buffer"));
4845 return;
4846 }
4847 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004848 return;
4849 term = buf->b_term;
4850 rows = get_tv_number(&argvars[1]);
4851 rows = rows <= 0 ? term->tl_rows : rows;
4852 cols = get_tv_number(&argvars[2]);
4853 cols = cols <= 0 ? term->tl_cols : cols;
4854 vterm_set_size(term->tl_vterm, rows, cols);
4855 /* handle_resize() will resize the windows */
4856
4857 /* Get and remember the size we ended up with. Update the pty. */
4858 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4859 term_report_winsize(term, term->tl_rows, term->tl_cols);
4860}
4861
4862/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004863 * "term_getstatus(buf)" function
4864 */
4865 void
4866f_term_getstatus(typval_T *argvars, typval_T *rettv)
4867{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004868 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004869 term_T *term;
4870 char_u val[100];
4871
4872 rettv->v_type = VAR_STRING;
4873 if (buf == NULL)
4874 return;
4875 term = buf->b_term;
4876
4877 if (term_job_running(term))
4878 STRCPY(val, "running");
4879 else
4880 STRCPY(val, "finished");
4881 if (term->tl_normal_mode)
4882 STRCAT(val, ",normal");
4883 rettv->vval.v_string = vim_strsave(val);
4884}
4885
4886/*
4887 * "term_gettitle(buf)" function
4888 */
4889 void
4890f_term_gettitle(typval_T *argvars, typval_T *rettv)
4891{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004892 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004893
4894 rettv->v_type = VAR_STRING;
4895 if (buf == NULL)
4896 return;
4897
4898 if (buf->b_term->tl_title != NULL)
4899 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4900}
4901
4902/*
4903 * "term_gettty(buf)" function
4904 */
4905 void
4906f_term_gettty(typval_T *argvars, typval_T *rettv)
4907{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004908 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004909 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004910 int num = 0;
4911
4912 rettv->v_type = VAR_STRING;
4913 if (buf == NULL)
4914 return;
4915 if (argvars[1].v_type != VAR_UNKNOWN)
4916 num = get_tv_number(&argvars[1]);
4917
4918 switch (num)
4919 {
4920 case 0:
4921 if (buf->b_term->tl_job != NULL)
4922 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004923 break;
4924 case 1:
4925 if (buf->b_term->tl_job != NULL)
4926 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004927 break;
4928 default:
4929 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4930 return;
4931 }
4932 if (p != NULL)
4933 rettv->vval.v_string = vim_strsave(p);
4934}
4935
4936/*
4937 * "term_list()" function
4938 */
4939 void
4940f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4941{
4942 term_T *tp;
4943 list_T *l;
4944
4945 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4946 return;
4947
4948 l = rettv->vval.v_list;
4949 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4950 if (tp != NULL && tp->tl_buffer != NULL)
4951 if (list_append_number(l,
4952 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4953 return;
4954}
4955
4956/*
4957 * "term_scrape(buf, row)" function
4958 */
4959 void
4960f_term_scrape(typval_T *argvars, typval_T *rettv)
4961{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004962 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004963 VTermScreen *screen = NULL;
4964 VTermPos pos;
4965 list_T *l;
4966 term_T *term;
4967 char_u *p;
4968 sb_line_T *line;
4969
4970 if (rettv_list_alloc(rettv) == FAIL)
4971 return;
4972 if (buf == NULL)
4973 return;
4974 term = buf->b_term;
4975
4976 l = rettv->vval.v_list;
4977 pos.row = get_row_number(&argvars[1], term);
4978
4979 if (term->tl_vterm != NULL)
4980 {
4981 screen = vterm_obtain_screen(term->tl_vterm);
4982 p = NULL;
4983 line = NULL;
4984 }
4985 else
4986 {
4987 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4988
4989 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4990 return;
4991 p = ml_get_buf(buf, lnum + 1, FALSE);
4992 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4993 }
4994
4995 for (pos.col = 0; pos.col < term->tl_cols; )
4996 {
4997 dict_T *dcell;
4998 int width;
4999 VTermScreenCellAttrs attrs;
5000 VTermColor fg, bg;
5001 char_u rgb[8];
5002 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5003 int off = 0;
5004 int i;
5005
5006 if (screen == NULL)
5007 {
5008 cellattr_T *cellattr;
5009 int len;
5010
5011 /* vterm has finished, get the cell from scrollback */
5012 if (pos.col >= line->sb_cols)
5013 break;
5014 cellattr = line->sb_cells + pos.col;
5015 width = cellattr->width;
5016 attrs = cellattr->attrs;
5017 fg = cellattr->fg;
5018 bg = cellattr->bg;
5019 len = MB_PTR2LEN(p);
5020 mch_memmove(mbs, p, len);
5021 mbs[len] = NUL;
5022 p += len;
5023 }
5024 else
5025 {
5026 VTermScreenCell cell;
5027 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5028 break;
5029 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5030 {
5031 if (cell.chars[i] == 0)
5032 break;
5033 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5034 }
5035 mbs[off] = NUL;
5036 width = cell.width;
5037 attrs = cell.attrs;
5038 fg = cell.fg;
5039 bg = cell.bg;
5040 }
5041 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005042 if (dcell == NULL)
5043 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005044 list_append_dict(l, dcell);
5045
5046 dict_add_nr_str(dcell, "chars", 0, mbs);
5047
5048 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5049 fg.red, fg.green, fg.blue);
5050 dict_add_nr_str(dcell, "fg", 0, rgb);
5051 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5052 bg.red, bg.green, bg.blue);
5053 dict_add_nr_str(dcell, "bg", 0, rgb);
5054
5055 dict_add_nr_str(dcell, "attr",
5056 cell2attr(attrs, fg, bg), NULL);
5057 dict_add_nr_str(dcell, "width", width, NULL);
5058
5059 ++pos.col;
5060 if (width == 2)
5061 ++pos.col;
5062 }
5063}
5064
5065/*
5066 * "term_sendkeys(buf, keys)" function
5067 */
5068 void
5069f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5070{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005071 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005072 char_u *msg;
5073 term_T *term;
5074
5075 rettv->v_type = VAR_UNKNOWN;
5076 if (buf == NULL)
5077 return;
5078
5079 msg = get_tv_string_chk(&argvars[1]);
5080 if (msg == NULL)
5081 return;
5082 term = buf->b_term;
5083 if (term->tl_vterm == NULL)
5084 return;
5085
5086 while (*msg != NUL)
5087 {
5088 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005089 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005090 }
5091}
5092
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005093#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5094/*
5095 * "term_getansicolors(buf)" function
5096 */
5097 void
5098f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5099{
5100 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5101 term_T *term;
5102 VTermState *state;
5103 VTermColor color;
5104 char_u hexbuf[10];
5105 int index;
5106 list_T *list;
5107
5108 if (rettv_list_alloc(rettv) == FAIL)
5109 return;
5110
5111 if (buf == NULL)
5112 return;
5113 term = buf->b_term;
5114 if (term->tl_vterm == NULL)
5115 return;
5116
5117 list = rettv->vval.v_list;
5118 state = vterm_obtain_state(term->tl_vterm);
5119 for (index = 0; index < 16; index++)
5120 {
5121 vterm_state_get_palette_color(state, index, &color);
5122 sprintf((char *)hexbuf, "#%02x%02x%02x",
5123 color.red, color.green, color.blue);
5124 if (list_append_string(list, hexbuf, 7) == FAIL)
5125 return;
5126 }
5127}
5128
5129/*
5130 * "term_setansicolors(buf, list)" function
5131 */
5132 void
5133f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5134{
5135 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5136 term_T *term;
5137
5138 if (buf == NULL)
5139 return;
5140 term = buf->b_term;
5141 if (term->tl_vterm == NULL)
5142 return;
5143
5144 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5145 {
5146 EMSG(_(e_listreq));
5147 return;
5148 }
5149
5150 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5151 EMSG(_(e_invarg));
5152}
5153#endif
5154
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005155/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005156 * "term_setrestore(buf, command)" function
5157 */
5158 void
5159f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5160{
5161#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005162 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005163 term_T *term;
5164 char_u *cmd;
5165
5166 if (buf == NULL)
5167 return;
5168 term = buf->b_term;
5169 vim_free(term->tl_command);
5170 cmd = get_tv_string_chk(&argvars[1]);
5171 if (cmd != NULL)
5172 term->tl_command = vim_strsave(cmd);
5173 else
5174 term->tl_command = NULL;
5175#endif
5176}
5177
5178/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005179 * "term_setkill(buf, how)" function
5180 */
5181 void
5182f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5183{
5184 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5185 term_T *term;
5186 char_u *how;
5187
5188 if (buf == NULL)
5189 return;
5190 term = buf->b_term;
5191 vim_free(term->tl_kill);
5192 how = get_tv_string_chk(&argvars[1]);
5193 if (how != NULL)
5194 term->tl_kill = vim_strsave(how);
5195 else
5196 term->tl_kill = NULL;
5197}
5198
5199/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005200 * "term_start(command, options)" function
5201 */
5202 void
5203f_term_start(typval_T *argvars, typval_T *rettv)
5204{
5205 jobopt_T opt;
5206 buf_T *buf;
5207
5208 init_job_options(&opt);
5209 if (argvars[1].v_type != VAR_UNKNOWN
5210 && get_job_options(&argvars[1], &opt,
5211 JO_TIMEOUT_ALL + JO_STOPONEXIT
5212 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5213 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5214 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5215 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005216 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005217 + JO2_NORESTORE + JO2_TERM_KILL
5218 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005219 return;
5220
Bram Moolenaar13568252018-03-16 20:46:58 +01005221 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005222
5223 if (buf != NULL && buf->b_term != NULL)
5224 rettv->vval.v_number = buf->b_fnum;
5225}
5226
5227/*
5228 * "term_wait" function
5229 */
5230 void
5231f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5232{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005233 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005234
5235 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005236 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005237 if (buf->b_term->tl_job == NULL)
5238 {
5239 ch_log(NULL, "term_wait(): no job to wait for");
5240 return;
5241 }
5242 if (buf->b_term->tl_job->jv_channel == NULL)
5243 /* channel is closed, nothing to do */
5244 return;
5245
5246 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005247 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5249 {
5250 /* The job is dead, keep reading channel I/O until the channel is
5251 * closed. buf->b_term may become NULL if the terminal was closed while
5252 * waiting. */
5253 ch_log(NULL, "term_wait(): waiting for channel to close");
5254 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5255 {
5256 mch_check_messages();
5257 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005258 if (!buf_valid(buf))
5259 /* If the terminal is closed when the channel is closed the
5260 * buffer disappears. */
5261 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005262 ui_delay(10L, FALSE);
5263 }
5264 mch_check_messages();
5265 parse_queued_messages();
5266 }
5267 else
5268 {
5269 long wait = 10L;
5270
5271 mch_check_messages();
5272 parse_queued_messages();
5273
5274 /* Wait for some time for any channel I/O. */
5275 if (argvars[1].v_type != VAR_UNKNOWN)
5276 wait = get_tv_number(&argvars[1]);
5277 ui_delay(wait, TRUE);
5278 mch_check_messages();
5279
5280 /* Flushing messages on channels is hopefully sufficient.
5281 * TODO: is there a better way? */
5282 parse_queued_messages();
5283 }
5284}
5285
5286/*
5287 * Called when a channel has sent all the lines to a terminal.
5288 * Send a CTRL-D to mark the end of the text.
5289 */
5290 void
5291term_send_eof(channel_T *ch)
5292{
5293 term_T *term;
5294
5295 for (term = first_term; term != NULL; term = term->tl_next)
5296 if (term->tl_job == ch->ch_job)
5297 {
5298 if (term->tl_eof_chars != NULL)
5299 {
5300 channel_send(ch, PART_IN, term->tl_eof_chars,
5301 (int)STRLEN(term->tl_eof_chars), NULL);
5302 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5303 }
5304# ifdef WIN3264
5305 else
5306 /* Default: CTRL-D */
5307 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5308# endif
5309 }
5310}
5311
5312# if defined(WIN3264) || defined(PROTO)
5313
5314/**************************************
5315 * 2. MS-Windows implementation.
5316 */
5317
5318# ifndef PROTO
5319
5320#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5321#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005322#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005323
5324void* (*winpty_config_new)(UINT64, void*);
5325void* (*winpty_open)(void*, void*);
5326void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5327BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5328void (*winpty_config_set_mouse_mode)(void*, int);
5329void (*winpty_config_set_initial_size)(void*, int, int);
5330LPCWSTR (*winpty_conin_name)(void*);
5331LPCWSTR (*winpty_conout_name)(void*);
5332LPCWSTR (*winpty_conerr_name)(void*);
5333void (*winpty_free)(void*);
5334void (*winpty_config_free)(void*);
5335void (*winpty_spawn_config_free)(void*);
5336void (*winpty_error_free)(void*);
5337LPCWSTR (*winpty_error_msg)(void*);
5338BOOL (*winpty_set_size)(void*, int, int, void*);
5339HANDLE (*winpty_agent_process)(void*);
5340
5341#define WINPTY_DLL "winpty.dll"
5342
5343static HINSTANCE hWinPtyDLL = NULL;
5344# endif
5345
5346 static int
5347dyn_winpty_init(int verbose)
5348{
5349 int i;
5350 static struct
5351 {
5352 char *name;
5353 FARPROC *ptr;
5354 } winpty_entry[] =
5355 {
5356 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5357 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5358 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5359 {"winpty_config_set_mouse_mode",
5360 (FARPROC*)&winpty_config_set_mouse_mode},
5361 {"winpty_config_set_initial_size",
5362 (FARPROC*)&winpty_config_set_initial_size},
5363 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5364 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5365 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5366 {"winpty_free", (FARPROC*)&winpty_free},
5367 {"winpty_open", (FARPROC*)&winpty_open},
5368 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5369 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5370 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5371 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5372 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5373 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5374 {NULL, NULL}
5375 };
5376
5377 /* No need to initialize twice. */
5378 if (hWinPtyDLL)
5379 return OK;
5380 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5381 * winpty.dll. */
5382 if (*p_winptydll != NUL)
5383 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5384 if (!hWinPtyDLL)
5385 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5386 if (!hWinPtyDLL)
5387 {
5388 if (verbose)
5389 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5390 : (char_u *)WINPTY_DLL);
5391 return FAIL;
5392 }
5393 for (i = 0; winpty_entry[i].name != NULL
5394 && winpty_entry[i].ptr != NULL; ++i)
5395 {
5396 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5397 winpty_entry[i].name)) == NULL)
5398 {
5399 if (verbose)
5400 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5401 return FAIL;
5402 }
5403 }
5404
5405 return OK;
5406}
5407
5408/*
5409 * Create a new terminal of "rows" by "cols" cells.
5410 * Store a reference in "term".
5411 * Return OK or FAIL.
5412 */
5413 static int
5414term_and_job_init(
5415 term_T *term,
5416 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005417 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005418 jobopt_T *opt,
5419 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005420{
5421 WCHAR *cmd_wchar = NULL;
5422 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005423 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005424 channel_T *channel = NULL;
5425 job_T *job = NULL;
5426 DWORD error;
5427 HANDLE jo = NULL;
5428 HANDLE child_process_handle;
5429 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005430 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005431 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005432 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005433 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005434
5435 if (dyn_winpty_init(TRUE) == FAIL)
5436 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005437 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5438 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005439
5440 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005441 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005442 cmd = argvar->vval.v_string;
5443 }
5444 else if (argvar->v_type == VAR_LIST)
5445 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005446 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005447 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005448 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005449 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005450 if (cmd == NULL || *cmd == NUL)
5451 {
5452 EMSG(_(e_invarg));
5453 goto failed;
5454 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005455
5456 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005457 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005458 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005459 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460 if (opt->jo_cwd != NULL)
5461 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005462
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005463 win32_build_env(opt->jo_env, &ga_env, TRUE);
5464 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005465
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005466 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5467 if (term->tl_winpty_config == NULL)
5468 goto failed;
5469
5470 winpty_config_set_mouse_mode(term->tl_winpty_config,
5471 WINPTY_MOUSE_MODE_FORCE);
5472 winpty_config_set_initial_size(term->tl_winpty_config,
5473 term->tl_cols, term->tl_rows);
5474 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5475 if (term->tl_winpty == NULL)
5476 goto failed;
5477
5478 spawn_config = winpty_spawn_config_new(
5479 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5480 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5481 NULL,
5482 cmd_wchar,
5483 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005484 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485 &winpty_err);
5486 if (spawn_config == NULL)
5487 goto failed;
5488
5489 channel = add_channel();
5490 if (channel == NULL)
5491 goto failed;
5492
5493 job = job_alloc();
5494 if (job == NULL)
5495 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005496 if (argvar->v_type == VAR_STRING)
5497 {
5498 int argc;
5499
5500 build_argv_from_string(cmd, &job->jv_argv, &argc);
5501 }
5502 else
5503 {
5504 int argc;
5505
5506 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5507 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005508
5509 if (opt->jo_set & JO_IN_BUF)
5510 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5511
5512 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5513 &child_thread_handle, &error, &winpty_err))
5514 goto failed;
5515
5516 channel_set_pipes(channel,
5517 (sock_T)CreateFileW(
5518 winpty_conin_name(term->tl_winpty),
5519 GENERIC_WRITE, 0, NULL,
5520 OPEN_EXISTING, 0, NULL),
5521 (sock_T)CreateFileW(
5522 winpty_conout_name(term->tl_winpty),
5523 GENERIC_READ, 0, NULL,
5524 OPEN_EXISTING, 0, NULL),
5525 (sock_T)CreateFileW(
5526 winpty_conerr_name(term->tl_winpty),
5527 GENERIC_READ, 0, NULL,
5528 OPEN_EXISTING, 0, NULL));
5529
5530 /* Write lines with CR instead of NL. */
5531 channel->ch_write_text_mode = TRUE;
5532
5533 jo = CreateJobObject(NULL, NULL);
5534 if (jo == NULL)
5535 goto failed;
5536
5537 if (!AssignProcessToJobObject(jo, child_process_handle))
5538 {
5539 /* Failed, switch the way to terminate process with TerminateProcess. */
5540 CloseHandle(jo);
5541 jo = NULL;
5542 }
5543
5544 winpty_spawn_config_free(spawn_config);
5545 vim_free(cmd_wchar);
5546 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005547 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005548
5549 create_vterm(term, term->tl_rows, term->tl_cols);
5550
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005551#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5552 if (opt->jo_set2 & JO2_ANSI_COLORS)
5553 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5554 else
5555 init_vterm_ansi_colors(term->tl_vterm);
5556#endif
5557
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005558 channel_set_job(channel, job, opt);
5559 job_set_options(job, opt);
5560
5561 job->jv_channel = channel;
5562 job->jv_proc_info.hProcess = child_process_handle;
5563 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5564 job->jv_job_object = jo;
5565 job->jv_status = JOB_STARTED;
5566 job->jv_tty_in = utf16_to_enc(
5567 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5568 job->jv_tty_out = utf16_to_enc(
5569 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5570 ++job->jv_refcount;
5571 term->tl_job = job;
5572
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005573 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5574 * open the file here and handle it in. opt->jo_io was changed in
5575 * setup_job_options(), use the original flags here. */
5576 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5577 {
5578 char_u *fname = opt->jo_io_name[PART_OUT];
5579
5580 ch_log(channel, "Opening output file %s", fname);
5581 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5582 if (term->tl_out_fd == NULL)
5583 EMSG2(_(e_notopen), fname);
5584 }
5585
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005586 return OK;
5587
5588failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005589 ga_clear(&ga_cmd);
5590 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005591 vim_free(cmd_wchar);
5592 vim_free(cwd_wchar);
5593 if (spawn_config != NULL)
5594 winpty_spawn_config_free(spawn_config);
5595 if (channel != NULL)
5596 channel_clear(channel);
5597 if (job != NULL)
5598 {
5599 job->jv_channel = NULL;
5600 job_cleanup(job);
5601 }
5602 term->tl_job = NULL;
5603 if (jo != NULL)
5604 CloseHandle(jo);
5605 if (term->tl_winpty != NULL)
5606 winpty_free(term->tl_winpty);
5607 term->tl_winpty = NULL;
5608 if (term->tl_winpty_config != NULL)
5609 winpty_config_free(term->tl_winpty_config);
5610 term->tl_winpty_config = NULL;
5611 if (winpty_err != NULL)
5612 {
5613 char_u *msg = utf16_to_enc(
5614 (short_u *)winpty_error_msg(winpty_err), NULL);
5615
5616 EMSG(msg);
5617 winpty_error_free(winpty_err);
5618 }
5619 return FAIL;
5620}
5621
5622 static int
5623create_pty_only(term_T *term, jobopt_T *options)
5624{
5625 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5626 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5627 char in_name[80], out_name[80];
5628 channel_T *channel = NULL;
5629
5630 create_vterm(term, term->tl_rows, term->tl_cols);
5631
5632 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5633 GetCurrentProcessId(),
5634 curbuf->b_fnum);
5635 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5636 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5637 PIPE_UNLIMITED_INSTANCES,
5638 0, 0, NMPWAIT_NOWAIT, NULL);
5639 if (hPipeIn == INVALID_HANDLE_VALUE)
5640 goto failed;
5641
5642 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5643 GetCurrentProcessId(),
5644 curbuf->b_fnum);
5645 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5646 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5647 PIPE_UNLIMITED_INSTANCES,
5648 0, 0, 0, NULL);
5649 if (hPipeOut == INVALID_HANDLE_VALUE)
5650 goto failed;
5651
5652 ConnectNamedPipe(hPipeIn, NULL);
5653 ConnectNamedPipe(hPipeOut, NULL);
5654
5655 term->tl_job = job_alloc();
5656 if (term->tl_job == NULL)
5657 goto failed;
5658 ++term->tl_job->jv_refcount;
5659
5660 /* behave like the job is already finished */
5661 term->tl_job->jv_status = JOB_FINISHED;
5662
5663 channel = add_channel();
5664 if (channel == NULL)
5665 goto failed;
5666 term->tl_job->jv_channel = channel;
5667 channel->ch_keep_open = TRUE;
5668 channel->ch_named_pipe = TRUE;
5669
5670 channel_set_pipes(channel,
5671 (sock_T)hPipeIn,
5672 (sock_T)hPipeOut,
5673 (sock_T)hPipeOut);
5674 channel_set_job(channel, term->tl_job, options);
5675 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5676 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5677
5678 return OK;
5679
5680failed:
5681 if (hPipeIn != NULL)
5682 CloseHandle(hPipeIn);
5683 if (hPipeOut != NULL)
5684 CloseHandle(hPipeOut);
5685 return FAIL;
5686}
5687
5688/*
5689 * Free the terminal emulator part of "term".
5690 */
5691 static void
5692term_free_vterm(term_T *term)
5693{
5694 if (term->tl_winpty != NULL)
5695 winpty_free(term->tl_winpty);
5696 term->tl_winpty = NULL;
5697 if (term->tl_winpty_config != NULL)
5698 winpty_config_free(term->tl_winpty_config);
5699 term->tl_winpty_config = NULL;
5700 if (term->tl_vterm != NULL)
5701 vterm_free(term->tl_vterm);
5702 term->tl_vterm = NULL;
5703}
5704
5705/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005706 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005707 */
5708 static void
5709term_report_winsize(term_T *term, int rows, int cols)
5710{
5711 if (term->tl_winpty)
5712 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5713}
5714
5715 int
5716terminal_enabled(void)
5717{
5718 return dyn_winpty_init(FALSE) == OK;
5719}
5720
5721# else
5722
5723/**************************************
5724 * 3. Unix-like implementation.
5725 */
5726
5727/*
5728 * Create a new terminal of "rows" by "cols" cells.
5729 * Start job for "cmd".
5730 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005731 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005732 * Return OK or FAIL.
5733 */
5734 static int
5735term_and_job_init(
5736 term_T *term,
5737 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005738 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005739 jobopt_T *opt,
5740 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005741{
5742 create_vterm(term, term->tl_rows, term->tl_cols);
5743
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005744#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5745 if (opt->jo_set2 & JO2_ANSI_COLORS)
5746 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5747 else
5748 init_vterm_ansi_colors(term->tl_vterm);
5749#endif
5750
Bram Moolenaar13568252018-03-16 20:46:58 +01005751 /* This may change a string in "argvar". */
5752 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005753 if (term->tl_job != NULL)
5754 ++term->tl_job->jv_refcount;
5755
5756 return term->tl_job != NULL
5757 && term->tl_job->jv_channel != NULL
5758 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5759}
5760
5761 static int
5762create_pty_only(term_T *term, jobopt_T *opt)
5763{
5764 create_vterm(term, term->tl_rows, term->tl_cols);
5765
5766 term->tl_job = job_alloc();
5767 if (term->tl_job == NULL)
5768 return FAIL;
5769 ++term->tl_job->jv_refcount;
5770
5771 /* behave like the job is already finished */
5772 term->tl_job->jv_status = JOB_FINISHED;
5773
5774 return mch_create_pty_channel(term->tl_job, opt);
5775}
5776
5777/*
5778 * Free the terminal emulator part of "term".
5779 */
5780 static void
5781term_free_vterm(term_T *term)
5782{
5783 if (term->tl_vterm != NULL)
5784 vterm_free(term->tl_vterm);
5785 term->tl_vterm = NULL;
5786}
5787
5788/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005789 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005790 */
5791 static void
5792term_report_winsize(term_T *term, int rows, int cols)
5793{
5794 /* Use an ioctl() to report the new window size to the job. */
5795 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5796 {
5797 int fd = -1;
5798 int part;
5799
5800 for (part = PART_OUT; part < PART_COUNT; ++part)
5801 {
5802 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5803 if (isatty(fd))
5804 break;
5805 }
5806 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5807 mch_signal_job(term->tl_job, (char_u *)"winch");
5808 }
5809}
5810
5811# endif
5812
5813#endif /* FEAT_TERMINAL */