blob: 8deac9da867de9f4f256c0904f0d34874b3d9e38 [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 Moolenaar1dd98332018-03-16 22:54:53 +0100106 int tl_finish;
107#define TL_FINISH_UNSET NUL
108#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
109#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
110#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111 char_u *tl_opencmd;
112 char_u *tl_eof_chars;
113
114#ifdef WIN3264
115 void *tl_winpty_config;
116 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200117
118 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200119#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100120#if defined(FEAT_SESSION)
121 char_u *tl_command;
122#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100123 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124
125 /* last known vterm size */
126 int tl_rows;
127 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200128
129 char_u *tl_title; /* NULL or allocated */
130 char_u *tl_status_text; /* NULL or allocated */
131
132 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200133 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200135 int tl_dirty_snapshot; /* text updated after making snapshot */
136#ifdef FEAT_TIMERS
137 int tl_timer_set;
138 proftime_T tl_timer_due;
139#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200140 int tl_postponed_scroll; /* to be scrolled up */
141
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200142 garray_T tl_scrollback;
143 int tl_scrollback_scrolled;
144 cellattr_T tl_default_color;
145
Bram Moolenaard96ff162018-02-18 22:13:29 +0100146 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
147 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
148
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200149 VTermPos tl_cursor_pos;
150 int tl_cursor_visible;
151 int tl_cursor_blink;
152 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
153 char_u *tl_cursor_color; /* NULL or allocated */
154
155 int tl_using_altscreen;
156};
157
158#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
159#define TMODE_LOOP 2 /* CTRL-W N used */
160
161/*
162 * List of all active terminals.
163 */
164static term_T *first_term = NULL;
165
166/* Terminal active in terminal_loop(). */
167static term_T *in_terminal_loop = NULL;
168
169#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
170#define KEY_BUF_LEN 200
171
172/*
173 * Functions with separate implementation for MS-Windows and Unix-like systems.
174 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200175static 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 +0200176static int create_pty_only(term_T *term, jobopt_T *opt);
177static void term_report_winsize(term_T *term, int rows, int cols);
178static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100179#ifdef FEAT_GUI
180static void update_system_term(term_T *term);
181#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100183/* The character that we know (or assume) that the terminal expects for the
184 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200185static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100187/* "Terminal" highlight group colors. */
188static int term_default_cterm_fg = -1;
189static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
Bram Moolenaard317b382018-02-08 22:33:31 +0100191/* Store the last set and the desired cursor properties, so that we only update
192 * them when needed. Doing it unnecessary may result in flicker. */
193static char_u *last_set_cursor_color = (char_u *)"";
194static char_u *desired_cursor_color = (char_u *)"";
195static int last_set_cursor_shape = -1;
196static int desired_cursor_shape = -1;
197static int last_set_cursor_blink = -1;
198static int desired_cursor_blink = -1;
199
200
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200201/**************************************
202 * 1. Generic code for all systems.
203 */
204
205/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200206 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200207 * current window.
208 * Sets "rows" and/or "cols" to zero when it should follow the window size.
209 * Return TRUE if the size is the minimum size: "24*80".
210 */
211 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200212parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200213{
214 int minsize = FALSE;
215
216 *rows = 0;
217 *cols = 0;
218
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200219 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200220 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200221 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200222
223 /* Syntax of value was already checked when it's set. */
224 if (p == NULL)
225 {
226 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200227 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200228 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200229 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200230 *cols = atoi((char *)p + 1);
231 }
232 return minsize;
233}
234
235/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200236 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200237 */
238 static void
239set_term_and_win_size(term_T *term)
240{
Bram Moolenaar13568252018-03-16 20:46:58 +0100241#ifdef FEAT_GUI
242 if (term->tl_system)
243 {
244 /* Use the whole screen for the system command. However, it will start
245 * at the command line and scroll up as needed, using tl_toprow. */
246 term->tl_rows = Rows;
247 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200248 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100249 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100250#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200251 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200252 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200253 if (term->tl_rows != 0)
254 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
255 if (term->tl_cols != 0)
256 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200257 }
258 if (term->tl_rows == 0)
259 term->tl_rows = curwin->w_height;
260 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200261 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200262 if (term->tl_cols == 0)
263 term->tl_cols = curwin->w_width;
264 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200265 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200266}
267
268/*
269 * Initialize job options for a terminal job.
270 * Caller may overrule some of them.
271 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100272 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200273init_job_options(jobopt_T *opt)
274{
275 clear_job_options(opt);
276
277 opt->jo_mode = MODE_RAW;
278 opt->jo_out_mode = MODE_RAW;
279 opt->jo_err_mode = MODE_RAW;
280 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
281}
282
283/*
284 * Set job options mandatory for a terminal job.
285 */
286 static void
287setup_job_options(jobopt_T *opt, int rows, int cols)
288{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200289#ifndef WIN3264
290 /* Win32: Redirecting the job output won't work, thus always connect stdout
291 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200292 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200293#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200294 {
295 /* Connect stdout to the terminal. */
296 opt->jo_io[PART_OUT] = JIO_BUFFER;
297 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
298 opt->jo_modifiable[PART_OUT] = 0;
299 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
300 }
301
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200302#ifndef WIN3264
303 /* Win32: Redirecting the job output won't work, thus always connect stderr
304 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200306#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200307 {
308 /* Connect stderr to the terminal. */
309 opt->jo_io[PART_ERR] = JIO_BUFFER;
310 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
311 opt->jo_modifiable[PART_ERR] = 0;
312 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
313 }
314
315 opt->jo_pty = TRUE;
316 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
317 opt->jo_term_rows = rows;
318 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
319 opt->jo_term_cols = cols;
320}
321
322/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100323 * Close a terminal buffer (and its window). Used when creating the terminal
324 * fails.
325 */
326 static void
327term_close_buffer(buf_T *buf, buf_T *old_curbuf)
328{
329 free_terminal(buf);
330 if (old_curbuf != NULL)
331 {
332 --curbuf->b_nwindows;
333 curbuf = old_curbuf;
334 curwin->w_buffer = curbuf;
335 ++curbuf->b_nwindows;
336 }
337
338 /* Wiping out the buffer will also close the window and call
339 * free_terminal(). */
340 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
341}
342
343/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100345 * Use either "argvar" or "argv", the other must be NULL.
346 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
347 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200348 * Returns NULL when failed.
349 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100350 buf_T *
351term_start(
352 typval_T *argvar,
353 char **argv,
354 jobopt_T *opt,
355 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200356{
357 exarg_T split_ea;
358 win_T *old_curwin = curwin;
359 term_T *term;
360 buf_T *old_curbuf = NULL;
361 int res;
362 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100363 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200364 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200365
366 if (check_restricted() || check_secure())
367 return NULL;
368
369 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
370 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
371 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
372 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
373 {
374 EMSG(_(e_invarg));
375 return NULL;
376 }
377
378 term = (term_T *)alloc_clear(sizeof(term_T));
379 if (term == NULL)
380 return NULL;
381 term->tl_dirty_row_end = MAX_ROW;
382 term->tl_cursor_visible = TRUE;
383 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
384 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100385#ifdef FEAT_GUI
386 term->tl_system = (flags & TERM_START_SYSTEM);
387#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200388 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
389
390 vim_memset(&split_ea, 0, sizeof(split_ea));
391 if (opt->jo_curwin)
392 {
393 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200395 {
396 no_write_message();
397 vim_free(term);
398 return NULL;
399 }
400 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100401 ECMD_HIDE
402 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
403 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200404 {
405 vim_free(term);
406 return NULL;
407 }
408 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100409 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410 {
411 buf_T *buf;
412
413 /* Create a new buffer without a window. Make it the current buffer for
414 * a moment to be able to do the initialisations. */
415 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
416 BLN_NEW | BLN_LISTED);
417 if (buf == NULL || ml_open(buf) == FAIL)
418 {
419 vim_free(term);
420 return NULL;
421 }
422 old_curbuf = curbuf;
423 --curbuf->b_nwindows;
424 curbuf = buf;
425 curwin->w_buffer = buf;
426 ++curbuf->b_nwindows;
427 }
428 else
429 {
430 /* Open a new window or tab. */
431 split_ea.cmdidx = CMD_new;
432 split_ea.cmd = (char_u *)"new";
433 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100434 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200435 {
436 split_ea.line2 = opt->jo_term_rows;
437 split_ea.addr_count = 1;
438 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100439 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440 {
441 split_ea.line2 = opt->jo_term_cols;
442 split_ea.addr_count = 1;
443 }
444
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100445 if (vertical)
446 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200447 ex_splitview(&split_ea);
448 if (curwin == old_curwin)
449 {
450 /* split failed */
451 vim_free(term);
452 return NULL;
453 }
454 }
455 term->tl_buffer = curbuf;
456 curbuf->b_term = term;
457
458 if (!opt->jo_hidden)
459 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100460 /* Only one size was taken care of with :new, do the other one. With
461 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100462 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100464 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200465 win_setwidth(opt->jo_term_cols);
466 }
467
468 /* Link the new terminal in the list of active terminals. */
469 term->tl_next = first_term;
470 first_term = term;
471
472 if (opt->jo_term_name != NULL)
473 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100474 else if (argv != NULL)
475 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200476 else
477 {
478 int i;
479 size_t len;
480 char_u *cmd, *p;
481
482 if (argvar->v_type == VAR_STRING)
483 {
484 cmd = argvar->vval.v_string;
485 if (cmd == NULL)
486 cmd = (char_u *)"";
487 else if (STRCMP(cmd, "NONE") == 0)
488 cmd = (char_u *)"pty";
489 }
490 else if (argvar->v_type != VAR_LIST
491 || argvar->vval.v_list == NULL
492 || argvar->vval.v_list->lv_len < 1
493 || (cmd = get_tv_string_chk(
494 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
495 cmd = (char_u*)"";
496
497 len = STRLEN(cmd) + 10;
498 p = alloc((int)len);
499
500 for (i = 0; p != NULL; ++i)
501 {
502 /* Prepend a ! to the command name to avoid the buffer name equals
503 * the executable, otherwise ":w!" would overwrite it. */
504 if (i == 0)
505 vim_snprintf((char *)p, len, "!%s", cmd);
506 else
507 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
508 if (buflist_findname(p) == NULL)
509 {
510 vim_free(curbuf->b_ffname);
511 curbuf->b_ffname = p;
512 break;
513 }
514 }
515 }
516 curbuf->b_fname = curbuf->b_ffname;
517
518 if (opt->jo_term_opencmd != NULL)
519 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
520
521 if (opt->jo_eof_chars != NULL)
522 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
523
524 set_string_option_direct((char_u *)"buftype", -1,
525 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
526
527 /* Mark the buffer as not modifiable. It can only be made modifiable after
528 * the job finished. */
529 curbuf->b_p_ma = FALSE;
530
531 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200532#ifdef WIN3264
533 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
534#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200535 setup_job_options(opt, term->tl_rows, term->tl_cols);
536
Bram Moolenaar13568252018-03-16 20:46:58 +0100537 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100538 return curbuf;
539
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100540#if defined(FEAT_SESSION)
541 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100542 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100543 {
544 term->tl_command = vim_strsave((char_u *)"NONE");
545 }
546 else if (argvar->v_type == VAR_STRING)
547 {
548 char_u *cmd = argvar->vval.v_string;
549
550 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
551 term->tl_command = vim_strsave(cmd);
552 }
553 else if (argvar->v_type == VAR_LIST
554 && argvar->vval.v_list != NULL
555 && argvar->vval.v_list->lv_len > 0)
556 {
557 garray_T ga;
558 listitem_T *item;
559
560 ga_init2(&ga, 1, 100);
561 for (item = argvar->vval.v_list->lv_first;
562 item != NULL; item = item->li_next)
563 {
564 char_u *s = get_tv_string_chk(&item->li_tv);
565 char_u *p;
566
567 if (s == NULL)
568 break;
569 p = vim_strsave_fnameescape(s, FALSE);
570 if (p == NULL)
571 break;
572 ga_concat(&ga, p);
573 vim_free(p);
574 ga_append(&ga, ' ');
575 }
576 if (item == NULL)
577 {
578 ga_append(&ga, NUL);
579 term->tl_command = ga.ga_data;
580 }
581 else
582 ga_clear(&ga);
583 }
584#endif
585
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100586 if (opt->jo_term_kill != NULL)
587 {
588 char_u *p = skiptowhite(opt->jo_term_kill);
589
590 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
591 }
592
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200593 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100594 if (argv == NULL
595 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596 && argvar->vval.v_string != NULL
597 && STRCMP(argvar->vval.v_string, "NONE") == 0)
598 res = create_pty_only(term, opt);
599 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200600 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200601
602 newbuf = curbuf;
603 if (res == OK)
604 {
605 /* Get and remember the size we ended up with. Update the pty. */
606 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
607 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100608#ifdef FEAT_GUI
609 if (term->tl_system)
610 {
611 /* display first line below typed command */
612 term->tl_toprow = msg_row + 1;
613 term->tl_dirty_row_end = 0;
614 }
615#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200616
617 /* Make sure we don't get stuck on sending keys to the job, it leads to
618 * a deadlock if the job is waiting for Vim to read. */
619 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
620
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200621 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622 {
623 --curbuf->b_nwindows;
624 curbuf = old_curbuf;
625 curwin->w_buffer = curbuf;
626 ++curbuf->b_nwindows;
627 }
628 }
629 else
630 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100631 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200632 return NULL;
633 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100634
Bram Moolenaar13568252018-03-16 20:46:58 +0100635 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200636 return newbuf;
637}
638
639/*
640 * ":terminal": open a terminal window and execute a job in it.
641 */
642 void
643ex_terminal(exarg_T *eap)
644{
645 typval_T argvar[2];
646 jobopt_T opt;
647 char_u *cmd;
648 char_u *tofree = NULL;
649
650 init_job_options(&opt);
651
652 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100653 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 {
655 char_u *p, *ep;
656
657 cmd += 2;
658 p = skiptowhite(cmd);
659 ep = vim_strchr(cmd, '=');
660 if (ep != NULL && ep < p)
661 p = ep;
662
663 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
664 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100665 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
666 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200667 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
668 opt.jo_term_finish = 'o';
669 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
670 opt.jo_curwin = 1;
671 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
672 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100673 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
674 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100675 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
676 && ep != NULL)
677 {
678 opt.jo_set2 |= JO2_TERM_KILL;
679 opt.jo_term_kill = ep + 1;
680 p = skiptowhite(cmd);
681 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200682 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
683 && ep != NULL && isdigit(ep[1]))
684 {
685 opt.jo_set2 |= JO2_TERM_ROWS;
686 opt.jo_term_rows = atoi((char *)ep + 1);
687 p = skiptowhite(cmd);
688 }
689 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
690 && ep != NULL && isdigit(ep[1]))
691 {
692 opt.jo_set2 |= JO2_TERM_COLS;
693 opt.jo_term_cols = atoi((char *)ep + 1);
694 p = skiptowhite(cmd);
695 }
696 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
697 && ep != NULL)
698 {
699 char_u *buf = NULL;
700 char_u *keys;
701
702 p = skiptowhite(cmd);
703 *p = NUL;
704 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
705 opt.jo_set2 |= JO2_EOF_CHARS;
706 opt.jo_eof_chars = vim_strsave(keys);
707 vim_free(buf);
708 *p = ' ';
709 }
710 else
711 {
712 if (*p)
713 *p = NUL;
714 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100715 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200716 }
717 cmd = skipwhite(p);
718 }
719 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100720 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200721 /* Make a copy of 'shell', an autocommand may change the option. */
722 tofree = cmd = vim_strsave(p_sh);
723
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100724 /* default to close when the shell exits */
725 if (opt.jo_term_finish == NUL)
726 opt.jo_term_finish = 'c';
727 }
728
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200729 if (eap->addr_count > 0)
730 {
731 /* Write lines from current buffer to the job. */
732 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
733 opt.jo_io[PART_IN] = JIO_BUFFER;
734 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
735 opt.jo_in_top = eap->line1;
736 opt.jo_in_bot = eap->line2;
737 }
738
739 argvar[0].v_type = VAR_STRING;
740 argvar[0].vval.v_string = cmd;
741 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100742 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200743 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100744
745theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 vim_free(opt.jo_eof_chars);
747}
748
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100749#if defined(FEAT_SESSION) || defined(PROTO)
750/*
751 * Write a :terminal command to the session file to restore the terminal in
752 * window "wp".
753 * Return FAIL if writing fails.
754 */
755 int
756term_write_session(FILE *fd, win_T *wp)
757{
758 term_T *term = wp->w_buffer->b_term;
759
760 /* Create the terminal and run the command. This is not without
761 * risk, but let's assume the user only creates a session when this
762 * will be OK. */
763 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
764 term->tl_cols, term->tl_rows) < 0)
765 return FAIL;
766 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
767 return FAIL;
768
769 return put_eol(fd);
770}
771
772/*
773 * Return TRUE if "buf" has a terminal that should be restored.
774 */
775 int
776term_should_restore(buf_T *buf)
777{
778 term_T *term = buf->b_term;
779
780 return term != NULL && (term->tl_command == NULL
781 || STRCMP(term->tl_command, "NONE") != 0);
782}
783#endif
784
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200785/*
786 * Free the scrollback buffer for "term".
787 */
788 static void
789free_scrollback(term_T *term)
790{
791 int i;
792
793 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
794 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
795 ga_clear(&term->tl_scrollback);
796}
797
798/*
799 * Free a terminal and everything it refers to.
800 * Kills the job if there is one.
801 * Called when wiping out a buffer.
802 */
803 void
804free_terminal(buf_T *buf)
805{
806 term_T *term = buf->b_term;
807 term_T *tp;
808
809 if (term == NULL)
810 return;
811 if (first_term == term)
812 first_term = term->tl_next;
813 else
814 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
815 if (tp->tl_next == term)
816 {
817 tp->tl_next = term->tl_next;
818 break;
819 }
820
821 if (term->tl_job != NULL)
822 {
823 if (term->tl_job->jv_status != JOB_ENDED
824 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100825 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200826 job_stop(term->tl_job, NULL, "kill");
827 job_unref(term->tl_job);
828 }
829
830 free_scrollback(term);
831
832 term_free_vterm(term);
833 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100834#ifdef FEAT_SESSION
835 vim_free(term->tl_command);
836#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100837 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 vim_free(term->tl_status_text);
839 vim_free(term->tl_opencmd);
840 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200841#ifdef WIN3264
842 if (term->tl_out_fd != NULL)
843 fclose(term->tl_out_fd);
844#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100845 if (desired_cursor_color == term->tl_cursor_color)
846 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200847 vim_free(term->tl_cursor_color);
848 vim_free(term);
849 buf->b_term = NULL;
850 if (in_terminal_loop == term)
851 in_terminal_loop = NULL;
852}
853
854/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100855 * Get the part that is connected to the tty. Normally this is PART_IN, but
856 * when writing buffer lines to the job it can be another. This makes it
857 * possible to do "1,5term vim -".
858 */
859 static ch_part_T
860get_tty_part(term_T *term)
861{
862#ifdef UNIX
863 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
864 int i;
865
866 for (i = 0; i < 3; ++i)
867 {
868 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
869
870 if (isatty(fd))
871 return parts[i];
872 }
873#endif
874 return PART_IN;
875}
876
877/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200878 * Write job output "msg[len]" to the vterm.
879 */
880 static void
881term_write_job_output(term_T *term, char_u *msg, size_t len)
882{
883 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100884 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200885
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100886 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100888 /* flush vterm buffer when vterm responded to control sequence */
889 if (prevlen != vterm_output_get_buffer_current(vterm))
890 {
891 char buf[KEY_BUF_LEN];
892 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
893
894 if (curlen > 0)
895 channel_send(term->tl_job->jv_channel, get_tty_part(term),
896 (char_u *)buf, (int)curlen, NULL);
897 }
898
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899 /* this invokes the damage callbacks */
900 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
901}
902
903 static void
904update_cursor(term_T *term, int redraw)
905{
906 if (term->tl_normal_mode)
907 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100908#ifdef FEAT_GUI
909 if (term->tl_system)
910 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
911 term->tl_cursor_pos.col);
912 else
913#endif
914 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200915 if (redraw)
916 {
917 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
918 cursor_on();
919 out_flush();
920#ifdef FEAT_GUI
921 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100922 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200923 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100924 gui_mch_flush();
925 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926#endif
927 }
928}
929
930/*
931 * Invoked when "msg" output from a job was received. Write it to the terminal
932 * of "buffer".
933 */
934 void
935write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
936{
937 size_t len = STRLEN(msg);
938 term_T *term = buffer->b_term;
939
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200940#ifdef WIN3264
941 /* Win32: Cannot redirect output of the job, intercept it here and write to
942 * the file. */
943 if (term->tl_out_fd != NULL)
944 {
945 ch_log(channel, "Writing %d bytes to output file", (int)len);
946 fwrite(msg, len, 1, term->tl_out_fd);
947 return;
948 }
949#endif
950
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200951 if (term->tl_vterm == NULL)
952 {
953 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
954 return;
955 }
956 ch_log(channel, "writing %d bytes to terminal", (int)len);
957 term_write_job_output(term, msg, len);
958
Bram Moolenaar13568252018-03-16 20:46:58 +0100959#ifdef FEAT_GUI
960 if (term->tl_system)
961 {
962 /* show system output, scrolling up the screen as needed */
963 update_system_term(term);
964 update_cursor(term, TRUE);
965 }
966 else
967#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200968 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
969 * contents, thus no screen update is needed. */
970 if (!term->tl_normal_mode)
971 {
972 /* TODO: only update once in a while. */
973 ch_log(term->tl_job->jv_channel, "updating screen");
974 if (buffer == curbuf)
975 {
976 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200977 /* update_screen() can be slow, check the terminal wasn't closed
978 * already */
979 if (buffer == curbuf && curbuf->b_term != NULL)
980 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200981 }
982 else
983 redraw_after_callback(TRUE);
984 }
985}
986
987/*
988 * Send a mouse position and click to the vterm
989 */
990 static int
991term_send_mouse(VTerm *vterm, int button, int pressed)
992{
993 VTermModifier mod = VTERM_MOD_NONE;
994
995 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200996 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100997 if (button != 0)
998 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200999 return TRUE;
1000}
1001
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001002static int enter_mouse_col = -1;
1003static int enter_mouse_row = -1;
1004
1005/*
1006 * Handle a mouse click, drag or release.
1007 * Return TRUE when a mouse event is sent to the terminal.
1008 */
1009 static int
1010term_mouse_click(VTerm *vterm, int key)
1011{
1012#if defined(FEAT_CLIPBOARD)
1013 /* For modeless selection mouse drag and release events are ignored, unless
1014 * they are preceded with a mouse down event */
1015 static int ignore_drag_release = TRUE;
1016 VTermMouseState mouse_state;
1017
1018 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1019 if (mouse_state.flags == 0)
1020 {
1021 /* Terminal is not using the mouse, use modeless selection. */
1022 switch (key)
1023 {
1024 case K_LEFTDRAG:
1025 case K_LEFTRELEASE:
1026 case K_RIGHTDRAG:
1027 case K_RIGHTRELEASE:
1028 /* Ignore drag and release events when the button-down wasn't
1029 * seen before. */
1030 if (ignore_drag_release)
1031 {
1032 int save_mouse_col, save_mouse_row;
1033
1034 if (enter_mouse_col < 0)
1035 break;
1036
1037 /* mouse click in the window gave us focus, handle that
1038 * click now */
1039 save_mouse_col = mouse_col;
1040 save_mouse_row = mouse_row;
1041 mouse_col = enter_mouse_col;
1042 mouse_row = enter_mouse_row;
1043 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1044 mouse_col = save_mouse_col;
1045 mouse_row = save_mouse_row;
1046 }
1047 /* FALLTHROUGH */
1048 case K_LEFTMOUSE:
1049 case K_RIGHTMOUSE:
1050 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1051 ignore_drag_release = TRUE;
1052 else
1053 ignore_drag_release = FALSE;
1054 /* Should we call mouse_has() here? */
1055 if (clip_star.available)
1056 {
1057 int button, is_click, is_drag;
1058
1059 button = get_mouse_button(KEY2TERMCAP1(key),
1060 &is_click, &is_drag);
1061 if (mouse_model_popup() && button == MOUSE_LEFT
1062 && (mod_mask & MOD_MASK_SHIFT))
1063 {
1064 /* Translate shift-left to right button. */
1065 button = MOUSE_RIGHT;
1066 mod_mask &= ~MOD_MASK_SHIFT;
1067 }
1068 clip_modeless(button, is_click, is_drag);
1069 }
1070 break;
1071
1072 case K_MIDDLEMOUSE:
1073 if (clip_star.available)
1074 insert_reg('*', TRUE);
1075 break;
1076 }
1077 enter_mouse_col = -1;
1078 return FALSE;
1079 }
1080#endif
1081 enter_mouse_col = -1;
1082
1083 switch (key)
1084 {
1085 case K_LEFTMOUSE:
1086 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1087 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1088 case K_LEFTRELEASE:
1089 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1090 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1091 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1092 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1093 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1094 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1095 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1096 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1097 }
1098 return TRUE;
1099}
1100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101/*
1102 * Convert typed key "c" into bytes to send to the job.
1103 * Return the number of bytes in "buf".
1104 */
1105 static int
1106term_convert_key(term_T *term, int c, char *buf)
1107{
1108 VTerm *vterm = term->tl_vterm;
1109 VTermKey key = VTERM_KEY_NONE;
1110 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001111 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001112
1113 switch (c)
1114 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001115 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1116
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001117 /* don't use VTERM_KEY_BACKSPACE, it always
1118 * becomes 0x7f DEL */
1119 case K_BS: c = term_backspace_char; break;
1120
1121 case ESC: key = VTERM_KEY_ESCAPE; break;
1122 case K_DEL: key = VTERM_KEY_DEL; break;
1123 case K_DOWN: key = VTERM_KEY_DOWN; break;
1124 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1125 key = VTERM_KEY_DOWN; break;
1126 case K_END: key = VTERM_KEY_END; break;
1127 case K_S_END: mod = VTERM_MOD_SHIFT;
1128 key = VTERM_KEY_END; break;
1129 case K_C_END: mod = VTERM_MOD_CTRL;
1130 key = VTERM_KEY_END; break;
1131 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1132 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1133 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1134 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1135 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1136 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1137 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1138 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1139 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1140 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1141 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1142 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1143 case K_HOME: key = VTERM_KEY_HOME; break;
1144 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1145 key = VTERM_KEY_HOME; break;
1146 case K_C_HOME: mod = VTERM_MOD_CTRL;
1147 key = VTERM_KEY_HOME; break;
1148 case K_INS: key = VTERM_KEY_INS; break;
1149 case K_K0: key = VTERM_KEY_KP_0; break;
1150 case K_K1: key = VTERM_KEY_KP_1; break;
1151 case K_K2: key = VTERM_KEY_KP_2; break;
1152 case K_K3: key = VTERM_KEY_KP_3; break;
1153 case K_K4: key = VTERM_KEY_KP_4; break;
1154 case K_K5: key = VTERM_KEY_KP_5; break;
1155 case K_K6: key = VTERM_KEY_KP_6; break;
1156 case K_K7: key = VTERM_KEY_KP_7; break;
1157 case K_K8: key = VTERM_KEY_KP_8; break;
1158 case K_K9: key = VTERM_KEY_KP_9; break;
1159 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1160 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1161 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1162 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1163 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1164 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1165 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1166 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1167 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1168 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1169 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1170 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1171 case K_LEFT: key = VTERM_KEY_LEFT; break;
1172 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1173 key = VTERM_KEY_LEFT; break;
1174 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1175 key = VTERM_KEY_LEFT; break;
1176 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1177 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1178 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1179 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1180 key = VTERM_KEY_RIGHT; break;
1181 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1182 key = VTERM_KEY_RIGHT; break;
1183 case K_UP: key = VTERM_KEY_UP; break;
1184 case K_S_UP: mod = VTERM_MOD_SHIFT;
1185 key = VTERM_KEY_UP; break;
1186 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001187 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1188 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001189
Bram Moolenaara42ad572017-11-16 13:08:04 +01001190 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1191 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001192 case K_MOUSELEFT: /* TODO */ return 0;
1193 case K_MOUSERIGHT: /* TODO */ return 0;
1194
1195 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001196 case K_LEFTMOUSE_NM:
1197 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001199 case K_LEFTRELEASE_NM:
1200 case K_MOUSEMOVE:
1201 case K_MIDDLEMOUSE:
1202 case K_MIDDLEDRAG:
1203 case K_MIDDLERELEASE:
1204 case K_RIGHTMOUSE:
1205 case K_RIGHTDRAG:
1206 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1207 return 0;
1208 other = TRUE;
1209 break;
1210
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001211 case K_X1MOUSE: /* TODO */ return 0;
1212 case K_X1DRAG: /* TODO */ return 0;
1213 case K_X1RELEASE: /* TODO */ return 0;
1214 case K_X2MOUSE: /* TODO */ return 0;
1215 case K_X2DRAG: /* TODO */ return 0;
1216 case K_X2RELEASE: /* TODO */ return 0;
1217
1218 case K_IGNORE: return 0;
1219 case K_NOP: return 0;
1220 case K_UNDO: return 0;
1221 case K_HELP: return 0;
1222 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1223 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1224 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1225 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1226 case K_SELECT: return 0;
1227#ifdef FEAT_GUI
1228 case K_VER_SCROLLBAR: return 0;
1229 case K_HOR_SCROLLBAR: return 0;
1230#endif
1231#ifdef FEAT_GUI_TABLINE
1232 case K_TABLINE: return 0;
1233 case K_TABMENU: return 0;
1234#endif
1235#ifdef FEAT_NETBEANS_INTG
1236 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1237#endif
1238#ifdef FEAT_DND
1239 case K_DROP: return 0;
1240#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001241 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001242 case K_PS: vterm_keyboard_start_paste(vterm);
1243 other = TRUE;
1244 break;
1245 case K_PE: vterm_keyboard_end_paste(vterm);
1246 other = TRUE;
1247 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001248 }
1249
1250 /*
1251 * Convert special keys to vterm keys:
1252 * - Write keys to vterm: vterm_keyboard_key()
1253 * - Write output to channel.
1254 * TODO: use mod_mask
1255 */
1256 if (key != VTERM_KEY_NONE)
1257 /* Special key, let vterm convert it. */
1258 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001259 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001260 /* Normal character, let vterm convert it. */
1261 vterm_keyboard_unichar(vterm, c, mod);
1262
1263 /* Read back the converted escape sequence. */
1264 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1265}
1266
1267/*
1268 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001269 * If "check_job_status" is TRUE update the job status.
1270 */
1271 static int
1272term_job_running_check(term_T *term, int check_job_status)
1273{
1274 /* Also consider the job finished when the channel is closed, to avoid a
1275 * race condition when updating the title. */
1276 if (term != NULL
1277 && term->tl_job != NULL
1278 && channel_is_open(term->tl_job->jv_channel))
1279 {
1280 if (check_job_status)
1281 job_status(term->tl_job);
1282 return (term->tl_job->jv_status == JOB_STARTED
1283 || term->tl_job->jv_channel->ch_keep_open);
1284 }
1285 return FALSE;
1286}
1287
1288/*
1289 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001290 */
1291 int
1292term_job_running(term_T *term)
1293{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001294 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001295}
1296
1297/*
1298 * Return TRUE if "term" has an active channel and used ":term NONE".
1299 */
1300 int
1301term_none_open(term_T *term)
1302{
1303 /* Also consider the job finished when the channel is closed, to avoid a
1304 * race condition when updating the title. */
1305 return term != NULL
1306 && term->tl_job != NULL
1307 && channel_is_open(term->tl_job->jv_channel)
1308 && term->tl_job->jv_channel->ch_keep_open;
1309}
1310
1311/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001312 * Used when exiting: kill the job in "buf" if so desired.
1313 * Return OK when the job finished.
1314 * Return FAIL when the job is still running.
1315 */
1316 int
1317term_try_stop_job(buf_T *buf)
1318{
1319 int count;
1320 char *how = (char *)buf->b_term->tl_kill;
1321
1322#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1323 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1324 {
1325 char_u buff[DIALOG_MSG_SIZE];
1326 int ret;
1327
1328 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1329 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1330 if (ret == VIM_YES)
1331 how = "kill";
1332 else if (ret == VIM_CANCEL)
1333 return FAIL;
1334 }
1335#endif
1336 if (how == NULL || *how == NUL)
1337 return FAIL;
1338
1339 job_stop(buf->b_term->tl_job, NULL, how);
1340
1341 /* wait for up to a second for the job to die */
1342 for (count = 0; count < 100; ++count)
1343 {
1344 /* buffer, terminal and job may be cleaned up while waiting */
1345 if (!buf_valid(buf)
1346 || buf->b_term == NULL
1347 || buf->b_term->tl_job == NULL)
1348 return OK;
1349
1350 /* call job_status() to update jv_status */
1351 job_status(buf->b_term->tl_job);
1352 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1353 return OK;
1354 ui_delay(10L, FALSE);
1355 mch_check_messages();
1356 parse_queued_messages();
1357 }
1358 return FAIL;
1359}
1360
1361/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 * Add the last line of the scrollback buffer to the buffer in the window.
1363 */
1364 static void
1365add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1366{
1367 buf_T *buf = term->tl_buffer;
1368 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1369 linenr_T lnum = buf->b_ml.ml_line_count;
1370
1371#ifdef WIN3264
1372 if (!enc_utf8 && enc_codepage > 0)
1373 {
1374 WCHAR *ret = NULL;
1375 int length = 0;
1376
1377 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1378 &ret, &length);
1379 if (ret != NULL)
1380 {
1381 WideCharToMultiByte_alloc(enc_codepage, 0,
1382 ret, length, (char **)&text, &len, 0, 0);
1383 vim_free(ret);
1384 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1385 vim_free(text);
1386 }
1387 }
1388 else
1389#endif
1390 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1391 if (empty)
1392 {
1393 /* Delete the empty line that was in the empty buffer. */
1394 curbuf = buf;
1395 ml_delete(1, FALSE);
1396 curbuf = curwin->w_buffer;
1397 }
1398}
1399
1400 static void
1401cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1402{
1403 attr->width = cell->width;
1404 attr->attrs = cell->attrs;
1405 attr->fg = cell->fg;
1406 attr->bg = cell->bg;
1407}
1408
1409 static int
1410equal_celattr(cellattr_T *a, cellattr_T *b)
1411{
1412 /* Comparing the colors should be sufficient. */
1413 return a->fg.red == b->fg.red
1414 && a->fg.green == b->fg.green
1415 && a->fg.blue == b->fg.blue
1416 && a->bg.red == b->bg.red
1417 && a->bg.green == b->bg.green
1418 && a->bg.blue == b->bg.blue;
1419}
1420
Bram Moolenaard96ff162018-02-18 22:13:29 +01001421/*
1422 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1423 * line at this position. Otherwise at the end.
1424 */
1425 static int
1426add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1427{
1428 if (ga_grow(&term->tl_scrollback, 1) == OK)
1429 {
1430 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1431 + term->tl_scrollback.ga_len;
1432
1433 if (lnum > 0)
1434 {
1435 int i;
1436
1437 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1438 {
1439 *line = *(line - 1);
1440 --line;
1441 }
1442 }
1443 line->sb_cols = 0;
1444 line->sb_cells = NULL;
1445 line->sb_fill_attr = *fill_attr;
1446 ++term->tl_scrollback.ga_len;
1447 return OK;
1448 }
1449 return FALSE;
1450}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001451
1452/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001453 * Remove the terminal contents from the scrollback and the buffer.
1454 * Used before adding a new scrollback line or updating the buffer for lines
1455 * displayed in the terminal.
1456 */
1457 static void
1458cleanup_scrollback(term_T *term)
1459{
1460 sb_line_T *line;
1461 garray_T *gap;
1462
1463 gap = &term->tl_scrollback;
1464 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1465 && gap->ga_len > 0)
1466 {
1467 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1468 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1469 vim_free(line->sb_cells);
1470 --gap->ga_len;
1471 }
1472 check_cursor();
1473}
1474
1475/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001476 * Add the current lines of the terminal to scrollback and to the buffer.
1477 * Called after the job has ended and when switching to Terminal-Normal mode.
1478 */
1479 static void
1480move_terminal_to_buffer(term_T *term)
1481{
1482 win_T *wp;
1483 int len;
1484 int lines_skipped = 0;
1485 VTermPos pos;
1486 VTermScreenCell cell;
1487 cellattr_T fill_attr, new_fill_attr;
1488 cellattr_T *p;
1489 VTermScreen *screen;
1490
1491 if (term->tl_vterm == NULL)
1492 return;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001493
1494 /* Nothing to do if the buffer already has the lines and nothing was
1495 * changed. */
1496 if (!term->tl_dirty_snapshot
1497 && curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled)
1498 return;
1499
1500 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1501 "Adding terminal window snapshot to buffer");
1502
1503 /* First remove the lines that were appended before, they might be
1504 * outdated. */
1505 cleanup_scrollback(term);
1506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507 screen = vterm_obtain_screen(term->tl_vterm);
1508 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001509 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1510 {
1511 len = 0;
1512 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1513 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1514 && cell.chars[0] != NUL)
1515 {
1516 len = pos.col + 1;
1517 new_fill_attr = term->tl_default_color;
1518 }
1519 else
1520 /* Assume the last attr is the filler attr. */
1521 cell2cellattr(&cell, &new_fill_attr);
1522
1523 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1524 ++lines_skipped;
1525 else
1526 {
1527 while (lines_skipped > 0)
1528 {
1529 /* Line was skipped, add an empty line. */
1530 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001531 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001532 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001533 }
1534
1535 if (len == 0)
1536 p = NULL;
1537 else
1538 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1539 if ((p != NULL || len == 0)
1540 && ga_grow(&term->tl_scrollback, 1) == OK)
1541 {
1542 garray_T ga;
1543 int width;
1544 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1545 + term->tl_scrollback.ga_len;
1546
1547 ga_init2(&ga, 1, 100);
1548 for (pos.col = 0; pos.col < len; pos.col += width)
1549 {
1550 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1551 {
1552 width = 1;
1553 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1554 if (ga_grow(&ga, 1) == OK)
1555 ga.ga_len += utf_char2bytes(' ',
1556 (char_u *)ga.ga_data + ga.ga_len);
1557 }
1558 else
1559 {
1560 width = cell.width;
1561
1562 cell2cellattr(&cell, &p[pos.col]);
1563
1564 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1565 {
1566 int i;
1567 int c;
1568
1569 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1570 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1571 (char_u *)ga.ga_data + ga.ga_len);
1572 }
1573 }
1574 }
1575 line->sb_cols = len;
1576 line->sb_cells = p;
1577 line->sb_fill_attr = new_fill_attr;
1578 fill_attr = new_fill_attr;
1579 ++term->tl_scrollback.ga_len;
1580
1581 if (ga_grow(&ga, 1) == FAIL)
1582 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1583 else
1584 {
1585 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1586 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1587 }
1588 ga_clear(&ga);
1589 }
1590 else
1591 vim_free(p);
1592 }
1593 }
1594
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001595 term->tl_dirty_snapshot = FALSE;
1596#ifdef FEAT_TIMERS
1597 term->tl_timer_set = FALSE;
1598#endif
1599
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001600 /* Obtain the current background color. */
1601 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1602 &term->tl_default_color.fg, &term->tl_default_color.bg);
1603
1604 FOR_ALL_WINDOWS(wp)
1605 {
1606 if (wp->w_buffer == term->tl_buffer)
1607 {
1608 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1609 wp->w_cursor.col = 0;
1610 wp->w_valid = 0;
1611 if (wp->w_cursor.lnum >= wp->w_height)
1612 {
1613 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1614
1615 if (wp->w_topline < min_topline)
1616 wp->w_topline = min_topline;
1617 }
1618 redraw_win_later(wp, NOT_VALID);
1619 }
1620 }
1621}
1622
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001623#if defined(FEAT_TIMERS) || defined(PROTO)
1624/*
1625 * Check if any terminal timer expired. If so, copy text from the terminal to
1626 * the buffer.
1627 * Return the time until the next timer will expire.
1628 */
1629 int
1630term_check_timers(int next_due_arg, proftime_T *now)
1631{
1632 term_T *term;
1633 int next_due = next_due_arg;
1634
1635 for (term = first_term; term != NULL; term = term->tl_next)
1636 {
1637 if (term->tl_timer_set && !term->tl_normal_mode)
1638 {
1639 long this_due = proftime_time_left(&term->tl_timer_due, now);
1640
1641 if (this_due <= 1)
1642 {
1643 term->tl_timer_set = FALSE;
1644 move_terminal_to_buffer(term);
1645 }
1646 else if (next_due == -1 || next_due > this_due)
1647 next_due = this_due;
1648 }
1649 }
1650
1651 return next_due;
1652}
1653#endif
1654
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001655 static void
1656set_terminal_mode(term_T *term, int normal_mode)
1657{
1658 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001659 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001660 if (term->tl_buffer == curbuf)
1661 maketitle();
1662}
1663
1664/*
1665 * Called after the job if finished and Terminal mode is not active:
1666 * Move the vterm contents into the scrollback buffer and free the vterm.
1667 */
1668 static void
1669cleanup_vterm(term_T *term)
1670{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001671 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672 move_terminal_to_buffer(term);
1673 term_free_vterm(term);
1674 set_terminal_mode(term, FALSE);
1675}
1676
1677/*
1678 * Switch from Terminal-Job mode to Terminal-Normal mode.
1679 * Suspends updating the terminal window.
1680 */
1681 static void
1682term_enter_normal_mode(void)
1683{
1684 term_T *term = curbuf->b_term;
1685
1686 /* Append the current terminal contents to the buffer. */
1687 move_terminal_to_buffer(term);
1688
1689 set_terminal_mode(term, TRUE);
1690
1691 /* Move the window cursor to the position of the cursor in the
1692 * terminal. */
1693 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1694 + term->tl_cursor_pos.row + 1;
1695 check_cursor();
1696 coladvance(term->tl_cursor_pos.col);
1697
1698 /* Display the same lines as in the terminal. */
1699 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1700}
1701
1702/*
1703 * Returns TRUE if the current window contains a terminal and we are in
1704 * Terminal-Normal mode.
1705 */
1706 int
1707term_in_normal_mode(void)
1708{
1709 term_T *term = curbuf->b_term;
1710
1711 return term != NULL && term->tl_normal_mode;
1712}
1713
1714/*
1715 * Switch from Terminal-Normal mode to Terminal-Job mode.
1716 * Restores updating the terminal window.
1717 */
1718 void
1719term_enter_job_mode()
1720{
1721 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001722
1723 set_terminal_mode(term, FALSE);
1724
1725 if (term->tl_channel_closed)
1726 cleanup_vterm(term);
1727 redraw_buf_and_status_later(curbuf, NOT_VALID);
1728}
1729
1730/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001731 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001732 * Note: while waiting a terminal may be closed and freed if the channel is
1733 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001734 */
1735 static int
1736term_vgetc()
1737{
1738 int c;
1739 int save_State = State;
1740
1741 State = TERMINAL;
1742 got_int = FALSE;
1743#ifdef WIN3264
1744 ctrl_break_was_pressed = FALSE;
1745#endif
1746 c = vgetc();
1747 got_int = FALSE;
1748 State = save_State;
1749 return c;
1750}
1751
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001752static int mouse_was_outside = FALSE;
1753
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 * Send keys to terminal.
1756 * Return FAIL when the key needs to be handled in Normal mode.
1757 * Return OK when the key was dropped or sent to the terminal.
1758 */
1759 int
1760send_keys_to_term(term_T *term, int c, int typed)
1761{
1762 char msg[KEY_BUF_LEN];
1763 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 int dragging_outside = FALSE;
1765
1766 /* Catch keys that need to be handled as in Normal mode. */
1767 switch (c)
1768 {
1769 case NUL:
1770 case K_ZERO:
1771 if (typed)
1772 stuffcharReadbuff(c);
1773 return FAIL;
1774
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001775 case K_TABLINE:
1776 stuffcharReadbuff(c);
1777 return FAIL;
1778
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001779 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001780 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001781 return FAIL;
1782
1783 case K_LEFTDRAG:
1784 case K_MIDDLEDRAG:
1785 case K_RIGHTDRAG:
1786 case K_X1DRAG:
1787 case K_X2DRAG:
1788 dragging_outside = mouse_was_outside;
1789 /* FALLTHROUGH */
1790 case K_LEFTMOUSE:
1791 case K_LEFTMOUSE_NM:
1792 case K_LEFTRELEASE:
1793 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001794 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795 case K_MIDDLEMOUSE:
1796 case K_MIDDLERELEASE:
1797 case K_RIGHTMOUSE:
1798 case K_RIGHTRELEASE:
1799 case K_X1MOUSE:
1800 case K_X1RELEASE:
1801 case K_X2MOUSE:
1802 case K_X2RELEASE:
1803
1804 case K_MOUSEUP:
1805 case K_MOUSEDOWN:
1806 case K_MOUSELEFT:
1807 case K_MOUSERIGHT:
1808 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001809 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001810 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001811 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 || dragging_outside)
1813 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001814 /* click or scroll outside the current window or on status line
1815 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001816 if (typed)
1817 {
1818 stuffcharReadbuff(c);
1819 mouse_was_outside = TRUE;
1820 }
1821 return FAIL;
1822 }
1823 }
1824 if (typed)
1825 mouse_was_outside = FALSE;
1826
1827 /* Convert the typed key to a sequence of bytes for the job. */
1828 len = term_convert_key(term, c, msg);
1829 if (len > 0)
1830 /* TODO: if FAIL is returned, stop? */
1831 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1832 (char_u *)msg, (int)len, NULL);
1833
1834 return OK;
1835}
1836
1837 static void
1838position_cursor(win_T *wp, VTermPos *pos)
1839{
1840 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1841 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1842 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1843}
1844
1845/*
1846 * Handle CTRL-W "": send register contents to the job.
1847 */
1848 static void
1849term_paste_register(int prev_c UNUSED)
1850{
1851 int c;
1852 list_T *l;
1853 listitem_T *item;
1854 long reglen = 0;
1855 int type;
1856
1857#ifdef FEAT_CMDL_INFO
1858 if (add_to_showcmd(prev_c))
1859 if (add_to_showcmd('"'))
1860 out_flush();
1861#endif
1862 c = term_vgetc();
1863#ifdef FEAT_CMDL_INFO
1864 clear_showcmd();
1865#endif
1866 if (!term_use_loop())
1867 /* job finished while waiting for a character */
1868 return;
1869
1870 /* CTRL-W "= prompt for expression to evaluate. */
1871 if (c == '=' && get_expr_register() != '=')
1872 return;
1873 if (!term_use_loop())
1874 /* job finished while waiting for a character */
1875 return;
1876
1877 l = (list_T *)get_reg_contents(c, GREG_LIST);
1878 if (l != NULL)
1879 {
1880 type = get_reg_type(c, &reglen);
1881 for (item = l->lv_first; item != NULL; item = item->li_next)
1882 {
1883 char_u *s = get_tv_string(&item->li_tv);
1884#ifdef WIN3264
1885 char_u *tmp = s;
1886
1887 if (!enc_utf8 && enc_codepage > 0)
1888 {
1889 WCHAR *ret = NULL;
1890 int length = 0;
1891
1892 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1893 (int)STRLEN(s), &ret, &length);
1894 if (ret != NULL)
1895 {
1896 WideCharToMultiByte_alloc(CP_UTF8, 0,
1897 ret, length, (char **)&s, &length, 0, 0);
1898 vim_free(ret);
1899 }
1900 }
1901#endif
1902 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1903 s, (int)STRLEN(s), NULL);
1904#ifdef WIN3264
1905 if (tmp != s)
1906 vim_free(s);
1907#endif
1908
1909 if (item->li_next != NULL || type == MLINE)
1910 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1911 (char_u *)"\r", 1, NULL);
1912 }
1913 list_free(l);
1914 }
1915}
1916
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001917/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001918 * Return TRUE when waiting for a character in the terminal, the cursor of the
1919 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001920 */
1921 int
1922terminal_is_active()
1923{
1924 return in_terminal_loop != NULL;
1925}
1926
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001927#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001928 cursorentry_T *
1929term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1930{
1931 term_T *term = in_terminal_loop;
1932 static cursorentry_T entry;
1933
1934 vim_memset(&entry, 0, sizeof(entry));
1935 entry.shape = entry.mshape =
1936 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1937 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1938 SHAPE_BLOCK;
1939 entry.percentage = 20;
1940 if (term->tl_cursor_blink)
1941 {
1942 entry.blinkwait = 700;
1943 entry.blinkon = 400;
1944 entry.blinkoff = 250;
1945 }
1946 *fg = gui.back_pixel;
1947 if (term->tl_cursor_color == NULL)
1948 *bg = gui.norm_pixel;
1949 else
1950 *bg = color_name2handle(term->tl_cursor_color);
1951 entry.name = "n";
1952 entry.used_for = SHAPE_CURSOR;
1953
1954 return &entry;
1955}
1956#endif
1957
Bram Moolenaard317b382018-02-08 22:33:31 +01001958 static void
1959may_output_cursor_props(void)
1960{
1961 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1962 || last_set_cursor_shape != desired_cursor_shape
1963 || last_set_cursor_blink != desired_cursor_blink)
1964 {
1965 last_set_cursor_color = desired_cursor_color;
1966 last_set_cursor_shape = desired_cursor_shape;
1967 last_set_cursor_blink = desired_cursor_blink;
1968 term_cursor_color(desired_cursor_color);
1969 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1970 /* this will restore the initial cursor style, if possible */
1971 ui_cursor_shape_forced(TRUE);
1972 else
1973 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1974 }
1975}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001976
Bram Moolenaard317b382018-02-08 22:33:31 +01001977/*
1978 * Set the cursor color and shape, if not last set to these.
1979 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001980 static void
1981may_set_cursor_props(term_T *term)
1982{
1983#ifdef FEAT_GUI
1984 /* For the GUI the cursor properties are obtained with
1985 * term_get_cursor_shape(). */
1986 if (gui.in_use)
1987 return;
1988#endif
1989 if (in_terminal_loop == term)
1990 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001991 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001992 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001994 desired_cursor_color = (char_u *)"";
1995 desired_cursor_shape = term->tl_cursor_shape;
1996 desired_cursor_blink = term->tl_cursor_blink;
1997 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 }
1999}
2000
Bram Moolenaard317b382018-02-08 22:33:31 +01002001/*
2002 * Reset the desired cursor properties and restore them when needed.
2003 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002004 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002005prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006{
2007#ifdef FEAT_GUI
2008 if (gui.in_use)
2009 return;
2010#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002011 desired_cursor_color = (char_u *)"";
2012 desired_cursor_shape = -1;
2013 desired_cursor_blink = -1;
2014 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002015}
2016
2017/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002018 * Returns TRUE if the current window contains a terminal and we are sending
2019 * keys to the job.
2020 * If "check_job_status" is TRUE update the job status.
2021 */
2022 static int
2023term_use_loop_check(int check_job_status)
2024{
2025 term_T *term = curbuf->b_term;
2026
2027 return term != NULL
2028 && !term->tl_normal_mode
2029 && term->tl_vterm != NULL
2030 && term_job_running_check(term, check_job_status);
2031}
2032
2033/*
2034 * Returns TRUE if the current window contains a terminal and we are sending
2035 * keys to the job.
2036 */
2037 int
2038term_use_loop(void)
2039{
2040 return term_use_loop_check(FALSE);
2041}
2042
2043/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002044 * Called when entering a window with the mouse. If this is a terminal window
2045 * we may want to change state.
2046 */
2047 void
2048term_win_entered()
2049{
2050 term_T *term = curbuf->b_term;
2051
2052 if (term != NULL)
2053 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002054 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002055 {
2056 reset_VIsual_and_resel();
2057 if (State & INSERT)
2058 stop_insert_mode = TRUE;
2059 }
2060 mouse_was_outside = FALSE;
2061 enter_mouse_col = mouse_col;
2062 enter_mouse_row = mouse_row;
2063 }
2064}
2065
2066/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002067 * Wait for input and send it to the job.
2068 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2069 * when there is no more typahead.
2070 * Return when the start of a CTRL-W command is typed or anything else that
2071 * should be handled as a Normal mode command.
2072 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2073 * the terminal was closed.
2074 */
2075 int
2076terminal_loop(int blocking)
2077{
2078 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002079 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002080 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002081#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002082 int tty_fd = curbuf->b_term->tl_job->jv_channel
2083 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002084#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002085 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002086
2087 /* Remember the terminal we are sending keys to. However, the terminal
2088 * might be closed while waiting for a character, e.g. typing "exit" in a
2089 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2090 * stored reference. */
2091 in_terminal_loop = curbuf->b_term;
2092
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002093 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002094 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002095 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2096 may_set_cursor_props(curbuf->b_term);
2097
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002098 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002099 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002100#ifdef FEAT_GUI
2101 if (!curbuf->b_term->tl_system)
2102#endif
2103 /* TODO: skip screen update when handling a sequence of keys. */
2104 /* Repeat redrawing in case a message is received while redrawing.
2105 */
2106 while (must_redraw != 0)
2107 if (update_screen(0) == FAIL)
2108 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002109 if (!term_use_loop_check(TRUE))
2110 /* job finished while redrawing */
2111 break;
2112
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002113 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002114 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002115
2116 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002117 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002118 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002119 /* Job finished while waiting for a character. Push back the
2120 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002121 if (c != K_IGNORE)
2122 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002123 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002124 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002125 if (c == K_IGNORE)
2126 continue;
2127
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002128#ifdef UNIX
2129 /*
2130 * The shell or another program may change the tty settings. Getting
2131 * them for every typed character is a bit of overhead, but it's needed
2132 * for the first character typed, e.g. when Vim starts in a shell.
2133 */
2134 if (isatty(tty_fd))
2135 {
2136 ttyinfo_T info;
2137
2138 /* Get the current backspace character of the pty. */
2139 if (get_tty_info(tty_fd, &info) == OK)
2140 term_backspace_char = info.backspace;
2141 }
2142#endif
2143
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144#ifdef WIN3264
2145 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2146 * Use CTRL-BREAK to kill the job. */
2147 if (ctrl_break_was_pressed)
2148 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2149#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002150 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002151 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002152 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002153#ifdef FEAT_GUI
2154 && !curbuf->b_term->tl_system
2155#endif
2156 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157 {
2158 int prev_c = c;
2159
2160#ifdef FEAT_CMDL_INFO
2161 if (add_to_showcmd(c))
2162 out_flush();
2163#endif
2164 c = term_vgetc();
2165#ifdef FEAT_CMDL_INFO
2166 clear_showcmd();
2167#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002168 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002169 /* job finished while waiting for a character */
2170 break;
2171
2172 if (prev_c == Ctrl_BSL)
2173 {
2174 if (c == Ctrl_N)
2175 {
2176 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2177 term_enter_normal_mode();
2178 ret = FAIL;
2179 goto theend;
2180 }
2181 /* Send both keys to the terminal. */
2182 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2183 }
2184 else if (c == Ctrl_C)
2185 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002186 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002187 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2188 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002189 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002190 {
2191 /* "CTRL-W .": send CTRL-W to the job */
2192 c = Ctrl_W;
2193 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002194 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002195 {
2196 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2197 c = Ctrl_BSL;
2198 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002199 else if (c == 'N')
2200 {
2201 /* CTRL-W N : go to Terminal-Normal mode. */
2202 term_enter_normal_mode();
2203 ret = FAIL;
2204 goto theend;
2205 }
2206 else if (c == '"')
2207 {
2208 term_paste_register(prev_c);
2209 continue;
2210 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002211 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002212 {
2213 stuffcharReadbuff(Ctrl_W);
2214 stuffcharReadbuff(c);
2215 ret = OK;
2216 goto theend;
2217 }
2218 }
2219# ifdef WIN3264
2220 if (!enc_utf8 && has_mbyte && c >= 0x80)
2221 {
2222 WCHAR wc;
2223 char_u mb[3];
2224
2225 mb[0] = (unsigned)c >> 8;
2226 mb[1] = c;
2227 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2228 c = wc;
2229 }
2230# endif
2231 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2232 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002233 if (c == K_MOUSEMOVE)
2234 /* We are sure to come back here, don't reset the cursor color
2235 * and shape to avoid flickering. */
2236 restore_cursor = FALSE;
2237
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 ret = OK;
2239 goto theend;
2240 }
2241 }
2242 ret = FAIL;
2243
2244theend:
2245 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002246 if (restore_cursor)
2247 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002248
2249 /* Move a snapshot of the screen contents to the buffer, so that completion
2250 * works in other buffers. */
2251 if (curbuf->b_term != NULL)
2252 move_terminal_to_buffer(curbuf->b_term);
2253
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002254 return ret;
2255}
2256
2257/*
2258 * Called when a job has finished.
2259 * This updates the title and status, but does not close the vterm, because
2260 * there might still be pending output in the channel.
2261 */
2262 void
2263term_job_ended(job_T *job)
2264{
2265 term_T *term;
2266 int did_one = FALSE;
2267
2268 for (term = first_term; term != NULL; term = term->tl_next)
2269 if (term->tl_job == job)
2270 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002271 VIM_CLEAR(term->tl_title);
2272 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002273 redraw_buf_and_status_later(term->tl_buffer, VALID);
2274 did_one = TRUE;
2275 }
2276 if (did_one)
2277 redraw_statuslines();
2278 if (curbuf->b_term != NULL)
2279 {
2280 if (curbuf->b_term->tl_job == job)
2281 maketitle();
2282 update_cursor(curbuf->b_term, TRUE);
2283 }
2284}
2285
2286 static void
2287may_toggle_cursor(term_T *term)
2288{
2289 if (in_terminal_loop == term)
2290 {
2291 if (term->tl_cursor_visible)
2292 cursor_on();
2293 else
2294 cursor_off();
2295 }
2296}
2297
2298/*
2299 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002300 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002301 */
2302 static int
2303color2index(VTermColor *color, int fg, int *boldp)
2304{
2305 int red = color->red;
2306 int blue = color->blue;
2307 int green = color->green;
2308
Bram Moolenaar46359e12017-11-29 22:33:38 +01002309 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002310 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002311 /* First 16 colors and default: use the ANSI index, because these
2312 * colors can be redefined. */
2313 if (t_colors >= 16)
2314 return color->ansi_index;
2315 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002316 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002317 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002318 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002319 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2320 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2321 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002322 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002323 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2324 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2325 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2326 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2327 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2328 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2329 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2330 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2331 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2332 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2333 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334 }
2335 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002336
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002337 if (t_colors >= 256)
2338 {
2339 if (red == blue && red == green)
2340 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002341 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002342 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002343 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2344 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2345 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002346 int i;
2347
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002348 if (red < 5)
2349 return 17; /* 00/00/00 */
2350 if (red > 245) /* ff/ff/ff */
2351 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002352 for (i = 0; i < 23; ++i)
2353 if (red < cutoff[i])
2354 return i + 233;
2355 return 256;
2356 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002357 {
2358 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2359 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002360
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002361 /* 216-color cube */
2362 for (ri = 0; ri < 5; ++ri)
2363 if (red < cutoff[ri])
2364 break;
2365 for (gi = 0; gi < 5; ++gi)
2366 if (green < cutoff[gi])
2367 break;
2368 for (bi = 0; bi < 5; ++bi)
2369 if (blue < cutoff[bi])
2370 break;
2371 return 17 + ri * 36 + gi * 6 + bi;
2372 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 }
2374 return 0;
2375}
2376
2377/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002378 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002379 */
2380 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002381vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382{
2383 int attr = 0;
2384
2385 if (cellattrs.bold)
2386 attr |= HL_BOLD;
2387 if (cellattrs.underline)
2388 attr |= HL_UNDERLINE;
2389 if (cellattrs.italic)
2390 attr |= HL_ITALIC;
2391 if (cellattrs.strike)
2392 attr |= HL_STRIKETHROUGH;
2393 if (cellattrs.reverse)
2394 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002395 return attr;
2396}
2397
2398/*
2399 * Store Vterm attributes in "cell" from highlight flags.
2400 */
2401 static void
2402hl2vtermAttr(int attr, cellattr_T *cell)
2403{
2404 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2405 if (attr & HL_BOLD)
2406 cell->attrs.bold = 1;
2407 if (attr & HL_UNDERLINE)
2408 cell->attrs.underline = 1;
2409 if (attr & HL_ITALIC)
2410 cell->attrs.italic = 1;
2411 if (attr & HL_STRIKETHROUGH)
2412 cell->attrs.strike = 1;
2413 if (attr & HL_INVERSE)
2414 cell->attrs.reverse = 1;
2415}
2416
2417/*
2418 * Convert the attributes of a vterm cell into an attribute index.
2419 */
2420 static int
2421cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2422{
2423 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002424
2425#ifdef FEAT_GUI
2426 if (gui.in_use)
2427 {
2428 guicolor_T fg, bg;
2429
2430 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2431 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2432 return get_gui_attr_idx(attr, fg, bg);
2433 }
2434 else
2435#endif
2436#ifdef FEAT_TERMGUICOLORS
2437 if (p_tgc)
2438 {
2439 guicolor_T fg, bg;
2440
2441 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2442 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2443
2444 return get_tgc_attr_idx(attr, fg, bg);
2445 }
2446 else
2447#endif
2448 {
2449 int bold = MAYBE;
2450 int fg = color2index(&cellfg, TRUE, &bold);
2451 int bg = color2index(&cellbg, FALSE, &bold);
2452
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002453 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002454 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002455 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002456 if (fg == 0 && term_default_cterm_fg >= 0)
2457 fg = term_default_cterm_fg + 1;
2458 if (bg == 0 && term_default_cterm_bg >= 0)
2459 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002460 }
2461
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002462 /* with 8 colors set the bold attribute to get a bright foreground */
2463 if (bold == TRUE)
2464 attr |= HL_BOLD;
2465 return get_cterm_attr_idx(attr, fg, bg);
2466 }
2467 return 0;
2468}
2469
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002470 static void
2471set_dirty_snapshot(term_T *term)
2472{
2473 term->tl_dirty_snapshot = TRUE;
2474#ifdef FEAT_TIMERS
2475 if (!term->tl_normal_mode)
2476 {
2477 /* Update the snapshot after 100 msec of not getting updates. */
2478 profile_setlimit(100L, &term->tl_timer_due);
2479 term->tl_timer_set = TRUE;
2480 }
2481#endif
2482}
2483
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002484 static int
2485handle_damage(VTermRect rect, void *user)
2486{
2487 term_T *term = (term_T *)user;
2488
2489 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2490 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002491 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002492 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002493 return 1;
2494}
2495
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002496 static void
2497term_scroll_up(term_T *term, int start_row, int count)
2498{
2499 win_T *wp;
2500 VTermColor fg, bg;
2501 VTermScreenCellAttrs attr;
2502 int clear_attr;
2503
2504 /* Set the color to clear lines with. */
2505 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2506 &fg, &bg);
2507 vim_memset(&attr, 0, sizeof(attr));
2508 clear_attr = cell2attr(attr, fg, bg);
2509
2510 FOR_ALL_WINDOWS(wp)
2511 {
2512 if (wp->w_buffer == term->tl_buffer)
2513 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2514 }
2515}
2516
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517 static int
2518handle_moverect(VTermRect dest, VTermRect src, void *user)
2519{
2520 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002521 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522
2523 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002524 * redrawing the text. But avoid doing this multiple times, postpone until
2525 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 if (dest.start_col == src.start_col
2527 && dest.end_col == src.end_col
2528 && dest.start_row < src.start_row)
2529 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002530 if (dest.start_row == 0)
2531 term->tl_postponed_scroll += count;
2532 else
2533 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002535
2536 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2537 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002538 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002539
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002540 /* Note sure if the scrolling will work correctly, let's do a complete
2541 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002542 redraw_buf_later(term->tl_buffer, NOT_VALID);
2543 return 1;
2544}
2545
2546 static int
2547handle_movecursor(
2548 VTermPos pos,
2549 VTermPos oldpos UNUSED,
2550 int visible,
2551 void *user)
2552{
2553 term_T *term = (term_T *)user;
2554 win_T *wp;
2555
2556 term->tl_cursor_pos = pos;
2557 term->tl_cursor_visible = visible;
2558
2559 FOR_ALL_WINDOWS(wp)
2560 {
2561 if (wp->w_buffer == term->tl_buffer)
2562 position_cursor(wp, &pos);
2563 }
2564 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2565 {
2566 may_toggle_cursor(term);
2567 update_cursor(term, term->tl_cursor_visible);
2568 }
2569
2570 return 1;
2571}
2572
2573 static int
2574handle_settermprop(
2575 VTermProp prop,
2576 VTermValue *value,
2577 void *user)
2578{
2579 term_T *term = (term_T *)user;
2580
2581 switch (prop)
2582 {
2583 case VTERM_PROP_TITLE:
2584 vim_free(term->tl_title);
2585 /* a blank title isn't useful, make it empty, so that "running" is
2586 * displayed */
2587 if (*skipwhite((char_u *)value->string) == NUL)
2588 term->tl_title = NULL;
2589#ifdef WIN3264
2590 else if (!enc_utf8 && enc_codepage > 0)
2591 {
2592 WCHAR *ret = NULL;
2593 int length = 0;
2594
2595 MultiByteToWideChar_alloc(CP_UTF8, 0,
2596 (char*)value->string, (int)STRLEN(value->string),
2597 &ret, &length);
2598 if (ret != NULL)
2599 {
2600 WideCharToMultiByte_alloc(enc_codepage, 0,
2601 ret, length, (char**)&term->tl_title,
2602 &length, 0, 0);
2603 vim_free(ret);
2604 }
2605 }
2606#endif
2607 else
2608 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002609 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002610 if (term == curbuf->b_term)
2611 maketitle();
2612 break;
2613
2614 case VTERM_PROP_CURSORVISIBLE:
2615 term->tl_cursor_visible = value->boolean;
2616 may_toggle_cursor(term);
2617 out_flush();
2618 break;
2619
2620 case VTERM_PROP_CURSORBLINK:
2621 term->tl_cursor_blink = value->boolean;
2622 may_set_cursor_props(term);
2623 break;
2624
2625 case VTERM_PROP_CURSORSHAPE:
2626 term->tl_cursor_shape = value->number;
2627 may_set_cursor_props(term);
2628 break;
2629
2630 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002631 if (desired_cursor_color == term->tl_cursor_color)
2632 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002633 vim_free(term->tl_cursor_color);
2634 if (*value->string == NUL)
2635 term->tl_cursor_color = NULL;
2636 else
2637 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2638 may_set_cursor_props(term);
2639 break;
2640
2641 case VTERM_PROP_ALTSCREEN:
2642 /* TODO: do anything else? */
2643 term->tl_using_altscreen = value->boolean;
2644 break;
2645
2646 default:
2647 break;
2648 }
2649 /* Always return 1, otherwise vterm doesn't store the value internally. */
2650 return 1;
2651}
2652
2653/*
2654 * The job running in the terminal resized the terminal.
2655 */
2656 static int
2657handle_resize(int rows, int cols, void *user)
2658{
2659 term_T *term = (term_T *)user;
2660 win_T *wp;
2661
2662 term->tl_rows = rows;
2663 term->tl_cols = cols;
2664 if (term->tl_vterm_size_changed)
2665 /* Size was set by vterm_set_size(), don't set the window size. */
2666 term->tl_vterm_size_changed = FALSE;
2667 else
2668 {
2669 FOR_ALL_WINDOWS(wp)
2670 {
2671 if (wp->w_buffer == term->tl_buffer)
2672 {
2673 win_setheight_win(rows, wp);
2674 win_setwidth_win(cols, wp);
2675 }
2676 }
2677 redraw_buf_later(term->tl_buffer, NOT_VALID);
2678 }
2679 return 1;
2680}
2681
2682/*
2683 * Handle a line that is pushed off the top of the screen.
2684 */
2685 static int
2686handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2687{
2688 term_T *term = (term_T *)user;
2689
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002690 /* First remove the lines that were appended before, the pushed line goes
2691 * above it. */
2692 cleanup_scrollback(term);
2693
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002694 /* If the number of lines that are stored goes over 'termscrollback' then
2695 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002696 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002697 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002698 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002699 int i;
2700
2701 curbuf = term->tl_buffer;
2702 for (i = 0; i < todo; ++i)
2703 {
2704 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2705 ml_delete(1, FALSE);
2706 }
2707 curbuf = curwin->w_buffer;
2708
2709 term->tl_scrollback.ga_len -= todo;
2710 mch_memmove(term->tl_scrollback.ga_data,
2711 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2712 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2713 }
2714
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 if (ga_grow(&term->tl_scrollback, 1) == OK)
2716 {
2717 cellattr_T *p = NULL;
2718 int len = 0;
2719 int i;
2720 int c;
2721 int col;
2722 sb_line_T *line;
2723 garray_T ga;
2724 cellattr_T fill_attr = term->tl_default_color;
2725
2726 /* do not store empty cells at the end */
2727 for (i = 0; i < cols; ++i)
2728 if (cells[i].chars[0] != 0)
2729 len = i + 1;
2730 else
2731 cell2cellattr(&cells[i], &fill_attr);
2732
2733 ga_init2(&ga, 1, 100);
2734 if (len > 0)
2735 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2736 if (p != NULL)
2737 {
2738 for (col = 0; col < len; col += cells[col].width)
2739 {
2740 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2741 {
2742 ga.ga_len = 0;
2743 break;
2744 }
2745 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2746 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2747 (char_u *)ga.ga_data + ga.ga_len);
2748 cell2cellattr(&cells[col], &p[col]);
2749 }
2750 }
2751 if (ga_grow(&ga, 1) == FAIL)
2752 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2753 else
2754 {
2755 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2756 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2757 }
2758 ga_clear(&ga);
2759
2760 line = (sb_line_T *)term->tl_scrollback.ga_data
2761 + term->tl_scrollback.ga_len;
2762 line->sb_cols = len;
2763 line->sb_cells = p;
2764 line->sb_fill_attr = fill_attr;
2765 ++term->tl_scrollback.ga_len;
2766 ++term->tl_scrollback_scrolled;
2767 }
2768 return 0; /* ignored */
2769}
2770
2771static VTermScreenCallbacks screen_callbacks = {
2772 handle_damage, /* damage */
2773 handle_moverect, /* moverect */
2774 handle_movecursor, /* movecursor */
2775 handle_settermprop, /* settermprop */
2776 NULL, /* bell */
2777 handle_resize, /* resize */
2778 handle_pushline, /* sb_pushline */
2779 NULL /* sb_popline */
2780};
2781
2782/*
2783 * Called when a channel has been closed.
2784 * If this was a channel for a terminal window then finish it up.
2785 */
2786 void
2787term_channel_closed(channel_T *ch)
2788{
2789 term_T *term;
2790 int did_one = FALSE;
2791
2792 for (term = first_term; term != NULL; term = term->tl_next)
2793 if (term->tl_job == ch->ch_job)
2794 {
2795 term->tl_channel_closed = TRUE;
2796 did_one = TRUE;
2797
Bram Moolenaard23a8232018-02-10 18:45:26 +01002798 VIM_CLEAR(term->tl_title);
2799 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002800#ifdef WIN3264
2801 if (term->tl_out_fd != NULL)
2802 {
2803 fclose(term->tl_out_fd);
2804 term->tl_out_fd = NULL;
2805 }
2806#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002807
2808 /* Unless in Terminal-Normal mode: clear the vterm. */
2809 if (!term->tl_normal_mode)
2810 {
2811 int fnum = term->tl_buffer->b_fnum;
2812
2813 cleanup_vterm(term);
2814
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002815 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002816 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002817 aco_save_T aco;
2818
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002819 /* ++close or term_finish == "close" */
2820 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002821 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002822 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002823 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002824 break;
2825 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002826 if (term->tl_finish == TL_FINISH_OPEN
2827 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828 {
2829 char buf[50];
2830
2831 /* TODO: use term_opencmd */
2832 ch_log(NULL, "terminal job finished, opening window");
2833 vim_snprintf(buf, sizeof(buf),
2834 term->tl_opencmd == NULL
2835 ? "botright sbuf %d"
2836 : (char *)term->tl_opencmd, fnum);
2837 do_cmdline_cmd((char_u *)buf);
2838 }
2839 else
2840 ch_log(NULL, "terminal job finished");
2841 }
2842
2843 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2844 }
2845 if (did_one)
2846 {
2847 redraw_statuslines();
2848
2849 /* Need to break out of vgetc(). */
2850 ins_char_typebuf(K_IGNORE);
2851 typebuf_was_filled = TRUE;
2852
2853 term = curbuf->b_term;
2854 if (term != NULL)
2855 {
2856 if (term->tl_job == ch->ch_job)
2857 maketitle();
2858 update_cursor(term, term->tl_cursor_visible);
2859 }
2860 }
2861}
2862
2863/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002864 * Fill one screen line from a line of the terminal.
2865 * Advances "pos" to past the last column.
2866 */
2867 static void
2868term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2869{
2870 int off = screen_get_current_line_off();
2871
2872 for (pos->col = 0; pos->col < max_col; )
2873 {
2874 VTermScreenCell cell;
2875 int c;
2876
2877 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2878 vim_memset(&cell, 0, sizeof(cell));
2879
2880 c = cell.chars[0];
2881 if (c == NUL)
2882 {
2883 ScreenLines[off] = ' ';
2884 if (enc_utf8)
2885 ScreenLinesUC[off] = NUL;
2886 }
2887 else
2888 {
2889 if (enc_utf8)
2890 {
2891 int i;
2892
2893 /* composing chars */
2894 for (i = 0; i < Screen_mco
2895 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2896 {
2897 ScreenLinesC[i][off] = cell.chars[i + 1];
2898 if (cell.chars[i + 1] == 0)
2899 break;
2900 }
2901 if (c >= 0x80 || (Screen_mco > 0
2902 && ScreenLinesC[0][off] != 0))
2903 {
2904 ScreenLines[off] = ' ';
2905 ScreenLinesUC[off] = c;
2906 }
2907 else
2908 {
2909 ScreenLines[off] = c;
2910 ScreenLinesUC[off] = NUL;
2911 }
2912 }
2913#ifdef WIN3264
2914 else if (has_mbyte && c >= 0x80)
2915 {
2916 char_u mb[MB_MAXBYTES+1];
2917 WCHAR wc = c;
2918
2919 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2920 (char*)mb, 2, 0, 0) > 1)
2921 {
2922 ScreenLines[off] = mb[0];
2923 ScreenLines[off + 1] = mb[1];
2924 cell.width = mb_ptr2cells(mb);
2925 }
2926 else
2927 ScreenLines[off] = c;
2928 }
2929#endif
2930 else
2931 ScreenLines[off] = c;
2932 }
2933 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2934
2935 ++pos->col;
2936 ++off;
2937 if (cell.width == 2)
2938 {
2939 if (enc_utf8)
2940 ScreenLinesUC[off] = NUL;
2941
2942 /* don't set the second byte to NUL for a DBCS encoding, it
2943 * has been set above */
2944 if (enc_utf8 || !has_mbyte)
2945 ScreenLines[off] = NUL;
2946
2947 ++pos->col;
2948 ++off;
2949 }
2950 }
2951}
2952
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002953#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002954 static void
2955update_system_term(term_T *term)
2956{
2957 VTermPos pos;
2958 VTermScreen *screen;
2959
2960 if (term->tl_vterm == NULL)
2961 return;
2962 screen = vterm_obtain_screen(term->tl_vterm);
2963
2964 /* Scroll up to make more room for terminal lines if needed. */
2965 while (term->tl_toprow > 0
2966 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2967 {
2968 int save_p_more = p_more;
2969
2970 p_more = FALSE;
2971 msg_row = Rows - 1;
2972 msg_puts((char_u *)"\n");
2973 p_more = save_p_more;
2974 --term->tl_toprow;
2975 }
2976
2977 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2978 && pos.row < Rows; ++pos.row)
2979 {
2980 if (pos.row < term->tl_rows)
2981 {
2982 int max_col = MIN(Columns, term->tl_cols);
2983
2984 term_line2screenline(screen, &pos, max_col);
2985 }
2986 else
2987 pos.col = 0;
2988
2989 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2990 }
2991
2992 term->tl_dirty_row_start = MAX_ROW;
2993 term->tl_dirty_row_end = 0;
2994 update_cursor(term, TRUE);
2995}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002996#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002997
2998/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002999 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3000 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003001 * Terminal-Normal mode.
3002 */
3003 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003004term_do_update_window(win_T *wp)
3005{
3006 term_T *term = wp->w_buffer->b_term;
3007
3008 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3009}
3010
3011/*
3012 * Called to update a window that contains an active terminal.
3013 */
3014 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003015term_update_window(win_T *wp)
3016{
3017 term_T *term = wp->w_buffer->b_term;
3018 VTerm *vterm;
3019 VTermScreen *screen;
3020 VTermState *state;
3021 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003022 int rows, cols;
3023 int newrows, newcols;
3024 int minsize;
3025 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003026
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003027 vterm = term->tl_vterm;
3028 screen = vterm_obtain_screen(vterm);
3029 state = vterm_obtain_state(vterm);
3030
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003031 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3032 * SOME_VALID only redraw what was marked dirty. */
3033 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003034 {
3035 term->tl_dirty_row_start = 0;
3036 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003037
3038 if (term->tl_postponed_scroll > 0
3039 && term->tl_postponed_scroll < term->tl_rows / 3)
3040 /* Scrolling is usually faster than redrawing, when there are only
3041 * a few lines to scroll. */
3042 term_scroll_up(term, 0, term->tl_postponed_scroll);
3043 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003044 }
3045
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 /*
3047 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003048 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003049 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003050 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051
Bram Moolenaar498c2562018-04-15 23:45:15 +02003052 newrows = 99999;
3053 newcols = 99999;
3054 FOR_ALL_WINDOWS(twp)
3055 {
3056 /* When more than one window shows the same terminal, use the
3057 * smallest size. */
3058 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003059 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003060 newrows = MIN(newrows, twp->w_height);
3061 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003062 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003063 }
3064 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3065 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3066
3067 if (term->tl_rows != newrows || term->tl_cols != newcols)
3068 {
3069
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003070
3071 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003072 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003074 newrows);
3075 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076 }
3077
3078 /* The cursor may have been moved when resizing. */
3079 vterm_state_get_cursorpos(state, &pos);
3080 position_cursor(wp, &pos);
3081
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003082 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3083 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003084 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003085 if (pos.row < term->tl_rows)
3086 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003087 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088
Bram Moolenaar13568252018-03-16 20:46:58 +01003089 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 }
3091 else
3092 pos.col = 0;
3093
Bram Moolenaarf118d482018-03-13 13:14:00 +01003094 screen_line(wp->w_winrow + pos.row
3095#ifdef FEAT_MENU
3096 + winbar_height(wp)
3097#endif
3098 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003100 term->tl_dirty_row_start = MAX_ROW;
3101 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003102}
3103
3104/*
3105 * Return TRUE if "wp" is a terminal window where the job has finished.
3106 */
3107 int
3108term_is_finished(buf_T *buf)
3109{
3110 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3111}
3112
3113/*
3114 * Return TRUE if "wp" is a terminal window where the job has finished or we
3115 * are in Terminal-Normal mode, thus we show the buffer contents.
3116 */
3117 int
3118term_show_buffer(buf_T *buf)
3119{
3120 term_T *term = buf->b_term;
3121
3122 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3123}
3124
3125/*
3126 * The current buffer is going to be changed. If there is terminal
3127 * highlighting remove it now.
3128 */
3129 void
3130term_change_in_curbuf(void)
3131{
3132 term_T *term = curbuf->b_term;
3133
3134 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3135 {
3136 free_scrollback(term);
3137 redraw_buf_later(term->tl_buffer, NOT_VALID);
3138
3139 /* The buffer is now like a normal buffer, it cannot be easily
3140 * abandoned when changed. */
3141 set_string_option_direct((char_u *)"buftype", -1,
3142 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3143 }
3144}
3145
3146/*
3147 * Get the screen attribute for a position in the buffer.
3148 * Use a negative "col" to get the filler background color.
3149 */
3150 int
3151term_get_attr(buf_T *buf, linenr_T lnum, int col)
3152{
3153 term_T *term = buf->b_term;
3154 sb_line_T *line;
3155 cellattr_T *cellattr;
3156
3157 if (lnum > term->tl_scrollback.ga_len)
3158 cellattr = &term->tl_default_color;
3159 else
3160 {
3161 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3162 if (col < 0 || col >= line->sb_cols)
3163 cellattr = &line->sb_fill_attr;
3164 else
3165 cellattr = line->sb_cells + col;
3166 }
3167 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3168}
3169
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003170/*
3171 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003172 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173 */
3174 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003175cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003177 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003178}
3179
3180/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003181 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182 */
3183 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003184init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003185{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003186 VTermColor *fg, *bg;
3187 int fgval, bgval;
3188 int id;
3189
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003190 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3191 term->tl_default_color.width = 1;
3192 fg = &term->tl_default_color.fg;
3193 bg = &term->tl_default_color.bg;
3194
3195 /* Vterm uses a default black background. Set it to white when
3196 * 'background' is "light". */
3197 if (*p_bg == 'l')
3198 {
3199 fgval = 0;
3200 bgval = 255;
3201 }
3202 else
3203 {
3204 fgval = 255;
3205 bgval = 0;
3206 }
3207 fg->red = fg->green = fg->blue = fgval;
3208 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003209 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003210
3211 /* The "Terminal" highlight group overrules the defaults. */
3212 id = syn_name2id((char_u *)"Terminal");
3213
Bram Moolenaar46359e12017-11-29 22:33:38 +01003214 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003215#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3216 if (0
3217# ifdef FEAT_GUI
3218 || gui.in_use
3219# endif
3220# ifdef FEAT_TERMGUICOLORS
3221 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003222# ifdef FEAT_VTP
3223 /* Finally get INVALCOLOR on this execution path */
3224 || (!p_tgc && t_colors >= 256)
3225# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003226# endif
3227 )
3228 {
3229 guicolor_T fg_rgb = INVALCOLOR;
3230 guicolor_T bg_rgb = INVALCOLOR;
3231
3232 if (id != 0)
3233 syn_id2colors(id, &fg_rgb, &bg_rgb);
3234
3235# ifdef FEAT_GUI
3236 if (gui.in_use)
3237 {
3238 if (fg_rgb == INVALCOLOR)
3239 fg_rgb = gui.norm_pixel;
3240 if (bg_rgb == INVALCOLOR)
3241 bg_rgb = gui.back_pixel;
3242 }
3243# ifdef FEAT_TERMGUICOLORS
3244 else
3245# endif
3246# endif
3247# ifdef FEAT_TERMGUICOLORS
3248 {
3249 if (fg_rgb == INVALCOLOR)
3250 fg_rgb = cterm_normal_fg_gui_color;
3251 if (bg_rgb == INVALCOLOR)
3252 bg_rgb = cterm_normal_bg_gui_color;
3253 }
3254# endif
3255 if (fg_rgb != INVALCOLOR)
3256 {
3257 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3258
3259 fg->red = (unsigned)(rgb >> 16);
3260 fg->green = (unsigned)(rgb >> 8) & 255;
3261 fg->blue = (unsigned)rgb & 255;
3262 }
3263 if (bg_rgb != INVALCOLOR)
3264 {
3265 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3266
3267 bg->red = (unsigned)(rgb >> 16);
3268 bg->green = (unsigned)(rgb >> 8) & 255;
3269 bg->blue = (unsigned)rgb & 255;
3270 }
3271 }
3272 else
3273#endif
3274 if (id != 0 && t_colors >= 16)
3275 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003276 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003277 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003278 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003279 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003280 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003281 else
3282 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003283#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003284 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003285#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003286
3287 /* In an MS-Windows console we know the normal colors. */
3288 if (cterm_normal_fg_color > 0)
3289 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003290 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003291# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003292 tmp = fg->red;
3293 fg->red = fg->blue;
3294 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003295# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003297# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003298 else
3299 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003300# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003301
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003302 if (cterm_normal_bg_color > 0)
3303 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003304 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003305# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003306 tmp = bg->red;
3307 bg->red = bg->blue;
3308 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003309# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003310 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003311# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003312 else
3313 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003314# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003315 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003316}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003317
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003318#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3319/*
3320 * Set the 16 ANSI colors from array of RGB values
3321 */
3322 static void
3323set_vterm_palette(VTerm *vterm, long_u *rgb)
3324{
3325 int index = 0;
3326 VTermState *state = vterm_obtain_state(vterm);
3327 for (; index < 16; index++)
3328 {
3329 VTermColor color;
3330 color.red = (unsigned)(rgb[index] >> 16);
3331 color.green = (unsigned)(rgb[index] >> 8) & 255;
3332 color.blue = (unsigned)rgb[index] & 255;
3333 vterm_state_set_palette_color(state, index, &color);
3334 }
3335}
3336
3337/*
3338 * Set the ANSI color palette from a list of colors
3339 */
3340 static int
3341set_ansi_colors_list(VTerm *vterm, list_T *list)
3342{
3343 int n = 0;
3344 long_u rgb[16];
3345 listitem_T *li = list->lv_first;
3346
3347 for (; li != NULL && n < 16; li = li->li_next, n++)
3348 {
3349 char_u *color_name;
3350 guicolor_T guicolor;
3351
3352 color_name = get_tv_string_chk(&li->li_tv);
3353 if (color_name == NULL)
3354 return FAIL;
3355
3356 guicolor = GUI_GET_COLOR(color_name);
3357 if (guicolor == INVALCOLOR)
3358 return FAIL;
3359
3360 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3361 }
3362
3363 if (n != 16 || li != NULL)
3364 return FAIL;
3365
3366 set_vterm_palette(vterm, rgb);
3367
3368 return OK;
3369}
3370
3371/*
3372 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3373 */
3374 static void
3375init_vterm_ansi_colors(VTerm *vterm)
3376{
3377 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3378
3379 if (var != NULL
3380 && (var->di_tv.v_type != VAR_LIST
3381 || var->di_tv.vval.v_list == NULL
3382 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3383 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3384}
3385#endif
3386
Bram Moolenaar52acb112018-03-18 19:20:22 +01003387/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003388 * Handles a "drop" command from the job in the terminal.
3389 * "item" is the file name, "item->li_next" may have options.
3390 */
3391 static void
3392handle_drop_command(listitem_T *item)
3393{
3394 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003395 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003396 int bufnr;
3397 win_T *wp;
3398 tabpage_T *tp;
3399 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003400 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003401
3402 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3403 FOR_ALL_TAB_WINDOWS(tp, wp)
3404 {
3405 if (wp->w_buffer->b_fnum == bufnr)
3406 {
3407 /* buffer is in a window already, go there */
3408 goto_tabpage_win(tp, wp);
3409 return;
3410 }
3411 }
3412
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003413 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003414
3415 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3416 && opt_item->li_tv.vval.v_dict != NULL)
3417 {
3418 dict_T *dict = opt_item->li_tv.vval.v_dict;
3419 char_u *p;
3420
3421 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3422 if (p == NULL)
3423 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3424 if (p != NULL)
3425 {
3426 if (check_ff_value(p) == FAIL)
3427 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3428 else
3429 ea.force_ff = *p;
3430 }
3431 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3432 if (p == NULL)
3433 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3434 if (p != NULL)
3435 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003436 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003437 if (ea.cmd != NULL)
3438 {
3439 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3440 ea.force_enc = 11;
3441 tofree = ea.cmd;
3442 }
3443 }
3444
3445 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3446 if (p != NULL)
3447 get_bad_opt(p, &ea);
3448
3449 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3450 ea.force_bin = FORCE_BIN;
3451 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3452 ea.force_bin = FORCE_BIN;
3453 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3454 ea.force_bin = FORCE_NOBIN;
3455 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3456 ea.force_bin = FORCE_NOBIN;
3457 }
3458
3459 /* open in new window, like ":split fname" */
3460 if (ea.cmd == NULL)
3461 ea.cmd = (char_u *)"split";
3462 ea.arg = fname;
3463 ea.cmdidx = CMD_split;
3464 ex_splitview(&ea);
3465
3466 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003467}
3468
3469/*
3470 * Handles a function call from the job running in a terminal.
3471 * "item" is the function name, "item->li_next" has the arguments.
3472 */
3473 static void
3474handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3475{
3476 char_u *func;
3477 typval_T argvars[2];
3478 typval_T rettv;
3479 int doesrange;
3480
3481 if (item->li_next == NULL)
3482 {
3483 ch_log(channel, "Missing function arguments for call");
3484 return;
3485 }
3486 func = get_tv_string(&item->li_tv);
3487
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003488 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003489 {
3490 ch_log(channel, "Invalid function name: %s", func);
3491 return;
3492 }
3493
3494 argvars[0].v_type = VAR_NUMBER;
3495 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3496 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003497 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003498 2, argvars, /* argv_func */ NULL,
3499 /* firstline */ 1, /* lastline */ 1,
3500 &doesrange, /* evaluate */ TRUE,
3501 /* partial */ NULL, /* selfdict */ NULL) == OK)
3502 {
3503 clear_tv(&rettv);
3504 ch_log(channel, "Function %s called", func);
3505 }
3506 else
3507 ch_log(channel, "Calling function %s failed", func);
3508}
3509
3510/*
3511 * Called by libvterm when it cannot recognize an OSC sequence.
3512 * We recognize a terminal API command.
3513 */
3514 static int
3515parse_osc(const char *command, size_t cmdlen, void *user)
3516{
3517 term_T *term = (term_T *)user;
3518 js_read_T reader;
3519 typval_T tv;
3520 channel_T *channel = term->tl_job == NULL ? NULL
3521 : term->tl_job->jv_channel;
3522
3523 /* We recognize only OSC 5 1 ; {command} */
3524 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3525 return 0; /* not handled */
3526
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003527 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003528 if (reader.js_buf == NULL)
3529 return 1;
3530 reader.js_fill = NULL;
3531 reader.js_used = 0;
3532 if (json_decode(&reader, &tv, 0) == OK
3533 && tv.v_type == VAR_LIST
3534 && tv.vval.v_list != NULL)
3535 {
3536 listitem_T *item = tv.vval.v_list->lv_first;
3537
3538 if (item == NULL)
3539 ch_log(channel, "Missing command");
3540 else
3541 {
3542 char_u *cmd = get_tv_string(&item->li_tv);
3543
Bram Moolenaara997b452018-04-17 23:24:06 +02003544 /* Make sure an invoked command doesn't delete the buffer (and the
3545 * terminal) under our fingers. */
3546 ++term->tl_buffer->b_locked;
3547
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003548 item = item->li_next;
3549 if (item == NULL)
3550 ch_log(channel, "Missing argument for %s", cmd);
3551 else if (STRCMP(cmd, "drop") == 0)
3552 handle_drop_command(item);
3553 else if (STRCMP(cmd, "call") == 0)
3554 handle_call_command(term, channel, item);
3555 else
3556 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003557 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003558 }
3559 }
3560 else
3561 ch_log(channel, "Invalid JSON received");
3562
3563 vim_free(reader.js_buf);
3564 clear_tv(&tv);
3565 return 1;
3566}
3567
3568static VTermParserCallbacks parser_fallbacks = {
3569 NULL, /* text */
3570 NULL, /* control */
3571 NULL, /* escape */
3572 NULL, /* csi */
3573 parse_osc, /* osc */
3574 NULL, /* dcs */
3575 NULL /* resize */
3576};
3577
3578/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003579 * Use Vim's allocation functions for vterm so profiling works.
3580 */
3581 static void *
3582vterm_malloc(size_t size, void *data UNUSED)
3583{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003584 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003585}
3586
3587 static void
3588vterm_memfree(void *ptr, void *data UNUSED)
3589{
3590 vim_free(ptr);
3591}
3592
3593static VTermAllocatorFunctions vterm_allocator = {
3594 &vterm_malloc,
3595 &vterm_memfree
3596};
3597
3598/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003599 * Create a new vterm and initialize it.
3600 */
3601 static void
3602create_vterm(term_T *term, int rows, int cols)
3603{
3604 VTerm *vterm;
3605 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003606 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003607 VTermValue value;
3608
Bram Moolenaar756ef112018-04-10 12:04:27 +02003609 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003610 term->tl_vterm = vterm;
3611 screen = vterm_obtain_screen(vterm);
3612 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3613 /* TODO: depends on 'encoding'. */
3614 vterm_set_utf8(vterm, 1);
3615
3616 init_default_colors(term);
3617
3618 vterm_state_set_default_colors(
3619 vterm_obtain_state(vterm),
3620 &term->tl_default_color.fg,
3621 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003622
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003623 if (t_colors >= 16)
3624 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3625
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003626 /* Required to initialize most things. */
3627 vterm_screen_reset(screen, 1 /* hard */);
3628
3629 /* Allow using alternate screen. */
3630 vterm_screen_enable_altscreen(screen, 1);
3631
3632 /* For unix do not use a blinking cursor. In an xterm this causes the
3633 * cursor to blink if it's blinking in the xterm.
3634 * For Windows we respect the system wide setting. */
3635#ifdef WIN3264
3636 if (GetCaretBlinkTime() == INFINITE)
3637 value.boolean = 0;
3638 else
3639 value.boolean = 1;
3640#else
3641 value.boolean = 0;
3642#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003643 state = vterm_obtain_state(vterm);
3644 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3645 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003646}
3647
3648/*
3649 * Return the text to show for the buffer name and status.
3650 */
3651 char_u *
3652term_get_status_text(term_T *term)
3653{
3654 if (term->tl_status_text == NULL)
3655 {
3656 char_u *txt;
3657 size_t len;
3658
3659 if (term->tl_normal_mode)
3660 {
3661 if (term_job_running(term))
3662 txt = (char_u *)_("Terminal");
3663 else
3664 txt = (char_u *)_("Terminal-finished");
3665 }
3666 else if (term->tl_title != NULL)
3667 txt = term->tl_title;
3668 else if (term_none_open(term))
3669 txt = (char_u *)_("active");
3670 else if (term_job_running(term))
3671 txt = (char_u *)_("running");
3672 else
3673 txt = (char_u *)_("finished");
3674 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3675 term->tl_status_text = alloc((int)len);
3676 if (term->tl_status_text != NULL)
3677 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3678 term->tl_buffer->b_fname, txt);
3679 }
3680 return term->tl_status_text;
3681}
3682
3683/*
3684 * Mark references in jobs of terminals.
3685 */
3686 int
3687set_ref_in_term(int copyID)
3688{
3689 int abort = FALSE;
3690 term_T *term;
3691 typval_T tv;
3692
3693 for (term = first_term; term != NULL; term = term->tl_next)
3694 if (term->tl_job != NULL)
3695 {
3696 tv.v_type = VAR_JOB;
3697 tv.vval.v_job = term->tl_job;
3698 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3699 }
3700 return abort;
3701}
3702
3703/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003704 * Cache "Terminal" highlight group colors.
3705 */
3706 void
3707set_terminal_default_colors(int cterm_fg, int cterm_bg)
3708{
3709 term_default_cterm_fg = cterm_fg - 1;
3710 term_default_cterm_bg = cterm_bg - 1;
3711}
3712
3713/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003714 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003715 * Returns NULL when the buffer is not for a terminal window and logs a message
3716 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003717 */
3718 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003719term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003720{
3721 buf_T *buf;
3722
3723 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3724 ++emsg_off;
3725 buf = get_buf_tv(&argvars[0], FALSE);
3726 --emsg_off;
3727 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003728 {
3729 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003730 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003731 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003732 return buf;
3733}
3734
Bram Moolenaard96ff162018-02-18 22:13:29 +01003735 static int
3736same_color(VTermColor *a, VTermColor *b)
3737{
3738 return a->red == b->red
3739 && a->green == b->green
3740 && a->blue == b->blue
3741 && a->ansi_index == b->ansi_index;
3742}
3743
3744 static void
3745dump_term_color(FILE *fd, VTermColor *color)
3746{
3747 fprintf(fd, "%02x%02x%02x%d",
3748 (int)color->red, (int)color->green, (int)color->blue,
3749 (int)color->ansi_index);
3750}
3751
3752/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003753 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003754 *
3755 * Each screen cell in full is:
3756 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3757 * {characters} is a space for an empty cell
3758 * For a double-width character "+" is changed to "*" and the next cell is
3759 * skipped.
3760 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3761 * when "&" use the same as the previous cell.
3762 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3763 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3764 * {color-idx} is a number from 0 to 255
3765 *
3766 * Screen cell with same width, attributes and color as the previous one:
3767 * |{characters}
3768 *
3769 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3770 *
3771 * Repeating the previous screen cell:
3772 * @{count}
3773 */
3774 void
3775f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3776{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003777 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003778 term_T *term;
3779 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003780 int max_height = 0;
3781 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003782 stat_T st;
3783 FILE *fd;
3784 VTermPos pos;
3785 VTermScreen *screen;
3786 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003787 VTermState *state;
3788 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003789
3790 if (check_restricted() || check_secure())
3791 return;
3792 if (buf == NULL)
3793 return;
3794 term = buf->b_term;
3795
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003796 if (argvars[2].v_type != VAR_UNKNOWN)
3797 {
3798 dict_T *d;
3799
3800 if (argvars[2].v_type != VAR_DICT)
3801 {
3802 EMSG(_(e_dictreq));
3803 return;
3804 }
3805 d = argvars[2].vval.v_dict;
3806 if (d != NULL)
3807 {
3808 max_height = get_dict_number(d, (char_u *)"rows");
3809 max_width = get_dict_number(d, (char_u *)"columns");
3810 }
3811 }
3812
Bram Moolenaard96ff162018-02-18 22:13:29 +01003813 fname = get_tv_string_chk(&argvars[1]);
3814 if (fname == NULL)
3815 return;
3816 if (mch_stat((char *)fname, &st) >= 0)
3817 {
3818 EMSG2(_("E953: File exists: %s"), fname);
3819 return;
3820 }
3821
Bram Moolenaard96ff162018-02-18 22:13:29 +01003822 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3823 {
3824 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3825 return;
3826 }
3827
3828 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3829
3830 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003831 state = vterm_obtain_state(term->tl_vterm);
3832 vterm_state_get_cursorpos(state, &cursor_pos);
3833
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003834 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3835 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003836 {
3837 int repeat = 0;
3838
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003839 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3840 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003841 {
3842 VTermScreenCell cell;
3843 int same_attr;
3844 int same_chars = TRUE;
3845 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003846 int is_cursor_pos = (pos.col == cursor_pos.col
3847 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003848
3849 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3850 vim_memset(&cell, 0, sizeof(cell));
3851
3852 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3853 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003854 int c = cell.chars[i];
3855 int pc = prev_cell.chars[i];
3856
3857 /* For the first character NUL is the same as space. */
3858 if (i == 0)
3859 {
3860 c = (c == NUL) ? ' ' : c;
3861 pc = (pc == NUL) ? ' ' : pc;
3862 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003863 if (cell.chars[i] != prev_cell.chars[i])
3864 same_chars = FALSE;
3865 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3866 break;
3867 }
3868 same_attr = vtermAttr2hl(cell.attrs)
3869 == vtermAttr2hl(prev_cell.attrs)
3870 && same_color(&cell.fg, &prev_cell.fg)
3871 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003872 if (same_chars && cell.width == prev_cell.width && same_attr
3873 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003874 {
3875 ++repeat;
3876 }
3877 else
3878 {
3879 if (repeat > 0)
3880 {
3881 fprintf(fd, "@%d", repeat);
3882 repeat = 0;
3883 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003884 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003885
3886 if (cell.chars[0] == NUL)
3887 fputs(" ", fd);
3888 else
3889 {
3890 char_u charbuf[10];
3891 int len;
3892
3893 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3894 && cell.chars[i] != NUL; ++i)
3895 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003896 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003897 fwrite(charbuf, len, 1, fd);
3898 }
3899 }
3900
3901 /* When only the characters differ we don't write anything, the
3902 * following "|", "@" or NL will indicate using the same
3903 * attributes. */
3904 if (cell.width != prev_cell.width || !same_attr)
3905 {
3906 if (cell.width == 2)
3907 {
3908 fputs("*", fd);
3909 ++pos.col;
3910 }
3911 else
3912 fputs("+", fd);
3913
3914 if (same_attr)
3915 {
3916 fputs("&", fd);
3917 }
3918 else
3919 {
3920 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3921 if (same_color(&cell.fg, &prev_cell.fg))
3922 fputs("&", fd);
3923 else
3924 {
3925 fputs("#", fd);
3926 dump_term_color(fd, &cell.fg);
3927 }
3928 if (same_color(&cell.bg, &prev_cell.bg))
3929 fputs("&", fd);
3930 else
3931 {
3932 fputs("#", fd);
3933 dump_term_color(fd, &cell.bg);
3934 }
3935 }
3936 }
3937
3938 prev_cell = cell;
3939 }
3940 }
3941 if (repeat > 0)
3942 fprintf(fd, "@%d", repeat);
3943 fputs("\n", fd);
3944 }
3945
3946 fclose(fd);
3947}
3948
3949/*
3950 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3951 */
3952 static void
3953dump_is_corrupt(garray_T *gap)
3954{
3955 ga_concat(gap, (char_u *)"CORRUPT");
3956}
3957
3958 static void
3959append_cell(garray_T *gap, cellattr_T *cell)
3960{
3961 if (ga_grow(gap, 1) == OK)
3962 {
3963 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3964 ++gap->ga_len;
3965 }
3966}
3967
3968/*
3969 * Read the dump file from "fd" and append lines to the current buffer.
3970 * Return the cell width of the longest line.
3971 */
3972 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003973read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003974{
3975 int c;
3976 garray_T ga_text;
3977 garray_T ga_cell;
3978 char_u *prev_char = NULL;
3979 int attr = 0;
3980 cellattr_T cell;
3981 term_T *term = curbuf->b_term;
3982 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003983 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003984
3985 ga_init2(&ga_text, 1, 90);
3986 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3987 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003988 cursor_pos->row = -1;
3989 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003990
3991 c = fgetc(fd);
3992 for (;;)
3993 {
3994 if (c == EOF)
3995 break;
3996 if (c == '\n')
3997 {
3998 /* End of a line: append it to the buffer. */
3999 if (ga_text.ga_data == NULL)
4000 dump_is_corrupt(&ga_text);
4001 if (ga_grow(&term->tl_scrollback, 1) == OK)
4002 {
4003 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4004 + term->tl_scrollback.ga_len;
4005
4006 if (max_cells < ga_cell.ga_len)
4007 max_cells = ga_cell.ga_len;
4008 line->sb_cols = ga_cell.ga_len;
4009 line->sb_cells = ga_cell.ga_data;
4010 line->sb_fill_attr = term->tl_default_color;
4011 ++term->tl_scrollback.ga_len;
4012 ga_init(&ga_cell);
4013
4014 ga_append(&ga_text, NUL);
4015 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4016 ga_text.ga_len, FALSE);
4017 }
4018 else
4019 ga_clear(&ga_cell);
4020 ga_text.ga_len = 0;
4021
4022 c = fgetc(fd);
4023 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004024 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004025 {
4026 int prev_len = ga_text.ga_len;
4027
Bram Moolenaar9271d052018-02-25 21:39:46 +01004028 if (c == '>')
4029 {
4030 if (cursor_pos->row != -1)
4031 dump_is_corrupt(&ga_text); /* duplicate cursor */
4032 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4033 cursor_pos->col = ga_cell.ga_len;
4034 }
4035
Bram Moolenaard96ff162018-02-18 22:13:29 +01004036 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4037 c = fgetc(fd);
4038 if (c != EOF)
4039 ga_append(&ga_text, c);
4040 for (;;)
4041 {
4042 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004043 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004044 || c == EOF || c == '\n')
4045 break;
4046 ga_append(&ga_text, c);
4047 }
4048
4049 /* save the character for repeating it */
4050 vim_free(prev_char);
4051 if (ga_text.ga_data != NULL)
4052 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4053 ga_text.ga_len - prev_len);
4054
Bram Moolenaar9271d052018-02-25 21:39:46 +01004055 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004056 {
4057 /* use all attributes from previous cell */
4058 }
4059 else if (c == '+' || c == '*')
4060 {
4061 int is_bg;
4062
4063 cell.width = c == '+' ? 1 : 2;
4064
4065 c = fgetc(fd);
4066 if (c == '&')
4067 {
4068 /* use same attr as previous cell */
4069 c = fgetc(fd);
4070 }
4071 else if (isdigit(c))
4072 {
4073 /* get the decimal attribute */
4074 attr = 0;
4075 while (isdigit(c))
4076 {
4077 attr = attr * 10 + (c - '0');
4078 c = fgetc(fd);
4079 }
4080 hl2vtermAttr(attr, &cell);
4081 }
4082 else
4083 dump_is_corrupt(&ga_text);
4084
4085 /* is_bg == 0: fg, is_bg == 1: bg */
4086 for (is_bg = 0; is_bg <= 1; ++is_bg)
4087 {
4088 if (c == '&')
4089 {
4090 /* use same color as previous cell */
4091 c = fgetc(fd);
4092 }
4093 else if (c == '#')
4094 {
4095 int red, green, blue, index = 0;
4096
4097 c = fgetc(fd);
4098 red = hex2nr(c);
4099 c = fgetc(fd);
4100 red = (red << 4) + hex2nr(c);
4101 c = fgetc(fd);
4102 green = hex2nr(c);
4103 c = fgetc(fd);
4104 green = (green << 4) + hex2nr(c);
4105 c = fgetc(fd);
4106 blue = hex2nr(c);
4107 c = fgetc(fd);
4108 blue = (blue << 4) + hex2nr(c);
4109 c = fgetc(fd);
4110 if (!isdigit(c))
4111 dump_is_corrupt(&ga_text);
4112 while (isdigit(c))
4113 {
4114 index = index * 10 + (c - '0');
4115 c = fgetc(fd);
4116 }
4117
4118 if (is_bg)
4119 {
4120 cell.bg.red = red;
4121 cell.bg.green = green;
4122 cell.bg.blue = blue;
4123 cell.bg.ansi_index = index;
4124 }
4125 else
4126 {
4127 cell.fg.red = red;
4128 cell.fg.green = green;
4129 cell.fg.blue = blue;
4130 cell.fg.ansi_index = index;
4131 }
4132 }
4133 else
4134 dump_is_corrupt(&ga_text);
4135 }
4136 }
4137 else
4138 dump_is_corrupt(&ga_text);
4139
4140 append_cell(&ga_cell, &cell);
4141 }
4142 else if (c == '@')
4143 {
4144 if (prev_char == NULL)
4145 dump_is_corrupt(&ga_text);
4146 else
4147 {
4148 int count = 0;
4149
4150 /* repeat previous character, get the count */
4151 for (;;)
4152 {
4153 c = fgetc(fd);
4154 if (!isdigit(c))
4155 break;
4156 count = count * 10 + (c - '0');
4157 }
4158
4159 while (count-- > 0)
4160 {
4161 ga_concat(&ga_text, prev_char);
4162 append_cell(&ga_cell, &cell);
4163 }
4164 }
4165 }
4166 else
4167 {
4168 dump_is_corrupt(&ga_text);
4169 c = fgetc(fd);
4170 }
4171 }
4172
4173 if (ga_text.ga_len > 0)
4174 {
4175 /* trailing characters after last NL */
4176 dump_is_corrupt(&ga_text);
4177 ga_append(&ga_text, NUL);
4178 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4179 ga_text.ga_len, FALSE);
4180 }
4181
4182 ga_clear(&ga_text);
4183 vim_free(prev_char);
4184
4185 return max_cells;
4186}
4187
4188/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004189 * Return an allocated string with at least "text_width" "=" characters and
4190 * "fname" inserted in the middle.
4191 */
4192 static char_u *
4193get_separator(int text_width, char_u *fname)
4194{
4195 int width = MAX(text_width, curwin->w_width);
4196 char_u *textline;
4197 int fname_size;
4198 char_u *p = fname;
4199 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004200 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004201
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004202 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004203 if (textline == NULL)
4204 return NULL;
4205
4206 fname_size = vim_strsize(fname);
4207 if (fname_size < width - 8)
4208 {
4209 /* enough room, don't use the full window width */
4210 width = MAX(text_width, fname_size + 8);
4211 }
4212 else if (fname_size > width - 8)
4213 {
4214 /* full name doesn't fit, use only the tail */
4215 p = gettail(fname);
4216 fname_size = vim_strsize(p);
4217 }
4218 /* skip characters until the name fits */
4219 while (fname_size > width - 8)
4220 {
4221 p += (*mb_ptr2len)(p);
4222 fname_size = vim_strsize(p);
4223 }
4224
4225 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4226 textline[i] = '=';
4227 textline[i++] = ' ';
4228
4229 STRCPY(textline + i, p);
4230 off = STRLEN(textline);
4231 textline[off] = ' ';
4232 for (i = 1; i < (width - fname_size) / 2; ++i)
4233 textline[off + i] = '=';
4234 textline[off + i] = NUL;
4235
4236 return textline;
4237}
4238
4239/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004240 * Common for "term_dumpdiff()" and "term_dumpload()".
4241 */
4242 static void
4243term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4244{
4245 jobopt_T opt;
4246 buf_T *buf;
4247 char_u buf1[NUMBUFLEN];
4248 char_u buf2[NUMBUFLEN];
4249 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004250 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004251 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004252 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004253 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004254 char_u *textline = NULL;
4255
4256 /* First open the files. If this fails bail out. */
4257 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4258 if (do_diff)
4259 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4260 if (fname1 == NULL || (do_diff && fname2 == NULL))
4261 {
4262 EMSG(_(e_invarg));
4263 return;
4264 }
4265 fd1 = mch_fopen((char *)fname1, READBIN);
4266 if (fd1 == NULL)
4267 {
4268 EMSG2(_(e_notread), fname1);
4269 return;
4270 }
4271 if (do_diff)
4272 {
4273 fd2 = mch_fopen((char *)fname2, READBIN);
4274 if (fd2 == NULL)
4275 {
4276 fclose(fd1);
4277 EMSG2(_(e_notread), fname2);
4278 return;
4279 }
4280 }
4281
4282 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004283 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4284 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4285 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4286 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4287 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004288
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004289 if (opt.jo_term_name == NULL)
4290 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004291 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004292
Bram Moolenaarb571c632018-03-21 22:27:59 +01004293 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004294 if (fname_tofree != NULL)
4295 {
4296 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4297 opt.jo_term_name = fname_tofree;
4298 }
4299 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004300
Bram Moolenaar13568252018-03-16 20:46:58 +01004301 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004302 if (buf != NULL && buf->b_term != NULL)
4303 {
4304 int i;
4305 linenr_T bot_lnum;
4306 linenr_T lnum;
4307 term_T *term = buf->b_term;
4308 int width;
4309 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004310 VTermPos cursor_pos1;
4311 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004312
Bram Moolenaar52acb112018-03-18 19:20:22 +01004313 init_default_colors(term);
4314
Bram Moolenaard96ff162018-02-18 22:13:29 +01004315 rettv->vval.v_number = buf->b_fnum;
4316
4317 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004318 width = read_dump_file(fd1, &cursor_pos1);
4319
4320 /* position the cursor */
4321 if (cursor_pos1.row >= 0)
4322 {
4323 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4324 coladvance(cursor_pos1.col);
4325 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004326
4327 /* Delete the empty line that was in the empty buffer. */
4328 ml_delete(1, FALSE);
4329
4330 /* For term_dumpload() we are done here. */
4331 if (!do_diff)
4332 goto theend;
4333
4334 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4335
Bram Moolenaar4a696342018-04-05 18:45:26 +02004336 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004337 if (textline == NULL)
4338 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004339 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4340 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4341 vim_free(textline);
4342
4343 textline = get_separator(width, fname2);
4344 if (textline == NULL)
4345 goto theend;
4346 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4347 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004348 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004349
4350 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004351 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004352 if (width2 > width)
4353 {
4354 vim_free(textline);
4355 textline = alloc(width2 + 1);
4356 if (textline == NULL)
4357 goto theend;
4358 width = width2;
4359 textline[width] = NUL;
4360 }
4361 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4362
4363 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4364 {
4365 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4366 {
4367 /* bottom part has fewer rows, fill with "-" */
4368 for (i = 0; i < width; ++i)
4369 textline[i] = '-';
4370 }
4371 else
4372 {
4373 char_u *line1;
4374 char_u *line2;
4375 char_u *p1;
4376 char_u *p2;
4377 int col;
4378 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4379 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4380 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4381 ->sb_cells;
4382
4383 /* Make a copy, getting the second line will invalidate it. */
4384 line1 = vim_strsave(ml_get(lnum));
4385 if (line1 == NULL)
4386 break;
4387 p1 = line1;
4388
4389 line2 = ml_get(lnum + bot_lnum);
4390 p2 = line2;
4391 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4392 {
4393 int len1 = utfc_ptr2len(p1);
4394 int len2 = utfc_ptr2len(p2);
4395
4396 textline[col] = ' ';
4397 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004398 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004399 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004400 else if (lnum == cursor_pos1.row + 1
4401 && col == cursor_pos1.col
4402 && (cursor_pos1.row != cursor_pos2.row
4403 || cursor_pos1.col != cursor_pos2.col))
4404 /* cursor in first but not in second */
4405 textline[col] = '>';
4406 else if (lnum == cursor_pos2.row + 1
4407 && col == cursor_pos2.col
4408 && (cursor_pos1.row != cursor_pos2.row
4409 || cursor_pos1.col != cursor_pos2.col))
4410 /* cursor in second but not in first */
4411 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004412 else if (cellattr1 != NULL && cellattr2 != NULL)
4413 {
4414 if ((cellattr1 + col)->width
4415 != (cellattr2 + col)->width)
4416 textline[col] = 'w';
4417 else if (!same_color(&(cellattr1 + col)->fg,
4418 &(cellattr2 + col)->fg))
4419 textline[col] = 'f';
4420 else if (!same_color(&(cellattr1 + col)->bg,
4421 &(cellattr2 + col)->bg))
4422 textline[col] = 'b';
4423 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4424 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4425 textline[col] = 'a';
4426 }
4427 p1 += len1;
4428 p2 += len2;
4429 /* TODO: handle different width */
4430 }
4431 vim_free(line1);
4432
4433 while (col < width)
4434 {
4435 if (*p1 == NUL && *p2 == NUL)
4436 textline[col] = '?';
4437 else if (*p1 == NUL)
4438 {
4439 textline[col] = '+';
4440 p2 += utfc_ptr2len(p2);
4441 }
4442 else
4443 {
4444 textline[col] = '-';
4445 p1 += utfc_ptr2len(p1);
4446 }
4447 ++col;
4448 }
4449 }
4450 if (add_empty_scrollback(term, &term->tl_default_color,
4451 term->tl_top_diff_rows) == OK)
4452 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4453 ++bot_lnum;
4454 }
4455
4456 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4457 {
4458 /* bottom part has more rows, fill with "+" */
4459 for (i = 0; i < width; ++i)
4460 textline[i] = '+';
4461 if (add_empty_scrollback(term, &term->tl_default_color,
4462 term->tl_top_diff_rows) == OK)
4463 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4464 ++lnum;
4465 ++bot_lnum;
4466 }
4467
4468 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004469
4470 /* looks better without wrapping */
4471 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004472 }
4473
4474theend:
4475 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004476 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004477 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004478 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004479 fclose(fd2);
4480}
4481
4482/*
4483 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4484 * bottom files.
4485 * Return FAIL when this is not possible.
4486 */
4487 int
4488term_swap_diff()
4489{
4490 term_T *term = curbuf->b_term;
4491 linenr_T line_count;
4492 linenr_T top_rows;
4493 linenr_T bot_rows;
4494 linenr_T bot_start;
4495 linenr_T lnum;
4496 char_u *p;
4497 sb_line_T *sb_line;
4498
4499 if (term == NULL
4500 || !term_is_finished(curbuf)
4501 || term->tl_top_diff_rows == 0
4502 || term->tl_scrollback.ga_len == 0)
4503 return FAIL;
4504
4505 line_count = curbuf->b_ml.ml_line_count;
4506 top_rows = term->tl_top_diff_rows;
4507 bot_rows = term->tl_bot_diff_rows;
4508 bot_start = line_count - bot_rows;
4509 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4510
4511 /* move lines from top to above the bottom part */
4512 for (lnum = 1; lnum <= top_rows; ++lnum)
4513 {
4514 p = vim_strsave(ml_get(1));
4515 if (p == NULL)
4516 return OK;
4517 ml_append(bot_start, p, 0, FALSE);
4518 ml_delete(1, FALSE);
4519 vim_free(p);
4520 }
4521
4522 /* move lines from bottom to the top */
4523 for (lnum = 1; lnum <= bot_rows; ++lnum)
4524 {
4525 p = vim_strsave(ml_get(bot_start + lnum));
4526 if (p == NULL)
4527 return OK;
4528 ml_delete(bot_start + lnum, FALSE);
4529 ml_append(lnum - 1, p, 0, FALSE);
4530 vim_free(p);
4531 }
4532
4533 if (top_rows == bot_rows)
4534 {
4535 /* rows counts are equal, can swap cell properties */
4536 for (lnum = 0; lnum < top_rows; ++lnum)
4537 {
4538 sb_line_T temp;
4539
4540 temp = *(sb_line + lnum);
4541 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4542 *(sb_line + bot_start + lnum) = temp;
4543 }
4544 }
4545 else
4546 {
4547 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4548 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4549
4550 /* need to copy cell properties into temp memory */
4551 if (temp != NULL)
4552 {
4553 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4554 mch_memmove(term->tl_scrollback.ga_data,
4555 temp + bot_start,
4556 sizeof(sb_line_T) * bot_rows);
4557 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4558 temp + top_rows,
4559 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4560 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4561 + line_count - top_rows,
4562 temp,
4563 sizeof(sb_line_T) * top_rows);
4564 vim_free(temp);
4565 }
4566 }
4567
4568 term->tl_top_diff_rows = bot_rows;
4569 term->tl_bot_diff_rows = top_rows;
4570
4571 update_screen(NOT_VALID);
4572 return OK;
4573}
4574
4575/*
4576 * "term_dumpdiff(filename, filename, options)" function
4577 */
4578 void
4579f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4580{
4581 term_load_dump(argvars, rettv, TRUE);
4582}
4583
4584/*
4585 * "term_dumpload(filename, options)" function
4586 */
4587 void
4588f_term_dumpload(typval_T *argvars, typval_T *rettv)
4589{
4590 term_load_dump(argvars, rettv, FALSE);
4591}
4592
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004593/*
4594 * "term_getaltscreen(buf)" function
4595 */
4596 void
4597f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4598{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004599 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004600
4601 if (buf == NULL)
4602 return;
4603 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4604}
4605
4606/*
4607 * "term_getattr(attr, name)" function
4608 */
4609 void
4610f_term_getattr(typval_T *argvars, typval_T *rettv)
4611{
4612 int attr;
4613 size_t i;
4614 char_u *name;
4615
4616 static struct {
4617 char *name;
4618 int attr;
4619 } attrs[] = {
4620 {"bold", HL_BOLD},
4621 {"italic", HL_ITALIC},
4622 {"underline", HL_UNDERLINE},
4623 {"strike", HL_STRIKETHROUGH},
4624 {"reverse", HL_INVERSE},
4625 };
4626
4627 attr = get_tv_number(&argvars[0]);
4628 name = get_tv_string_chk(&argvars[1]);
4629 if (name == NULL)
4630 return;
4631
4632 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4633 if (STRCMP(name, attrs[i].name) == 0)
4634 {
4635 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4636 break;
4637 }
4638}
4639
4640/*
4641 * "term_getcursor(buf)" function
4642 */
4643 void
4644f_term_getcursor(typval_T *argvars, typval_T *rettv)
4645{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004646 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004647 term_T *term;
4648 list_T *l;
4649 dict_T *d;
4650
4651 if (rettv_list_alloc(rettv) == FAIL)
4652 return;
4653 if (buf == NULL)
4654 return;
4655 term = buf->b_term;
4656
4657 l = rettv->vval.v_list;
4658 list_append_number(l, term->tl_cursor_pos.row + 1);
4659 list_append_number(l, term->tl_cursor_pos.col + 1);
4660
4661 d = dict_alloc();
4662 if (d != NULL)
4663 {
4664 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4665 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4666 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4667 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4668 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4669 ? (char_u *)"" : term->tl_cursor_color);
4670 list_append_dict(l, d);
4671 }
4672}
4673
4674/*
4675 * "term_getjob(buf)" function
4676 */
4677 void
4678f_term_getjob(typval_T *argvars, typval_T *rettv)
4679{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004680 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004681
4682 rettv->v_type = VAR_JOB;
4683 rettv->vval.v_job = NULL;
4684 if (buf == NULL)
4685 return;
4686
4687 rettv->vval.v_job = buf->b_term->tl_job;
4688 if (rettv->vval.v_job != NULL)
4689 ++rettv->vval.v_job->jv_refcount;
4690}
4691
4692 static int
4693get_row_number(typval_T *tv, term_T *term)
4694{
4695 if (tv->v_type == VAR_STRING
4696 && tv->vval.v_string != NULL
4697 && STRCMP(tv->vval.v_string, ".") == 0)
4698 return term->tl_cursor_pos.row;
4699 return (int)get_tv_number(tv) - 1;
4700}
4701
4702/*
4703 * "term_getline(buf, row)" function
4704 */
4705 void
4706f_term_getline(typval_T *argvars, typval_T *rettv)
4707{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004708 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004709 term_T *term;
4710 int row;
4711
4712 rettv->v_type = VAR_STRING;
4713 if (buf == NULL)
4714 return;
4715 term = buf->b_term;
4716 row = get_row_number(&argvars[1], term);
4717
4718 if (term->tl_vterm == NULL)
4719 {
4720 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4721
4722 /* vterm is finished, get the text from the buffer */
4723 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4724 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4725 }
4726 else
4727 {
4728 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4729 VTermRect rect;
4730 int len;
4731 char_u *p;
4732
4733 if (row < 0 || row >= term->tl_rows)
4734 return;
4735 len = term->tl_cols * MB_MAXBYTES + 1;
4736 p = alloc(len);
4737 if (p == NULL)
4738 return;
4739 rettv->vval.v_string = p;
4740
4741 rect.start_col = 0;
4742 rect.end_col = term->tl_cols;
4743 rect.start_row = row;
4744 rect.end_row = row + 1;
4745 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4746 }
4747}
4748
4749/*
4750 * "term_getscrolled(buf)" function
4751 */
4752 void
4753f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4754{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004755 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004756
4757 if (buf == NULL)
4758 return;
4759 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4760}
4761
4762/*
4763 * "term_getsize(buf)" function
4764 */
4765 void
4766f_term_getsize(typval_T *argvars, typval_T *rettv)
4767{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004768 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004769 list_T *l;
4770
4771 if (rettv_list_alloc(rettv) == FAIL)
4772 return;
4773 if (buf == NULL)
4774 return;
4775
4776 l = rettv->vval.v_list;
4777 list_append_number(l, buf->b_term->tl_rows);
4778 list_append_number(l, buf->b_term->tl_cols);
4779}
4780
4781/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004782 * "term_setsize(buf, rows, cols)" function
4783 */
4784 void
4785f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4786{
4787 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4788 term_T *term;
4789 varnumber_T rows, cols;
4790
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004791 if (buf == NULL)
4792 {
4793 EMSG(_("E955: Not a terminal buffer"));
4794 return;
4795 }
4796 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004797 return;
4798 term = buf->b_term;
4799 rows = get_tv_number(&argvars[1]);
4800 rows = rows <= 0 ? term->tl_rows : rows;
4801 cols = get_tv_number(&argvars[2]);
4802 cols = cols <= 0 ? term->tl_cols : cols;
4803 vterm_set_size(term->tl_vterm, rows, cols);
4804 /* handle_resize() will resize the windows */
4805
4806 /* Get and remember the size we ended up with. Update the pty. */
4807 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4808 term_report_winsize(term, term->tl_rows, term->tl_cols);
4809}
4810
4811/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004812 * "term_getstatus(buf)" function
4813 */
4814 void
4815f_term_getstatus(typval_T *argvars, typval_T *rettv)
4816{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004817 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004818 term_T *term;
4819 char_u val[100];
4820
4821 rettv->v_type = VAR_STRING;
4822 if (buf == NULL)
4823 return;
4824 term = buf->b_term;
4825
4826 if (term_job_running(term))
4827 STRCPY(val, "running");
4828 else
4829 STRCPY(val, "finished");
4830 if (term->tl_normal_mode)
4831 STRCAT(val, ",normal");
4832 rettv->vval.v_string = vim_strsave(val);
4833}
4834
4835/*
4836 * "term_gettitle(buf)" function
4837 */
4838 void
4839f_term_gettitle(typval_T *argvars, typval_T *rettv)
4840{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004841 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004842
4843 rettv->v_type = VAR_STRING;
4844 if (buf == NULL)
4845 return;
4846
4847 if (buf->b_term->tl_title != NULL)
4848 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4849}
4850
4851/*
4852 * "term_gettty(buf)" function
4853 */
4854 void
4855f_term_gettty(typval_T *argvars, typval_T *rettv)
4856{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004857 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004858 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004859 int num = 0;
4860
4861 rettv->v_type = VAR_STRING;
4862 if (buf == NULL)
4863 return;
4864 if (argvars[1].v_type != VAR_UNKNOWN)
4865 num = get_tv_number(&argvars[1]);
4866
4867 switch (num)
4868 {
4869 case 0:
4870 if (buf->b_term->tl_job != NULL)
4871 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004872 break;
4873 case 1:
4874 if (buf->b_term->tl_job != NULL)
4875 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004876 break;
4877 default:
4878 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4879 return;
4880 }
4881 if (p != NULL)
4882 rettv->vval.v_string = vim_strsave(p);
4883}
4884
4885/*
4886 * "term_list()" function
4887 */
4888 void
4889f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4890{
4891 term_T *tp;
4892 list_T *l;
4893
4894 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4895 return;
4896
4897 l = rettv->vval.v_list;
4898 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4899 if (tp != NULL && tp->tl_buffer != NULL)
4900 if (list_append_number(l,
4901 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4902 return;
4903}
4904
4905/*
4906 * "term_scrape(buf, row)" function
4907 */
4908 void
4909f_term_scrape(typval_T *argvars, typval_T *rettv)
4910{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004911 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004912 VTermScreen *screen = NULL;
4913 VTermPos pos;
4914 list_T *l;
4915 term_T *term;
4916 char_u *p;
4917 sb_line_T *line;
4918
4919 if (rettv_list_alloc(rettv) == FAIL)
4920 return;
4921 if (buf == NULL)
4922 return;
4923 term = buf->b_term;
4924
4925 l = rettv->vval.v_list;
4926 pos.row = get_row_number(&argvars[1], term);
4927
4928 if (term->tl_vterm != NULL)
4929 {
4930 screen = vterm_obtain_screen(term->tl_vterm);
4931 p = NULL;
4932 line = NULL;
4933 }
4934 else
4935 {
4936 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4937
4938 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4939 return;
4940 p = ml_get_buf(buf, lnum + 1, FALSE);
4941 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4942 }
4943
4944 for (pos.col = 0; pos.col < term->tl_cols; )
4945 {
4946 dict_T *dcell;
4947 int width;
4948 VTermScreenCellAttrs attrs;
4949 VTermColor fg, bg;
4950 char_u rgb[8];
4951 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4952 int off = 0;
4953 int i;
4954
4955 if (screen == NULL)
4956 {
4957 cellattr_T *cellattr;
4958 int len;
4959
4960 /* vterm has finished, get the cell from scrollback */
4961 if (pos.col >= line->sb_cols)
4962 break;
4963 cellattr = line->sb_cells + pos.col;
4964 width = cellattr->width;
4965 attrs = cellattr->attrs;
4966 fg = cellattr->fg;
4967 bg = cellattr->bg;
4968 len = MB_PTR2LEN(p);
4969 mch_memmove(mbs, p, len);
4970 mbs[len] = NUL;
4971 p += len;
4972 }
4973 else
4974 {
4975 VTermScreenCell cell;
4976 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4977 break;
4978 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4979 {
4980 if (cell.chars[i] == 0)
4981 break;
4982 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4983 }
4984 mbs[off] = NUL;
4985 width = cell.width;
4986 attrs = cell.attrs;
4987 fg = cell.fg;
4988 bg = cell.bg;
4989 }
4990 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004991 if (dcell == NULL)
4992 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004993 list_append_dict(l, dcell);
4994
4995 dict_add_nr_str(dcell, "chars", 0, mbs);
4996
4997 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4998 fg.red, fg.green, fg.blue);
4999 dict_add_nr_str(dcell, "fg", 0, rgb);
5000 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5001 bg.red, bg.green, bg.blue);
5002 dict_add_nr_str(dcell, "bg", 0, rgb);
5003
5004 dict_add_nr_str(dcell, "attr",
5005 cell2attr(attrs, fg, bg), NULL);
5006 dict_add_nr_str(dcell, "width", width, NULL);
5007
5008 ++pos.col;
5009 if (width == 2)
5010 ++pos.col;
5011 }
5012}
5013
5014/*
5015 * "term_sendkeys(buf, keys)" function
5016 */
5017 void
5018f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5019{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005020 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005021 char_u *msg;
5022 term_T *term;
5023
5024 rettv->v_type = VAR_UNKNOWN;
5025 if (buf == NULL)
5026 return;
5027
5028 msg = get_tv_string_chk(&argvars[1]);
5029 if (msg == NULL)
5030 return;
5031 term = buf->b_term;
5032 if (term->tl_vterm == NULL)
5033 return;
5034
5035 while (*msg != NUL)
5036 {
5037 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005038 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005039 }
5040}
5041
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005042#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5043/*
5044 * "term_getansicolors(buf)" function
5045 */
5046 void
5047f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5048{
5049 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5050 term_T *term;
5051 VTermState *state;
5052 VTermColor color;
5053 char_u hexbuf[10];
5054 int index;
5055 list_T *list;
5056
5057 if (rettv_list_alloc(rettv) == FAIL)
5058 return;
5059
5060 if (buf == NULL)
5061 return;
5062 term = buf->b_term;
5063 if (term->tl_vterm == NULL)
5064 return;
5065
5066 list = rettv->vval.v_list;
5067 state = vterm_obtain_state(term->tl_vterm);
5068 for (index = 0; index < 16; index++)
5069 {
5070 vterm_state_get_palette_color(state, index, &color);
5071 sprintf((char *)hexbuf, "#%02x%02x%02x",
5072 color.red, color.green, color.blue);
5073 if (list_append_string(list, hexbuf, 7) == FAIL)
5074 return;
5075 }
5076}
5077
5078/*
5079 * "term_setansicolors(buf, list)" function
5080 */
5081 void
5082f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5083{
5084 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5085 term_T *term;
5086
5087 if (buf == NULL)
5088 return;
5089 term = buf->b_term;
5090 if (term->tl_vterm == NULL)
5091 return;
5092
5093 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5094 {
5095 EMSG(_(e_listreq));
5096 return;
5097 }
5098
5099 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5100 EMSG(_(e_invarg));
5101}
5102#endif
5103
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005104/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005105 * "term_setrestore(buf, command)" function
5106 */
5107 void
5108f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5109{
5110#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005111 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005112 term_T *term;
5113 char_u *cmd;
5114
5115 if (buf == NULL)
5116 return;
5117 term = buf->b_term;
5118 vim_free(term->tl_command);
5119 cmd = get_tv_string_chk(&argvars[1]);
5120 if (cmd != NULL)
5121 term->tl_command = vim_strsave(cmd);
5122 else
5123 term->tl_command = NULL;
5124#endif
5125}
5126
5127/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005128 * "term_setkill(buf, how)" function
5129 */
5130 void
5131f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5132{
5133 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5134 term_T *term;
5135 char_u *how;
5136
5137 if (buf == NULL)
5138 return;
5139 term = buf->b_term;
5140 vim_free(term->tl_kill);
5141 how = get_tv_string_chk(&argvars[1]);
5142 if (how != NULL)
5143 term->tl_kill = vim_strsave(how);
5144 else
5145 term->tl_kill = NULL;
5146}
5147
5148/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005149 * "term_start(command, options)" function
5150 */
5151 void
5152f_term_start(typval_T *argvars, typval_T *rettv)
5153{
5154 jobopt_T opt;
5155 buf_T *buf;
5156
5157 init_job_options(&opt);
5158 if (argvars[1].v_type != VAR_UNKNOWN
5159 && get_job_options(&argvars[1], &opt,
5160 JO_TIMEOUT_ALL + JO_STOPONEXIT
5161 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5162 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5163 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5164 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005165 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005166 + JO2_NORESTORE + JO2_TERM_KILL
5167 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005168 return;
5169
Bram Moolenaar13568252018-03-16 20:46:58 +01005170 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005171
5172 if (buf != NULL && buf->b_term != NULL)
5173 rettv->vval.v_number = buf->b_fnum;
5174}
5175
5176/*
5177 * "term_wait" function
5178 */
5179 void
5180f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5181{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005182 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005183
5184 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005185 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005186 if (buf->b_term->tl_job == NULL)
5187 {
5188 ch_log(NULL, "term_wait(): no job to wait for");
5189 return;
5190 }
5191 if (buf->b_term->tl_job->jv_channel == NULL)
5192 /* channel is closed, nothing to do */
5193 return;
5194
5195 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005196 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005197 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5198 {
5199 /* The job is dead, keep reading channel I/O until the channel is
5200 * closed. buf->b_term may become NULL if the terminal was closed while
5201 * waiting. */
5202 ch_log(NULL, "term_wait(): waiting for channel to close");
5203 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5204 {
5205 mch_check_messages();
5206 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005207 if (!buf_valid(buf))
5208 /* If the terminal is closed when the channel is closed the
5209 * buffer disappears. */
5210 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005211 ui_delay(10L, FALSE);
5212 }
5213 mch_check_messages();
5214 parse_queued_messages();
5215 }
5216 else
5217 {
5218 long wait = 10L;
5219
5220 mch_check_messages();
5221 parse_queued_messages();
5222
5223 /* Wait for some time for any channel I/O. */
5224 if (argvars[1].v_type != VAR_UNKNOWN)
5225 wait = get_tv_number(&argvars[1]);
5226 ui_delay(wait, TRUE);
5227 mch_check_messages();
5228
5229 /* Flushing messages on channels is hopefully sufficient.
5230 * TODO: is there a better way? */
5231 parse_queued_messages();
5232 }
5233}
5234
5235/*
5236 * Called when a channel has sent all the lines to a terminal.
5237 * Send a CTRL-D to mark the end of the text.
5238 */
5239 void
5240term_send_eof(channel_T *ch)
5241{
5242 term_T *term;
5243
5244 for (term = first_term; term != NULL; term = term->tl_next)
5245 if (term->tl_job == ch->ch_job)
5246 {
5247 if (term->tl_eof_chars != NULL)
5248 {
5249 channel_send(ch, PART_IN, term->tl_eof_chars,
5250 (int)STRLEN(term->tl_eof_chars), NULL);
5251 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5252 }
5253# ifdef WIN3264
5254 else
5255 /* Default: CTRL-D */
5256 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5257# endif
5258 }
5259}
5260
5261# if defined(WIN3264) || defined(PROTO)
5262
5263/**************************************
5264 * 2. MS-Windows implementation.
5265 */
5266
5267# ifndef PROTO
5268
5269#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5270#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005271#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005272
5273void* (*winpty_config_new)(UINT64, void*);
5274void* (*winpty_open)(void*, void*);
5275void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5276BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5277void (*winpty_config_set_mouse_mode)(void*, int);
5278void (*winpty_config_set_initial_size)(void*, int, int);
5279LPCWSTR (*winpty_conin_name)(void*);
5280LPCWSTR (*winpty_conout_name)(void*);
5281LPCWSTR (*winpty_conerr_name)(void*);
5282void (*winpty_free)(void*);
5283void (*winpty_config_free)(void*);
5284void (*winpty_spawn_config_free)(void*);
5285void (*winpty_error_free)(void*);
5286LPCWSTR (*winpty_error_msg)(void*);
5287BOOL (*winpty_set_size)(void*, int, int, void*);
5288HANDLE (*winpty_agent_process)(void*);
5289
5290#define WINPTY_DLL "winpty.dll"
5291
5292static HINSTANCE hWinPtyDLL = NULL;
5293# endif
5294
5295 static int
5296dyn_winpty_init(int verbose)
5297{
5298 int i;
5299 static struct
5300 {
5301 char *name;
5302 FARPROC *ptr;
5303 } winpty_entry[] =
5304 {
5305 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5306 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5307 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5308 {"winpty_config_set_mouse_mode",
5309 (FARPROC*)&winpty_config_set_mouse_mode},
5310 {"winpty_config_set_initial_size",
5311 (FARPROC*)&winpty_config_set_initial_size},
5312 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5313 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5314 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5315 {"winpty_free", (FARPROC*)&winpty_free},
5316 {"winpty_open", (FARPROC*)&winpty_open},
5317 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5318 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5319 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5320 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5321 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5322 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5323 {NULL, NULL}
5324 };
5325
5326 /* No need to initialize twice. */
5327 if (hWinPtyDLL)
5328 return OK;
5329 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5330 * winpty.dll. */
5331 if (*p_winptydll != NUL)
5332 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5333 if (!hWinPtyDLL)
5334 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5335 if (!hWinPtyDLL)
5336 {
5337 if (verbose)
5338 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5339 : (char_u *)WINPTY_DLL);
5340 return FAIL;
5341 }
5342 for (i = 0; winpty_entry[i].name != NULL
5343 && winpty_entry[i].ptr != NULL; ++i)
5344 {
5345 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5346 winpty_entry[i].name)) == NULL)
5347 {
5348 if (verbose)
5349 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5350 return FAIL;
5351 }
5352 }
5353
5354 return OK;
5355}
5356
5357/*
5358 * Create a new terminal of "rows" by "cols" cells.
5359 * Store a reference in "term".
5360 * Return OK or FAIL.
5361 */
5362 static int
5363term_and_job_init(
5364 term_T *term,
5365 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005366 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005367 jobopt_T *opt,
5368 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005369{
5370 WCHAR *cmd_wchar = NULL;
5371 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005372 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005373 channel_T *channel = NULL;
5374 job_T *job = NULL;
5375 DWORD error;
5376 HANDLE jo = NULL;
5377 HANDLE child_process_handle;
5378 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005379 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005380 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005381 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005382 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005383
5384 if (dyn_winpty_init(TRUE) == FAIL)
5385 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005386 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5387 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005388
5389 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005390 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005391 cmd = argvar->vval.v_string;
5392 }
5393 else if (argvar->v_type == VAR_LIST)
5394 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005395 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005396 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005397 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005398 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005399 if (cmd == NULL || *cmd == NUL)
5400 {
5401 EMSG(_(e_invarg));
5402 goto failed;
5403 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005404
5405 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005406 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005407 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005408 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005409 if (opt->jo_cwd != NULL)
5410 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005411
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005412 win32_build_env(opt->jo_env, &ga_env, TRUE);
5413 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005414
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005415 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5416 if (term->tl_winpty_config == NULL)
5417 goto failed;
5418
5419 winpty_config_set_mouse_mode(term->tl_winpty_config,
5420 WINPTY_MOUSE_MODE_FORCE);
5421 winpty_config_set_initial_size(term->tl_winpty_config,
5422 term->tl_cols, term->tl_rows);
5423 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5424 if (term->tl_winpty == NULL)
5425 goto failed;
5426
5427 spawn_config = winpty_spawn_config_new(
5428 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5429 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5430 NULL,
5431 cmd_wchar,
5432 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005433 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005434 &winpty_err);
5435 if (spawn_config == NULL)
5436 goto failed;
5437
5438 channel = add_channel();
5439 if (channel == NULL)
5440 goto failed;
5441
5442 job = job_alloc();
5443 if (job == NULL)
5444 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005445 if (argvar->v_type == VAR_STRING)
5446 {
5447 int argc;
5448
5449 build_argv_from_string(cmd, &job->jv_argv, &argc);
5450 }
5451 else
5452 {
5453 int argc;
5454
5455 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5456 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005457
5458 if (opt->jo_set & JO_IN_BUF)
5459 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5460
5461 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5462 &child_thread_handle, &error, &winpty_err))
5463 goto failed;
5464
5465 channel_set_pipes(channel,
5466 (sock_T)CreateFileW(
5467 winpty_conin_name(term->tl_winpty),
5468 GENERIC_WRITE, 0, NULL,
5469 OPEN_EXISTING, 0, NULL),
5470 (sock_T)CreateFileW(
5471 winpty_conout_name(term->tl_winpty),
5472 GENERIC_READ, 0, NULL,
5473 OPEN_EXISTING, 0, NULL),
5474 (sock_T)CreateFileW(
5475 winpty_conerr_name(term->tl_winpty),
5476 GENERIC_READ, 0, NULL,
5477 OPEN_EXISTING, 0, NULL));
5478
5479 /* Write lines with CR instead of NL. */
5480 channel->ch_write_text_mode = TRUE;
5481
5482 jo = CreateJobObject(NULL, NULL);
5483 if (jo == NULL)
5484 goto failed;
5485
5486 if (!AssignProcessToJobObject(jo, child_process_handle))
5487 {
5488 /* Failed, switch the way to terminate process with TerminateProcess. */
5489 CloseHandle(jo);
5490 jo = NULL;
5491 }
5492
5493 winpty_spawn_config_free(spawn_config);
5494 vim_free(cmd_wchar);
5495 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005496 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005497
5498 create_vterm(term, term->tl_rows, term->tl_cols);
5499
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005500#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5501 if (opt->jo_set2 & JO2_ANSI_COLORS)
5502 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5503 else
5504 init_vterm_ansi_colors(term->tl_vterm);
5505#endif
5506
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005507 channel_set_job(channel, job, opt);
5508 job_set_options(job, opt);
5509
5510 job->jv_channel = channel;
5511 job->jv_proc_info.hProcess = child_process_handle;
5512 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5513 job->jv_job_object = jo;
5514 job->jv_status = JOB_STARTED;
5515 job->jv_tty_in = utf16_to_enc(
5516 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5517 job->jv_tty_out = utf16_to_enc(
5518 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5519 ++job->jv_refcount;
5520 term->tl_job = job;
5521
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005522 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5523 * open the file here and handle it in. opt->jo_io was changed in
5524 * setup_job_options(), use the original flags here. */
5525 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5526 {
5527 char_u *fname = opt->jo_io_name[PART_OUT];
5528
5529 ch_log(channel, "Opening output file %s", fname);
5530 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5531 if (term->tl_out_fd == NULL)
5532 EMSG2(_(e_notopen), fname);
5533 }
5534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005535 return OK;
5536
5537failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005538 ga_clear(&ga_cmd);
5539 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005540 vim_free(cmd_wchar);
5541 vim_free(cwd_wchar);
5542 if (spawn_config != NULL)
5543 winpty_spawn_config_free(spawn_config);
5544 if (channel != NULL)
5545 channel_clear(channel);
5546 if (job != NULL)
5547 {
5548 job->jv_channel = NULL;
5549 job_cleanup(job);
5550 }
5551 term->tl_job = NULL;
5552 if (jo != NULL)
5553 CloseHandle(jo);
5554 if (term->tl_winpty != NULL)
5555 winpty_free(term->tl_winpty);
5556 term->tl_winpty = NULL;
5557 if (term->tl_winpty_config != NULL)
5558 winpty_config_free(term->tl_winpty_config);
5559 term->tl_winpty_config = NULL;
5560 if (winpty_err != NULL)
5561 {
5562 char_u *msg = utf16_to_enc(
5563 (short_u *)winpty_error_msg(winpty_err), NULL);
5564
5565 EMSG(msg);
5566 winpty_error_free(winpty_err);
5567 }
5568 return FAIL;
5569}
5570
5571 static int
5572create_pty_only(term_T *term, jobopt_T *options)
5573{
5574 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5575 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5576 char in_name[80], out_name[80];
5577 channel_T *channel = NULL;
5578
5579 create_vterm(term, term->tl_rows, term->tl_cols);
5580
5581 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5582 GetCurrentProcessId(),
5583 curbuf->b_fnum);
5584 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5585 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5586 PIPE_UNLIMITED_INSTANCES,
5587 0, 0, NMPWAIT_NOWAIT, NULL);
5588 if (hPipeIn == INVALID_HANDLE_VALUE)
5589 goto failed;
5590
5591 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5592 GetCurrentProcessId(),
5593 curbuf->b_fnum);
5594 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5595 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5596 PIPE_UNLIMITED_INSTANCES,
5597 0, 0, 0, NULL);
5598 if (hPipeOut == INVALID_HANDLE_VALUE)
5599 goto failed;
5600
5601 ConnectNamedPipe(hPipeIn, NULL);
5602 ConnectNamedPipe(hPipeOut, NULL);
5603
5604 term->tl_job = job_alloc();
5605 if (term->tl_job == NULL)
5606 goto failed;
5607 ++term->tl_job->jv_refcount;
5608
5609 /* behave like the job is already finished */
5610 term->tl_job->jv_status = JOB_FINISHED;
5611
5612 channel = add_channel();
5613 if (channel == NULL)
5614 goto failed;
5615 term->tl_job->jv_channel = channel;
5616 channel->ch_keep_open = TRUE;
5617 channel->ch_named_pipe = TRUE;
5618
5619 channel_set_pipes(channel,
5620 (sock_T)hPipeIn,
5621 (sock_T)hPipeOut,
5622 (sock_T)hPipeOut);
5623 channel_set_job(channel, term->tl_job, options);
5624 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5625 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5626
5627 return OK;
5628
5629failed:
5630 if (hPipeIn != NULL)
5631 CloseHandle(hPipeIn);
5632 if (hPipeOut != NULL)
5633 CloseHandle(hPipeOut);
5634 return FAIL;
5635}
5636
5637/*
5638 * Free the terminal emulator part of "term".
5639 */
5640 static void
5641term_free_vterm(term_T *term)
5642{
5643 if (term->tl_winpty != NULL)
5644 winpty_free(term->tl_winpty);
5645 term->tl_winpty = NULL;
5646 if (term->tl_winpty_config != NULL)
5647 winpty_config_free(term->tl_winpty_config);
5648 term->tl_winpty_config = NULL;
5649 if (term->tl_vterm != NULL)
5650 vterm_free(term->tl_vterm);
5651 term->tl_vterm = NULL;
5652}
5653
5654/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005655 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005656 */
5657 static void
5658term_report_winsize(term_T *term, int rows, int cols)
5659{
5660 if (term->tl_winpty)
5661 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5662}
5663
5664 int
5665terminal_enabled(void)
5666{
5667 return dyn_winpty_init(FALSE) == OK;
5668}
5669
5670# else
5671
5672/**************************************
5673 * 3. Unix-like implementation.
5674 */
5675
5676/*
5677 * Create a new terminal of "rows" by "cols" cells.
5678 * Start job for "cmd".
5679 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005680 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005681 * Return OK or FAIL.
5682 */
5683 static int
5684term_and_job_init(
5685 term_T *term,
5686 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005687 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005688 jobopt_T *opt,
5689 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005690{
5691 create_vterm(term, term->tl_rows, term->tl_cols);
5692
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005693#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5694 if (opt->jo_set2 & JO2_ANSI_COLORS)
5695 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5696 else
5697 init_vterm_ansi_colors(term->tl_vterm);
5698#endif
5699
Bram Moolenaar13568252018-03-16 20:46:58 +01005700 /* This may change a string in "argvar". */
5701 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702 if (term->tl_job != NULL)
5703 ++term->tl_job->jv_refcount;
5704
5705 return term->tl_job != NULL
5706 && term->tl_job->jv_channel != NULL
5707 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5708}
5709
5710 static int
5711create_pty_only(term_T *term, jobopt_T *opt)
5712{
5713 create_vterm(term, term->tl_rows, term->tl_cols);
5714
5715 term->tl_job = job_alloc();
5716 if (term->tl_job == NULL)
5717 return FAIL;
5718 ++term->tl_job->jv_refcount;
5719
5720 /* behave like the job is already finished */
5721 term->tl_job->jv_status = JOB_FINISHED;
5722
5723 return mch_create_pty_channel(term->tl_job, opt);
5724}
5725
5726/*
5727 * Free the terminal emulator part of "term".
5728 */
5729 static void
5730term_free_vterm(term_T *term)
5731{
5732 if (term->tl_vterm != NULL)
5733 vterm_free(term->tl_vterm);
5734 term->tl_vterm = NULL;
5735}
5736
5737/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005738 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005739 */
5740 static void
5741term_report_winsize(term_T *term, int rows, int cols)
5742{
5743 /* Use an ioctl() to report the new window size to the job. */
5744 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5745 {
5746 int fd = -1;
5747 int part;
5748
5749 for (part = PART_OUT; part < PART_COUNT; ++part)
5750 {
5751 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5752 if (isatty(fd))
5753 break;
5754 }
5755 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5756 mch_signal_job(term->tl_job, (char_u *)"winch");
5757 }
5758}
5759
5760# endif
5761
5762#endif /* FEAT_TERMINAL */