blob: 849d926fe7ebf834401e115f39fca50e3603c51e [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 Moolenaar4d6cd292018-05-15 23:53:26 +020049 * - terminal API: Add more functionality? (Ozaki Kiichi 2018 May 13, #2907)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +020050 * - When the job only outputs lines, we could handle resizing the terminal
51 * better: store lines separated by line breaks, instead of screen lines,
52 * then when the window is resized redraw those lines.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020053 * - Redrawing is slow with Athena and Motif. (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020054 * - For the GUI fill termios with default values, perhaps like pangoterm:
55 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020056 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020057 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020058 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
59 * "run". Everything else works, including communication channel. Not
60 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020061 */
62
63#include "vim.h"
64
65#if defined(FEAT_TERMINAL) || defined(PROTO)
66
67#ifndef MIN
68# define MIN(x,y) ((x) < (y) ? (x) : (y))
69#endif
70#ifndef MAX
71# define MAX(x,y) ((x) > (y) ? (x) : (y))
72#endif
73
74#include "libvterm/include/vterm.h"
75
76/* This is VTermScreenCell without the characters, thus much smaller. */
77typedef struct {
78 VTermScreenCellAttrs attrs;
79 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010080 VTermColor fg;
81 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020082} cellattr_T;
83
84typedef struct sb_line_S {
85 int sb_cols; /* can differ per line */
86 cellattr_T *sb_cells; /* allocated */
87 cellattr_T sb_fill_attr; /* for short line */
88} sb_line_T;
89
90/* typedef term_T in structs.h */
91struct terminal_S {
92 term_T *tl_next;
93
94 VTerm *tl_vterm;
95 job_T *tl_job;
96 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010097#if defined(FEAT_GUI)
98 int tl_system; /* when non-zero used for :!cmd output */
99 int tl_toprow; /* row with first line of system terminal */
100#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200101
102 /* Set when setting the size of a vterm, reset after redrawing. */
103 int tl_vterm_size_changed;
104
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200105 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
106 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200107 int tl_channel_recently_closed; // still need to handle tl_finish
108
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100109 int tl_finish;
110#define TL_FINISH_UNSET NUL
111#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
112#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
113#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200114 char_u *tl_opencmd;
115 char_u *tl_eof_chars;
116
117#ifdef WIN3264
118 void *tl_winpty_config;
119 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200120
121 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200122#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100123#if defined(FEAT_SESSION)
124 char_u *tl_command;
125#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100126 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200127
128 /* last known vterm size */
129 int tl_rows;
130 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131
132 char_u *tl_title; /* NULL or allocated */
133 char_u *tl_status_text; /* NULL or allocated */
134
135 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200136 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200137 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200138 int tl_dirty_snapshot; /* text updated after making snapshot */
139#ifdef FEAT_TIMERS
140 int tl_timer_set;
141 proftime_T tl_timer_due;
142#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200143 int tl_postponed_scroll; /* to be scrolled up */
144
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200145 garray_T tl_scrollback;
146 int tl_scrollback_scrolled;
147 cellattr_T tl_default_color;
148
Bram Moolenaard96ff162018-02-18 22:13:29 +0100149 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
150 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
151
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200152 VTermPos tl_cursor_pos;
153 int tl_cursor_visible;
154 int tl_cursor_blink;
155 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
156 char_u *tl_cursor_color; /* NULL or allocated */
157
158 int tl_using_altscreen;
159};
160
161#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
162#define TMODE_LOOP 2 /* CTRL-W N used */
163
164/*
165 * List of all active terminals.
166 */
167static term_T *first_term = NULL;
168
169/* Terminal active in terminal_loop(). */
170static term_T *in_terminal_loop = NULL;
171
172#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
173#define KEY_BUF_LEN 200
174
175/*
176 * Functions with separate implementation for MS-Windows and Unix-like systems.
177 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200178static 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 +0200179static int create_pty_only(term_T *term, jobopt_T *opt);
180static void term_report_winsize(term_T *term, int rows, int cols);
181static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100182#ifdef FEAT_GUI
183static void update_system_term(term_T *term);
184#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200185
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100186/* The character that we know (or assume) that the terminal expects for the
187 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100190/* "Terminal" highlight group colors. */
191static int term_default_cterm_fg = -1;
192static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaard317b382018-02-08 22:33:31 +0100194/* Store the last set and the desired cursor properties, so that we only update
195 * them when needed. Doing it unnecessary may result in flicker. */
196static char_u *last_set_cursor_color = (char_u *)"";
197static char_u *desired_cursor_color = (char_u *)"";
198static int last_set_cursor_shape = -1;
199static int desired_cursor_shape = -1;
200static int last_set_cursor_blink = -1;
201static int desired_cursor_blink = -1;
202
203
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204/**************************************
205 * 1. Generic code for all systems.
206 */
207
208/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200209 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200210 * current window.
211 * Sets "rows" and/or "cols" to zero when it should follow the window size.
212 * Return TRUE if the size is the minimum size: "24*80".
213 */
214 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200215parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200216{
217 int minsize = FALSE;
218
219 *rows = 0;
220 *cols = 0;
221
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200222 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200223 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200224 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200225
226 /* Syntax of value was already checked when it's set. */
227 if (p == NULL)
228 {
229 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200230 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200231 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200232 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200233 *cols = atoi((char *)p + 1);
234 }
235 return minsize;
236}
237
238/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200239 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200240 */
241 static void
242set_term_and_win_size(term_T *term)
243{
Bram Moolenaar13568252018-03-16 20:46:58 +0100244#ifdef FEAT_GUI
245 if (term->tl_system)
246 {
247 /* Use the whole screen for the system command. However, it will start
248 * at the command line and scroll up as needed, using tl_toprow. */
249 term->tl_rows = Rows;
250 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200251 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100252 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100253#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200254 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200255 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256 if (term->tl_rows != 0)
257 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
258 if (term->tl_cols != 0)
259 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200260 }
261 if (term->tl_rows == 0)
262 term->tl_rows = curwin->w_height;
263 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200264 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200265 if (term->tl_cols == 0)
266 term->tl_cols = curwin->w_width;
267 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200269}
270
271/*
272 * Initialize job options for a terminal job.
273 * Caller may overrule some of them.
274 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100275 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200276init_job_options(jobopt_T *opt)
277{
278 clear_job_options(opt);
279
280 opt->jo_mode = MODE_RAW;
281 opt->jo_out_mode = MODE_RAW;
282 opt->jo_err_mode = MODE_RAW;
283 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
284}
285
286/*
287 * Set job options mandatory for a terminal job.
288 */
289 static void
290setup_job_options(jobopt_T *opt, int rows, int cols)
291{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200292#ifndef WIN3264
293 /* Win32: Redirecting the job output won't work, thus always connect stdout
294 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200296#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200297 {
298 /* Connect stdout to the terminal. */
299 opt->jo_io[PART_OUT] = JIO_BUFFER;
300 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
301 opt->jo_modifiable[PART_OUT] = 0;
302 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
303 }
304
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200305#ifndef WIN3264
306 /* Win32: Redirecting the job output won't work, thus always connect stderr
307 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200308 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200309#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200310 {
311 /* Connect stderr to the terminal. */
312 opt->jo_io[PART_ERR] = JIO_BUFFER;
313 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
314 opt->jo_modifiable[PART_ERR] = 0;
315 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
316 }
317
318 opt->jo_pty = TRUE;
319 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
320 opt->jo_term_rows = rows;
321 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
322 opt->jo_term_cols = cols;
323}
324
325/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100326 * Close a terminal buffer (and its window). Used when creating the terminal
327 * fails.
328 */
329 static void
330term_close_buffer(buf_T *buf, buf_T *old_curbuf)
331{
332 free_terminal(buf);
333 if (old_curbuf != NULL)
334 {
335 --curbuf->b_nwindows;
336 curbuf = old_curbuf;
337 curwin->w_buffer = curbuf;
338 ++curbuf->b_nwindows;
339 }
340
341 /* Wiping out the buffer will also close the window and call
342 * free_terminal(). */
343 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
344}
345
346/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200347 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100348 * Use either "argvar" or "argv", the other must be NULL.
349 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
350 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200351 * Returns NULL when failed.
352 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100353 buf_T *
354term_start(
355 typval_T *argvar,
356 char **argv,
357 jobopt_T *opt,
358 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200359{
360 exarg_T split_ea;
361 win_T *old_curwin = curwin;
362 term_T *term;
363 buf_T *old_curbuf = NULL;
364 int res;
365 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100366 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200367 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200368
369 if (check_restricted() || check_secure())
370 return NULL;
371
372 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
373 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
374 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
375 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
376 {
377 EMSG(_(e_invarg));
378 return NULL;
379 }
380
381 term = (term_T *)alloc_clear(sizeof(term_T));
382 if (term == NULL)
383 return NULL;
384 term->tl_dirty_row_end = MAX_ROW;
385 term->tl_cursor_visible = TRUE;
386 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
387 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100388#ifdef FEAT_GUI
389 term->tl_system = (flags & TERM_START_SYSTEM);
390#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200391 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
392
393 vim_memset(&split_ea, 0, sizeof(split_ea));
394 if (opt->jo_curwin)
395 {
396 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100397 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200398 {
399 no_write_message();
400 vim_free(term);
401 return NULL;
402 }
403 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100404 ECMD_HIDE
405 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
406 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200407 {
408 vim_free(term);
409 return NULL;
410 }
411 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100412 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413 {
414 buf_T *buf;
415
416 /* Create a new buffer without a window. Make it the current buffer for
417 * a moment to be able to do the initialisations. */
418 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
419 BLN_NEW | BLN_LISTED);
420 if (buf == NULL || ml_open(buf) == FAIL)
421 {
422 vim_free(term);
423 return NULL;
424 }
425 old_curbuf = curbuf;
426 --curbuf->b_nwindows;
427 curbuf = buf;
428 curwin->w_buffer = buf;
429 ++curbuf->b_nwindows;
430 }
431 else
432 {
433 /* Open a new window or tab. */
434 split_ea.cmdidx = CMD_new;
435 split_ea.cmd = (char_u *)"new";
436 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 {
439 split_ea.line2 = opt->jo_term_rows;
440 split_ea.addr_count = 1;
441 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100442 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200443 {
444 split_ea.line2 = opt->jo_term_cols;
445 split_ea.addr_count = 1;
446 }
447
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100448 if (vertical)
449 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450 ex_splitview(&split_ea);
451 if (curwin == old_curwin)
452 {
453 /* split failed */
454 vim_free(term);
455 return NULL;
456 }
457 }
458 term->tl_buffer = curbuf;
459 curbuf->b_term = term;
460
461 if (!opt->jo_hidden)
462 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100463 /* Only one size was taken care of with :new, do the other one. With
464 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100465 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200466 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100467 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 win_setwidth(opt->jo_term_cols);
469 }
470
471 /* Link the new terminal in the list of active terminals. */
472 term->tl_next = first_term;
473 first_term = term;
474
475 if (opt->jo_term_name != NULL)
476 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100477 else if (argv != NULL)
478 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200479 else
480 {
481 int i;
482 size_t len;
483 char_u *cmd, *p;
484
485 if (argvar->v_type == VAR_STRING)
486 {
487 cmd = argvar->vval.v_string;
488 if (cmd == NULL)
489 cmd = (char_u *)"";
490 else if (STRCMP(cmd, "NONE") == 0)
491 cmd = (char_u *)"pty";
492 }
493 else if (argvar->v_type != VAR_LIST
494 || argvar->vval.v_list == NULL
495 || argvar->vval.v_list->lv_len < 1
496 || (cmd = get_tv_string_chk(
497 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
498 cmd = (char_u*)"";
499
500 len = STRLEN(cmd) + 10;
501 p = alloc((int)len);
502
503 for (i = 0; p != NULL; ++i)
504 {
505 /* Prepend a ! to the command name to avoid the buffer name equals
506 * the executable, otherwise ":w!" would overwrite it. */
507 if (i == 0)
508 vim_snprintf((char *)p, len, "!%s", cmd);
509 else
510 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
511 if (buflist_findname(p) == NULL)
512 {
513 vim_free(curbuf->b_ffname);
514 curbuf->b_ffname = p;
515 break;
516 }
517 }
518 }
519 curbuf->b_fname = curbuf->b_ffname;
520
521 if (opt->jo_term_opencmd != NULL)
522 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
523
524 if (opt->jo_eof_chars != NULL)
525 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
526
527 set_string_option_direct((char_u *)"buftype", -1,
528 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
529
530 /* Mark the buffer as not modifiable. It can only be made modifiable after
531 * the job finished. */
532 curbuf->b_p_ma = FALSE;
533
534 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200535#ifdef WIN3264
536 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
537#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200538 setup_job_options(opt, term->tl_rows, term->tl_cols);
539
Bram Moolenaar13568252018-03-16 20:46:58 +0100540 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100541 return curbuf;
542
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100543#if defined(FEAT_SESSION)
544 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100545 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100546 {
547 term->tl_command = vim_strsave((char_u *)"NONE");
548 }
549 else if (argvar->v_type == VAR_STRING)
550 {
551 char_u *cmd = argvar->vval.v_string;
552
553 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
554 term->tl_command = vim_strsave(cmd);
555 }
556 else if (argvar->v_type == VAR_LIST
557 && argvar->vval.v_list != NULL
558 && argvar->vval.v_list->lv_len > 0)
559 {
560 garray_T ga;
561 listitem_T *item;
562
563 ga_init2(&ga, 1, 100);
564 for (item = argvar->vval.v_list->lv_first;
565 item != NULL; item = item->li_next)
566 {
567 char_u *s = get_tv_string_chk(&item->li_tv);
568 char_u *p;
569
570 if (s == NULL)
571 break;
572 p = vim_strsave_fnameescape(s, FALSE);
573 if (p == NULL)
574 break;
575 ga_concat(&ga, p);
576 vim_free(p);
577 ga_append(&ga, ' ');
578 }
579 if (item == NULL)
580 {
581 ga_append(&ga, NUL);
582 term->tl_command = ga.ga_data;
583 }
584 else
585 ga_clear(&ga);
586 }
587#endif
588
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100589 if (opt->jo_term_kill != NULL)
590 {
591 char_u *p = skiptowhite(opt->jo_term_kill);
592
593 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
594 }
595
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200596 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 if (argv == NULL
598 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 && argvar->vval.v_string != NULL
600 && STRCMP(argvar->vval.v_string, "NONE") == 0)
601 res = create_pty_only(term, opt);
602 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200603 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604
605 newbuf = curbuf;
606 if (res == OK)
607 {
608 /* Get and remember the size we ended up with. Update the pty. */
609 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
610 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100611#ifdef FEAT_GUI
612 if (term->tl_system)
613 {
614 /* display first line below typed command */
615 term->tl_toprow = msg_row + 1;
616 term->tl_dirty_row_end = 0;
617 }
618#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200619
620 /* Make sure we don't get stuck on sending keys to the job, it leads to
621 * a deadlock if the job is waiting for Vim to read. */
622 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
623
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200624 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200625 {
626 --curbuf->b_nwindows;
627 curbuf = old_curbuf;
628 curwin->w_buffer = curbuf;
629 ++curbuf->b_nwindows;
630 }
631 }
632 else
633 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100634 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 return NULL;
636 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100637
Bram Moolenaar13568252018-03-16 20:46:58 +0100638 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200639 return newbuf;
640}
641
642/*
643 * ":terminal": open a terminal window and execute a job in it.
644 */
645 void
646ex_terminal(exarg_T *eap)
647{
648 typval_T argvar[2];
649 jobopt_T opt;
650 char_u *cmd;
651 char_u *tofree = NULL;
652
653 init_job_options(&opt);
654
655 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100656 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657 {
658 char_u *p, *ep;
659
660 cmd += 2;
661 p = skiptowhite(cmd);
662 ep = vim_strchr(cmd, '=');
663 if (ep != NULL && ep < p)
664 p = ep;
665
666 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
667 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100668 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
669 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200670 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
671 opt.jo_term_finish = 'o';
672 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
673 opt.jo_curwin = 1;
674 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
675 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100676 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
677 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100678 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
679 && ep != NULL)
680 {
681 opt.jo_set2 |= JO2_TERM_KILL;
682 opt.jo_term_kill = ep + 1;
683 p = skiptowhite(cmd);
684 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200685 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
686 && ep != NULL && isdigit(ep[1]))
687 {
688 opt.jo_set2 |= JO2_TERM_ROWS;
689 opt.jo_term_rows = atoi((char *)ep + 1);
690 p = skiptowhite(cmd);
691 }
692 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
693 && ep != NULL && isdigit(ep[1]))
694 {
695 opt.jo_set2 |= JO2_TERM_COLS;
696 opt.jo_term_cols = atoi((char *)ep + 1);
697 p = skiptowhite(cmd);
698 }
699 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
700 && ep != NULL)
701 {
702 char_u *buf = NULL;
703 char_u *keys;
704
705 p = skiptowhite(cmd);
706 *p = NUL;
707 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
708 opt.jo_set2 |= JO2_EOF_CHARS;
709 opt.jo_eof_chars = vim_strsave(keys);
710 vim_free(buf);
711 *p = ' ';
712 }
713 else
714 {
715 if (*p)
716 *p = NUL;
717 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100718 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 }
720 cmd = skipwhite(p);
721 }
722 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100723 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 /* Make a copy of 'shell', an autocommand may change the option. */
725 tofree = cmd = vim_strsave(p_sh);
726
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100727 /* default to close when the shell exits */
728 if (opt.jo_term_finish == NUL)
729 opt.jo_term_finish = 'c';
730 }
731
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 if (eap->addr_count > 0)
733 {
734 /* Write lines from current buffer to the job. */
735 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
736 opt.jo_io[PART_IN] = JIO_BUFFER;
737 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
738 opt.jo_in_top = eap->line1;
739 opt.jo_in_bot = eap->line2;
740 }
741
742 argvar[0].v_type = VAR_STRING;
743 argvar[0].vval.v_string = cmd;
744 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100745 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100747
748theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 vim_free(opt.jo_eof_chars);
750}
751
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100752#if defined(FEAT_SESSION) || defined(PROTO)
753/*
754 * Write a :terminal command to the session file to restore the terminal in
755 * window "wp".
756 * Return FAIL if writing fails.
757 */
758 int
759term_write_session(FILE *fd, win_T *wp)
760{
761 term_T *term = wp->w_buffer->b_term;
762
763 /* Create the terminal and run the command. This is not without
764 * risk, but let's assume the user only creates a session when this
765 * will be OK. */
766 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
767 term->tl_cols, term->tl_rows) < 0)
768 return FAIL;
769 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
770 return FAIL;
771
772 return put_eol(fd);
773}
774
775/*
776 * Return TRUE if "buf" has a terminal that should be restored.
777 */
778 int
779term_should_restore(buf_T *buf)
780{
781 term_T *term = buf->b_term;
782
783 return term != NULL && (term->tl_command == NULL
784 || STRCMP(term->tl_command, "NONE") != 0);
785}
786#endif
787
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200788/*
789 * Free the scrollback buffer for "term".
790 */
791 static void
792free_scrollback(term_T *term)
793{
794 int i;
795
796 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
797 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
798 ga_clear(&term->tl_scrollback);
799}
800
801/*
802 * Free a terminal and everything it refers to.
803 * Kills the job if there is one.
804 * Called when wiping out a buffer.
805 */
806 void
807free_terminal(buf_T *buf)
808{
809 term_T *term = buf->b_term;
810 term_T *tp;
811
812 if (term == NULL)
813 return;
814 if (first_term == term)
815 first_term = term->tl_next;
816 else
817 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
818 if (tp->tl_next == term)
819 {
820 tp->tl_next = term->tl_next;
821 break;
822 }
823
824 if (term->tl_job != NULL)
825 {
826 if (term->tl_job->jv_status != JOB_ENDED
827 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100828 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200829 job_stop(term->tl_job, NULL, "kill");
830 job_unref(term->tl_job);
831 }
832
833 free_scrollback(term);
834
835 term_free_vterm(term);
836 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100837#ifdef FEAT_SESSION
838 vim_free(term->tl_command);
839#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100840 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 vim_free(term->tl_status_text);
842 vim_free(term->tl_opencmd);
843 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200844#ifdef WIN3264
845 if (term->tl_out_fd != NULL)
846 fclose(term->tl_out_fd);
847#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100848 if (desired_cursor_color == term->tl_cursor_color)
849 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200850 vim_free(term->tl_cursor_color);
851 vim_free(term);
852 buf->b_term = NULL;
853 if (in_terminal_loop == term)
854 in_terminal_loop = NULL;
855}
856
857/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100858 * Get the part that is connected to the tty. Normally this is PART_IN, but
859 * when writing buffer lines to the job it can be another. This makes it
860 * possible to do "1,5term vim -".
861 */
862 static ch_part_T
863get_tty_part(term_T *term)
864{
865#ifdef UNIX
866 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
867 int i;
868
869 for (i = 0; i < 3; ++i)
870 {
871 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
872
873 if (isatty(fd))
874 return parts[i];
875 }
876#endif
877 return PART_IN;
878}
879
880/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881 * Write job output "msg[len]" to the vterm.
882 */
883 static void
884term_write_job_output(term_T *term, char_u *msg, size_t len)
885{
886 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100887 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100889 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200890
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100891 /* flush vterm buffer when vterm responded to control sequence */
892 if (prevlen != vterm_output_get_buffer_current(vterm))
893 {
894 char buf[KEY_BUF_LEN];
895 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
896
897 if (curlen > 0)
898 channel_send(term->tl_job->jv_channel, get_tty_part(term),
899 (char_u *)buf, (int)curlen, NULL);
900 }
901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200902 /* this invokes the damage callbacks */
903 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
904}
905
906 static void
907update_cursor(term_T *term, int redraw)
908{
909 if (term->tl_normal_mode)
910 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100911#ifdef FEAT_GUI
912 if (term->tl_system)
913 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
914 term->tl_cursor_pos.col);
915 else
916#endif
917 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200918 if (redraw)
919 {
920 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
921 cursor_on();
922 out_flush();
923#ifdef FEAT_GUI
924 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100925 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200926 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100927 gui_mch_flush();
928 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200929#endif
930 }
931}
932
933/*
934 * Invoked when "msg" output from a job was received. Write it to the terminal
935 * of "buffer".
936 */
937 void
938write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
939{
940 size_t len = STRLEN(msg);
941 term_T *term = buffer->b_term;
942
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200943#ifdef WIN3264
944 /* Win32: Cannot redirect output of the job, intercept it here and write to
945 * the file. */
946 if (term->tl_out_fd != NULL)
947 {
948 ch_log(channel, "Writing %d bytes to output file", (int)len);
949 fwrite(msg, len, 1, term->tl_out_fd);
950 return;
951 }
952#endif
953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200954 if (term->tl_vterm == NULL)
955 {
956 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
957 return;
958 }
959 ch_log(channel, "writing %d bytes to terminal", (int)len);
960 term_write_job_output(term, msg, len);
961
Bram Moolenaar13568252018-03-16 20:46:58 +0100962#ifdef FEAT_GUI
963 if (term->tl_system)
964 {
965 /* show system output, scrolling up the screen as needed */
966 update_system_term(term);
967 update_cursor(term, TRUE);
968 }
969 else
970#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
972 * contents, thus no screen update is needed. */
973 if (!term->tl_normal_mode)
974 {
975 /* TODO: only update once in a while. */
976 ch_log(term->tl_job->jv_channel, "updating screen");
977 if (buffer == curbuf)
978 {
979 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200980 /* update_screen() can be slow, check the terminal wasn't closed
981 * already */
982 if (buffer == curbuf && curbuf->b_term != NULL)
983 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200984 }
985 else
986 redraw_after_callback(TRUE);
987 }
988}
989
990/*
991 * Send a mouse position and click to the vterm
992 */
993 static int
994term_send_mouse(VTerm *vterm, int button, int pressed)
995{
996 VTermModifier mod = VTERM_MOD_NONE;
997
998 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200999 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001000 if (button != 0)
1001 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001002 return TRUE;
1003}
1004
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001005static int enter_mouse_col = -1;
1006static int enter_mouse_row = -1;
1007
1008/*
1009 * Handle a mouse click, drag or release.
1010 * Return TRUE when a mouse event is sent to the terminal.
1011 */
1012 static int
1013term_mouse_click(VTerm *vterm, int key)
1014{
1015#if defined(FEAT_CLIPBOARD)
1016 /* For modeless selection mouse drag and release events are ignored, unless
1017 * they are preceded with a mouse down event */
1018 static int ignore_drag_release = TRUE;
1019 VTermMouseState mouse_state;
1020
1021 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1022 if (mouse_state.flags == 0)
1023 {
1024 /* Terminal is not using the mouse, use modeless selection. */
1025 switch (key)
1026 {
1027 case K_LEFTDRAG:
1028 case K_LEFTRELEASE:
1029 case K_RIGHTDRAG:
1030 case K_RIGHTRELEASE:
1031 /* Ignore drag and release events when the button-down wasn't
1032 * seen before. */
1033 if (ignore_drag_release)
1034 {
1035 int save_mouse_col, save_mouse_row;
1036
1037 if (enter_mouse_col < 0)
1038 break;
1039
1040 /* mouse click in the window gave us focus, handle that
1041 * click now */
1042 save_mouse_col = mouse_col;
1043 save_mouse_row = mouse_row;
1044 mouse_col = enter_mouse_col;
1045 mouse_row = enter_mouse_row;
1046 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1047 mouse_col = save_mouse_col;
1048 mouse_row = save_mouse_row;
1049 }
1050 /* FALLTHROUGH */
1051 case K_LEFTMOUSE:
1052 case K_RIGHTMOUSE:
1053 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1054 ignore_drag_release = TRUE;
1055 else
1056 ignore_drag_release = FALSE;
1057 /* Should we call mouse_has() here? */
1058 if (clip_star.available)
1059 {
1060 int button, is_click, is_drag;
1061
1062 button = get_mouse_button(KEY2TERMCAP1(key),
1063 &is_click, &is_drag);
1064 if (mouse_model_popup() && button == MOUSE_LEFT
1065 && (mod_mask & MOD_MASK_SHIFT))
1066 {
1067 /* Translate shift-left to right button. */
1068 button = MOUSE_RIGHT;
1069 mod_mask &= ~MOD_MASK_SHIFT;
1070 }
1071 clip_modeless(button, is_click, is_drag);
1072 }
1073 break;
1074
1075 case K_MIDDLEMOUSE:
1076 if (clip_star.available)
1077 insert_reg('*', TRUE);
1078 break;
1079 }
1080 enter_mouse_col = -1;
1081 return FALSE;
1082 }
1083#endif
1084 enter_mouse_col = -1;
1085
1086 switch (key)
1087 {
1088 case K_LEFTMOUSE:
1089 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1090 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1091 case K_LEFTRELEASE:
1092 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1093 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1094 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1095 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1096 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1097 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1098 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1099 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1100 }
1101 return TRUE;
1102}
1103
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001104/*
1105 * Convert typed key "c" into bytes to send to the job.
1106 * Return the number of bytes in "buf".
1107 */
1108 static int
1109term_convert_key(term_T *term, int c, char *buf)
1110{
1111 VTerm *vterm = term->tl_vterm;
1112 VTermKey key = VTERM_KEY_NONE;
1113 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001114 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001115
1116 switch (c)
1117 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001118 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1119
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001120 /* don't use VTERM_KEY_BACKSPACE, it always
1121 * becomes 0x7f DEL */
1122 case K_BS: c = term_backspace_char; break;
1123
1124 case ESC: key = VTERM_KEY_ESCAPE; break;
1125 case K_DEL: key = VTERM_KEY_DEL; break;
1126 case K_DOWN: key = VTERM_KEY_DOWN; break;
1127 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1128 key = VTERM_KEY_DOWN; break;
1129 case K_END: key = VTERM_KEY_END; break;
1130 case K_S_END: mod = VTERM_MOD_SHIFT;
1131 key = VTERM_KEY_END; break;
1132 case K_C_END: mod = VTERM_MOD_CTRL;
1133 key = VTERM_KEY_END; break;
1134 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1135 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1136 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1137 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1138 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1139 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1140 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1141 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1142 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1143 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1144 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1145 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1146 case K_HOME: key = VTERM_KEY_HOME; break;
1147 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1148 key = VTERM_KEY_HOME; break;
1149 case K_C_HOME: mod = VTERM_MOD_CTRL;
1150 key = VTERM_KEY_HOME; break;
1151 case K_INS: key = VTERM_KEY_INS; break;
1152 case K_K0: key = VTERM_KEY_KP_0; break;
1153 case K_K1: key = VTERM_KEY_KP_1; break;
1154 case K_K2: key = VTERM_KEY_KP_2; break;
1155 case K_K3: key = VTERM_KEY_KP_3; break;
1156 case K_K4: key = VTERM_KEY_KP_4; break;
1157 case K_K5: key = VTERM_KEY_KP_5; break;
1158 case K_K6: key = VTERM_KEY_KP_6; break;
1159 case K_K7: key = VTERM_KEY_KP_7; break;
1160 case K_K8: key = VTERM_KEY_KP_8; break;
1161 case K_K9: key = VTERM_KEY_KP_9; break;
1162 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1163 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1164 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1165 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1166 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1167 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1168 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1169 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1170 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1171 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1172 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1173 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1174 case K_LEFT: key = VTERM_KEY_LEFT; break;
1175 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1176 key = VTERM_KEY_LEFT; break;
1177 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1178 key = VTERM_KEY_LEFT; break;
1179 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1180 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1181 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1182 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1183 key = VTERM_KEY_RIGHT; break;
1184 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1185 key = VTERM_KEY_RIGHT; break;
1186 case K_UP: key = VTERM_KEY_UP; break;
1187 case K_S_UP: mod = VTERM_MOD_SHIFT;
1188 key = VTERM_KEY_UP; break;
1189 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001190 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1191 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001192
Bram Moolenaara42ad572017-11-16 13:08:04 +01001193 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1194 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001195 case K_MOUSELEFT: /* TODO */ return 0;
1196 case K_MOUSERIGHT: /* TODO */ return 0;
1197
1198 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001199 case K_LEFTMOUSE_NM:
1200 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001202 case K_LEFTRELEASE_NM:
1203 case K_MOUSEMOVE:
1204 case K_MIDDLEMOUSE:
1205 case K_MIDDLEDRAG:
1206 case K_MIDDLERELEASE:
1207 case K_RIGHTMOUSE:
1208 case K_RIGHTDRAG:
1209 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1210 return 0;
1211 other = TRUE;
1212 break;
1213
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001214 case K_X1MOUSE: /* TODO */ return 0;
1215 case K_X1DRAG: /* TODO */ return 0;
1216 case K_X1RELEASE: /* TODO */ return 0;
1217 case K_X2MOUSE: /* TODO */ return 0;
1218 case K_X2DRAG: /* TODO */ return 0;
1219 case K_X2RELEASE: /* TODO */ return 0;
1220
1221 case K_IGNORE: return 0;
1222 case K_NOP: return 0;
1223 case K_UNDO: return 0;
1224 case K_HELP: return 0;
1225 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1226 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1227 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1228 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1229 case K_SELECT: return 0;
1230#ifdef FEAT_GUI
1231 case K_VER_SCROLLBAR: return 0;
1232 case K_HOR_SCROLLBAR: return 0;
1233#endif
1234#ifdef FEAT_GUI_TABLINE
1235 case K_TABLINE: return 0;
1236 case K_TABMENU: return 0;
1237#endif
1238#ifdef FEAT_NETBEANS_INTG
1239 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1240#endif
1241#ifdef FEAT_DND
1242 case K_DROP: return 0;
1243#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001244 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001245 case K_PS: vterm_keyboard_start_paste(vterm);
1246 other = TRUE;
1247 break;
1248 case K_PE: vterm_keyboard_end_paste(vterm);
1249 other = TRUE;
1250 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001251 }
1252
1253 /*
1254 * Convert special keys to vterm keys:
1255 * - Write keys to vterm: vterm_keyboard_key()
1256 * - Write output to channel.
1257 * TODO: use mod_mask
1258 */
1259 if (key != VTERM_KEY_NONE)
1260 /* Special key, let vterm convert it. */
1261 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001262 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001263 /* Normal character, let vterm convert it. */
1264 vterm_keyboard_unichar(vterm, c, mod);
1265
1266 /* Read back the converted escape sequence. */
1267 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1268}
1269
1270/*
1271 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001272 * If "check_job_status" is TRUE update the job status.
1273 */
1274 static int
1275term_job_running_check(term_T *term, int check_job_status)
1276{
1277 /* Also consider the job finished when the channel is closed, to avoid a
1278 * race condition when updating the title. */
1279 if (term != NULL
1280 && term->tl_job != NULL
1281 && channel_is_open(term->tl_job->jv_channel))
1282 {
1283 if (check_job_status)
1284 job_status(term->tl_job);
1285 return (term->tl_job->jv_status == JOB_STARTED
1286 || term->tl_job->jv_channel->ch_keep_open);
1287 }
1288 return FALSE;
1289}
1290
1291/*
1292 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001293 */
1294 int
1295term_job_running(term_T *term)
1296{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001297 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001298}
1299
1300/*
1301 * Return TRUE if "term" has an active channel and used ":term NONE".
1302 */
1303 int
1304term_none_open(term_T *term)
1305{
1306 /* Also consider the job finished when the channel is closed, to avoid a
1307 * race condition when updating the title. */
1308 return term != NULL
1309 && term->tl_job != NULL
1310 && channel_is_open(term->tl_job->jv_channel)
1311 && term->tl_job->jv_channel->ch_keep_open;
1312}
1313
1314/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001315 * Used when exiting: kill the job in "buf" if so desired.
1316 * Return OK when the job finished.
1317 * Return FAIL when the job is still running.
1318 */
1319 int
1320term_try_stop_job(buf_T *buf)
1321{
1322 int count;
1323 char *how = (char *)buf->b_term->tl_kill;
1324
1325#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1326 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1327 {
1328 char_u buff[DIALOG_MSG_SIZE];
1329 int ret;
1330
1331 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1332 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1333 if (ret == VIM_YES)
1334 how = "kill";
1335 else if (ret == VIM_CANCEL)
1336 return FAIL;
1337 }
1338#endif
1339 if (how == NULL || *how == NUL)
1340 return FAIL;
1341
1342 job_stop(buf->b_term->tl_job, NULL, how);
1343
1344 /* wait for up to a second for the job to die */
1345 for (count = 0; count < 100; ++count)
1346 {
1347 /* buffer, terminal and job may be cleaned up while waiting */
1348 if (!buf_valid(buf)
1349 || buf->b_term == NULL
1350 || buf->b_term->tl_job == NULL)
1351 return OK;
1352
1353 /* call job_status() to update jv_status */
1354 job_status(buf->b_term->tl_job);
1355 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1356 return OK;
1357 ui_delay(10L, FALSE);
1358 mch_check_messages();
1359 parse_queued_messages();
1360 }
1361 return FAIL;
1362}
1363
1364/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365 * Add the last line of the scrollback buffer to the buffer in the window.
1366 */
1367 static void
1368add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1369{
1370 buf_T *buf = term->tl_buffer;
1371 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1372 linenr_T lnum = buf->b_ml.ml_line_count;
1373
1374#ifdef WIN3264
1375 if (!enc_utf8 && enc_codepage > 0)
1376 {
1377 WCHAR *ret = NULL;
1378 int length = 0;
1379
1380 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1381 &ret, &length);
1382 if (ret != NULL)
1383 {
1384 WideCharToMultiByte_alloc(enc_codepage, 0,
1385 ret, length, (char **)&text, &len, 0, 0);
1386 vim_free(ret);
1387 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1388 vim_free(text);
1389 }
1390 }
1391 else
1392#endif
1393 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1394 if (empty)
1395 {
1396 /* Delete the empty line that was in the empty buffer. */
1397 curbuf = buf;
1398 ml_delete(1, FALSE);
1399 curbuf = curwin->w_buffer;
1400 }
1401}
1402
1403 static void
1404cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1405{
1406 attr->width = cell->width;
1407 attr->attrs = cell->attrs;
1408 attr->fg = cell->fg;
1409 attr->bg = cell->bg;
1410}
1411
1412 static int
1413equal_celattr(cellattr_T *a, cellattr_T *b)
1414{
1415 /* Comparing the colors should be sufficient. */
1416 return a->fg.red == b->fg.red
1417 && a->fg.green == b->fg.green
1418 && a->fg.blue == b->fg.blue
1419 && a->bg.red == b->bg.red
1420 && a->bg.green == b->bg.green
1421 && a->bg.blue == b->bg.blue;
1422}
1423
Bram Moolenaard96ff162018-02-18 22:13:29 +01001424/*
1425 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1426 * line at this position. Otherwise at the end.
1427 */
1428 static int
1429add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1430{
1431 if (ga_grow(&term->tl_scrollback, 1) == OK)
1432 {
1433 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1434 + term->tl_scrollback.ga_len;
1435
1436 if (lnum > 0)
1437 {
1438 int i;
1439
1440 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1441 {
1442 *line = *(line - 1);
1443 --line;
1444 }
1445 }
1446 line->sb_cols = 0;
1447 line->sb_cells = NULL;
1448 line->sb_fill_attr = *fill_attr;
1449 ++term->tl_scrollback.ga_len;
1450 return OK;
1451 }
1452 return FALSE;
1453}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001454
1455/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001456 * Remove the terminal contents from the scrollback and the buffer.
1457 * Used before adding a new scrollback line or updating the buffer for lines
1458 * displayed in the terminal.
1459 */
1460 static void
1461cleanup_scrollback(term_T *term)
1462{
1463 sb_line_T *line;
1464 garray_T *gap;
1465
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001466 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001467 gap = &term->tl_scrollback;
1468 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1469 && gap->ga_len > 0)
1470 {
1471 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1472 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1473 vim_free(line->sb_cells);
1474 --gap->ga_len;
1475 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001476 curbuf = curwin->w_buffer;
1477 if (curbuf == term->tl_buffer)
1478 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001479}
1480
1481/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001483 */
1484 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001485update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001486{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001487 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001488 int len;
1489 int lines_skipped = 0;
1490 VTermPos pos;
1491 VTermScreenCell cell;
1492 cellattr_T fill_attr, new_fill_attr;
1493 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001494
1495 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1496 "Adding terminal window snapshot to buffer");
1497
1498 /* First remove the lines that were appended before, they might be
1499 * outdated. */
1500 cleanup_scrollback(term);
1501
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001502 screen = vterm_obtain_screen(term->tl_vterm);
1503 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001504 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1505 {
1506 len = 0;
1507 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1508 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1509 && cell.chars[0] != NUL)
1510 {
1511 len = pos.col + 1;
1512 new_fill_attr = term->tl_default_color;
1513 }
1514 else
1515 /* Assume the last attr is the filler attr. */
1516 cell2cellattr(&cell, &new_fill_attr);
1517
1518 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1519 ++lines_skipped;
1520 else
1521 {
1522 while (lines_skipped > 0)
1523 {
1524 /* Line was skipped, add an empty line. */
1525 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001526 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001527 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001528 }
1529
1530 if (len == 0)
1531 p = NULL;
1532 else
1533 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1534 if ((p != NULL || len == 0)
1535 && ga_grow(&term->tl_scrollback, 1) == OK)
1536 {
1537 garray_T ga;
1538 int width;
1539 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1540 + term->tl_scrollback.ga_len;
1541
1542 ga_init2(&ga, 1, 100);
1543 for (pos.col = 0; pos.col < len; pos.col += width)
1544 {
1545 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1546 {
1547 width = 1;
1548 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1549 if (ga_grow(&ga, 1) == OK)
1550 ga.ga_len += utf_char2bytes(' ',
1551 (char_u *)ga.ga_data + ga.ga_len);
1552 }
1553 else
1554 {
1555 width = cell.width;
1556
1557 cell2cellattr(&cell, &p[pos.col]);
1558
1559 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1560 {
1561 int i;
1562 int c;
1563
1564 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1565 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1566 (char_u *)ga.ga_data + ga.ga_len);
1567 }
1568 }
1569 }
1570 line->sb_cols = len;
1571 line->sb_cells = p;
1572 line->sb_fill_attr = new_fill_attr;
1573 fill_attr = new_fill_attr;
1574 ++term->tl_scrollback.ga_len;
1575
1576 if (ga_grow(&ga, 1) == FAIL)
1577 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1578 else
1579 {
1580 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1581 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1582 }
1583 ga_clear(&ga);
1584 }
1585 else
1586 vim_free(p);
1587 }
1588 }
1589
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001590 term->tl_dirty_snapshot = FALSE;
1591#ifdef FEAT_TIMERS
1592 term->tl_timer_set = FALSE;
1593#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001594}
1595
1596/*
1597 * If needed, add the current lines of the terminal to scrollback and to the
1598 * buffer. Called after the job has ended and when switching to
1599 * Terminal-Normal mode.
1600 * When "redraw" is TRUE redraw the windows that show the terminal.
1601 */
1602 static void
1603may_move_terminal_to_buffer(term_T *term, int redraw)
1604{
1605 win_T *wp;
1606
1607 if (term->tl_vterm == NULL)
1608 return;
1609
1610 /* Update the snapshot only if something changes or the buffer does not
1611 * have all the lines. */
1612 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1613 <= term->tl_scrollback_scrolled)
1614 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001615
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001616 /* Obtain the current background color. */
1617 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1618 &term->tl_default_color.fg, &term->tl_default_color.bg);
1619
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001620 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001621 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001623 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001625 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1626 wp->w_cursor.col = 0;
1627 wp->w_valid = 0;
1628 if (wp->w_cursor.lnum >= wp->w_height)
1629 {
1630 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001632 if (wp->w_topline < min_topline)
1633 wp->w_topline = min_topline;
1634 }
1635 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001638}
1639
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001640#if defined(FEAT_TIMERS) || defined(PROTO)
1641/*
1642 * Check if any terminal timer expired. If so, copy text from the terminal to
1643 * the buffer.
1644 * Return the time until the next timer will expire.
1645 */
1646 int
1647term_check_timers(int next_due_arg, proftime_T *now)
1648{
1649 term_T *term;
1650 int next_due = next_due_arg;
1651
1652 for (term = first_term; term != NULL; term = term->tl_next)
1653 {
1654 if (term->tl_timer_set && !term->tl_normal_mode)
1655 {
1656 long this_due = proftime_time_left(&term->tl_timer_due, now);
1657
1658 if (this_due <= 1)
1659 {
1660 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001661 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001662 }
1663 else if (next_due == -1 || next_due > this_due)
1664 next_due = this_due;
1665 }
1666 }
1667
1668 return next_due;
1669}
1670#endif
1671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672 static void
1673set_terminal_mode(term_T *term, int normal_mode)
1674{
1675 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001676 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001677 if (term->tl_buffer == curbuf)
1678 maketitle();
1679}
1680
1681/*
1682 * Called after the job if finished and Terminal mode is not active:
1683 * Move the vterm contents into the scrollback buffer and free the vterm.
1684 */
1685 static void
1686cleanup_vterm(term_T *term)
1687{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001688 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001689 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001690 term_free_vterm(term);
1691 set_terminal_mode(term, FALSE);
1692}
1693
1694/*
1695 * Switch from Terminal-Job mode to Terminal-Normal mode.
1696 * Suspends updating the terminal window.
1697 */
1698 static void
1699term_enter_normal_mode(void)
1700{
1701 term_T *term = curbuf->b_term;
1702
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001703 set_terminal_mode(term, TRUE);
1704
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001705 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001706 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001707
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001708 /* Move the window cursor to the position of the cursor in the
1709 * terminal. */
1710 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1711 + term->tl_cursor_pos.row + 1;
1712 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001713 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1714 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001715
1716 /* Display the same lines as in the terminal. */
1717 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1718}
1719
1720/*
1721 * Returns TRUE if the current window contains a terminal and we are in
1722 * Terminal-Normal mode.
1723 */
1724 int
1725term_in_normal_mode(void)
1726{
1727 term_T *term = curbuf->b_term;
1728
1729 return term != NULL && term->tl_normal_mode;
1730}
1731
1732/*
1733 * Switch from Terminal-Normal mode to Terminal-Job mode.
1734 * Restores updating the terminal window.
1735 */
1736 void
1737term_enter_job_mode()
1738{
1739 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001740
1741 set_terminal_mode(term, FALSE);
1742
1743 if (term->tl_channel_closed)
1744 cleanup_vterm(term);
1745 redraw_buf_and_status_later(curbuf, NOT_VALID);
1746}
1747
1748/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001749 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750 * Note: while waiting a terminal may be closed and freed if the channel is
1751 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001752 */
1753 static int
1754term_vgetc()
1755{
1756 int c;
1757 int save_State = State;
1758
1759 State = TERMINAL;
1760 got_int = FALSE;
1761#ifdef WIN3264
1762 ctrl_break_was_pressed = FALSE;
1763#endif
1764 c = vgetc();
1765 got_int = FALSE;
1766 State = save_State;
1767 return c;
1768}
1769
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001770static int mouse_was_outside = FALSE;
1771
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001773 * Send keys to terminal.
1774 * Return FAIL when the key needs to be handled in Normal mode.
1775 * Return OK when the key was dropped or sent to the terminal.
1776 */
1777 int
1778send_keys_to_term(term_T *term, int c, int typed)
1779{
1780 char msg[KEY_BUF_LEN];
1781 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001782 int dragging_outside = FALSE;
1783
1784 /* Catch keys that need to be handled as in Normal mode. */
1785 switch (c)
1786 {
1787 case NUL:
1788 case K_ZERO:
1789 if (typed)
1790 stuffcharReadbuff(c);
1791 return FAIL;
1792
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001793 case K_TABLINE:
1794 stuffcharReadbuff(c);
1795 return FAIL;
1796
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001797 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001798 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 return FAIL;
1800
1801 case K_LEFTDRAG:
1802 case K_MIDDLEDRAG:
1803 case K_RIGHTDRAG:
1804 case K_X1DRAG:
1805 case K_X2DRAG:
1806 dragging_outside = mouse_was_outside;
1807 /* FALLTHROUGH */
1808 case K_LEFTMOUSE:
1809 case K_LEFTMOUSE_NM:
1810 case K_LEFTRELEASE:
1811 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001812 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001813 case K_MIDDLEMOUSE:
1814 case K_MIDDLERELEASE:
1815 case K_RIGHTMOUSE:
1816 case K_RIGHTRELEASE:
1817 case K_X1MOUSE:
1818 case K_X1RELEASE:
1819 case K_X2MOUSE:
1820 case K_X2RELEASE:
1821
1822 case K_MOUSEUP:
1823 case K_MOUSEDOWN:
1824 case K_MOUSELEFT:
1825 case K_MOUSERIGHT:
1826 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001827 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001828 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001829 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 || dragging_outside)
1831 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001832 /* click or scroll outside the current window or on status line
1833 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001834 if (typed)
1835 {
1836 stuffcharReadbuff(c);
1837 mouse_was_outside = TRUE;
1838 }
1839 return FAIL;
1840 }
1841 }
1842 if (typed)
1843 mouse_was_outside = FALSE;
1844
1845 /* Convert the typed key to a sequence of bytes for the job. */
1846 len = term_convert_key(term, c, msg);
1847 if (len > 0)
1848 /* TODO: if FAIL is returned, stop? */
1849 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1850 (char_u *)msg, (int)len, NULL);
1851
1852 return OK;
1853}
1854
1855 static void
1856position_cursor(win_T *wp, VTermPos *pos)
1857{
1858 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1859 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1860 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1861}
1862
1863/*
1864 * Handle CTRL-W "": send register contents to the job.
1865 */
1866 static void
1867term_paste_register(int prev_c UNUSED)
1868{
1869 int c;
1870 list_T *l;
1871 listitem_T *item;
1872 long reglen = 0;
1873 int type;
1874
1875#ifdef FEAT_CMDL_INFO
1876 if (add_to_showcmd(prev_c))
1877 if (add_to_showcmd('"'))
1878 out_flush();
1879#endif
1880 c = term_vgetc();
1881#ifdef FEAT_CMDL_INFO
1882 clear_showcmd();
1883#endif
1884 if (!term_use_loop())
1885 /* job finished while waiting for a character */
1886 return;
1887
1888 /* CTRL-W "= prompt for expression to evaluate. */
1889 if (c == '=' && get_expr_register() != '=')
1890 return;
1891 if (!term_use_loop())
1892 /* job finished while waiting for a character */
1893 return;
1894
1895 l = (list_T *)get_reg_contents(c, GREG_LIST);
1896 if (l != NULL)
1897 {
1898 type = get_reg_type(c, &reglen);
1899 for (item = l->lv_first; item != NULL; item = item->li_next)
1900 {
1901 char_u *s = get_tv_string(&item->li_tv);
1902#ifdef WIN3264
1903 char_u *tmp = s;
1904
1905 if (!enc_utf8 && enc_codepage > 0)
1906 {
1907 WCHAR *ret = NULL;
1908 int length = 0;
1909
1910 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1911 (int)STRLEN(s), &ret, &length);
1912 if (ret != NULL)
1913 {
1914 WideCharToMultiByte_alloc(CP_UTF8, 0,
1915 ret, length, (char **)&s, &length, 0, 0);
1916 vim_free(ret);
1917 }
1918 }
1919#endif
1920 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1921 s, (int)STRLEN(s), NULL);
1922#ifdef WIN3264
1923 if (tmp != s)
1924 vim_free(s);
1925#endif
1926
1927 if (item->li_next != NULL || type == MLINE)
1928 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1929 (char_u *)"\r", 1, NULL);
1930 }
1931 list_free(l);
1932 }
1933}
1934
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001935/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001936 * Return TRUE when waiting for a character in the terminal, the cursor of the
1937 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938 */
1939 int
1940terminal_is_active()
1941{
1942 return in_terminal_loop != NULL;
1943}
1944
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001945#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946 cursorentry_T *
1947term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1948{
1949 term_T *term = in_terminal_loop;
1950 static cursorentry_T entry;
1951
1952 vim_memset(&entry, 0, sizeof(entry));
1953 entry.shape = entry.mshape =
1954 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1955 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1956 SHAPE_BLOCK;
1957 entry.percentage = 20;
1958 if (term->tl_cursor_blink)
1959 {
1960 entry.blinkwait = 700;
1961 entry.blinkon = 400;
1962 entry.blinkoff = 250;
1963 }
1964 *fg = gui.back_pixel;
1965 if (term->tl_cursor_color == NULL)
1966 *bg = gui.norm_pixel;
1967 else
1968 *bg = color_name2handle(term->tl_cursor_color);
1969 entry.name = "n";
1970 entry.used_for = SHAPE_CURSOR;
1971
1972 return &entry;
1973}
1974#endif
1975
Bram Moolenaard317b382018-02-08 22:33:31 +01001976 static void
1977may_output_cursor_props(void)
1978{
1979 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1980 || last_set_cursor_shape != desired_cursor_shape
1981 || last_set_cursor_blink != desired_cursor_blink)
1982 {
1983 last_set_cursor_color = desired_cursor_color;
1984 last_set_cursor_shape = desired_cursor_shape;
1985 last_set_cursor_blink = desired_cursor_blink;
1986 term_cursor_color(desired_cursor_color);
1987 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1988 /* this will restore the initial cursor style, if possible */
1989 ui_cursor_shape_forced(TRUE);
1990 else
1991 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1992 }
1993}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994
Bram Moolenaard317b382018-02-08 22:33:31 +01001995/*
1996 * Set the cursor color and shape, if not last set to these.
1997 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 static void
1999may_set_cursor_props(term_T *term)
2000{
2001#ifdef FEAT_GUI
2002 /* For the GUI the cursor properties are obtained with
2003 * term_get_cursor_shape(). */
2004 if (gui.in_use)
2005 return;
2006#endif
2007 if (in_terminal_loop == term)
2008 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01002010 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 else
Bram Moolenaard317b382018-02-08 22:33:31 +01002012 desired_cursor_color = (char_u *)"";
2013 desired_cursor_shape = term->tl_cursor_shape;
2014 desired_cursor_blink = term->tl_cursor_blink;
2015 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 }
2017}
2018
Bram Moolenaard317b382018-02-08 22:33:31 +01002019/*
2020 * Reset the desired cursor properties and restore them when needed.
2021 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002023prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002024{
2025#ifdef FEAT_GUI
2026 if (gui.in_use)
2027 return;
2028#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002029 desired_cursor_color = (char_u *)"";
2030 desired_cursor_shape = -1;
2031 desired_cursor_blink = -1;
2032 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033}
2034
2035/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002036 * Returns TRUE if the current window contains a terminal and we are sending
2037 * keys to the job.
2038 * If "check_job_status" is TRUE update the job status.
2039 */
2040 static int
2041term_use_loop_check(int check_job_status)
2042{
2043 term_T *term = curbuf->b_term;
2044
2045 return term != NULL
2046 && !term->tl_normal_mode
2047 && term->tl_vterm != NULL
2048 && term_job_running_check(term, check_job_status);
2049}
2050
2051/*
2052 * Returns TRUE if the current window contains a terminal and we are sending
2053 * keys to the job.
2054 */
2055 int
2056term_use_loop(void)
2057{
2058 return term_use_loop_check(FALSE);
2059}
2060
2061/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002062 * Called when entering a window with the mouse. If this is a terminal window
2063 * we may want to change state.
2064 */
2065 void
2066term_win_entered()
2067{
2068 term_T *term = curbuf->b_term;
2069
2070 if (term != NULL)
2071 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002072 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002073 {
2074 reset_VIsual_and_resel();
2075 if (State & INSERT)
2076 stop_insert_mode = TRUE;
2077 }
2078 mouse_was_outside = FALSE;
2079 enter_mouse_col = mouse_col;
2080 enter_mouse_row = mouse_row;
2081 }
2082}
2083
2084/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085 * Wait for input and send it to the job.
2086 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2087 * when there is no more typahead.
2088 * Return when the start of a CTRL-W command is typed or anything else that
2089 * should be handled as a Normal mode command.
2090 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2091 * the terminal was closed.
2092 */
2093 int
2094terminal_loop(int blocking)
2095{
2096 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002097 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002098 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002099#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002100 int tty_fd = curbuf->b_term->tl_job->jv_channel
2101 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002102#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002103 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002104
2105 /* Remember the terminal we are sending keys to. However, the terminal
2106 * might be closed while waiting for a character, e.g. typing "exit" in a
2107 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2108 * stored reference. */
2109 in_terminal_loop = curbuf->b_term;
2110
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002111 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002112 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002113 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2114 may_set_cursor_props(curbuf->b_term);
2115
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002116 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002118#ifdef FEAT_GUI
2119 if (!curbuf->b_term->tl_system)
2120#endif
2121 /* TODO: skip screen update when handling a sequence of keys. */
2122 /* Repeat redrawing in case a message is received while redrawing.
2123 */
2124 while (must_redraw != 0)
2125 if (update_screen(0) == FAIL)
2126 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002127 if (!term_use_loop_check(TRUE))
2128 /* job finished while redrawing */
2129 break;
2130
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002132 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002133
2134 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002135 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002136 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002137 /* Job finished while waiting for a character. Push back the
2138 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002139 if (c != K_IGNORE)
2140 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002142 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002143 if (c == K_IGNORE)
2144 continue;
2145
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002146#ifdef UNIX
2147 /*
2148 * The shell or another program may change the tty settings. Getting
2149 * them for every typed character is a bit of overhead, but it's needed
2150 * for the first character typed, e.g. when Vim starts in a shell.
2151 */
2152 if (isatty(tty_fd))
2153 {
2154 ttyinfo_T info;
2155
2156 /* Get the current backspace character of the pty. */
2157 if (get_tty_info(tty_fd, &info) == OK)
2158 term_backspace_char = info.backspace;
2159 }
2160#endif
2161
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162#ifdef WIN3264
2163 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2164 * Use CTRL-BREAK to kill the job. */
2165 if (ctrl_break_was_pressed)
2166 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2167#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002168 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002169 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002170 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002171#ifdef FEAT_GUI
2172 && !curbuf->b_term->tl_system
2173#endif
2174 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 {
2176 int prev_c = c;
2177
2178#ifdef FEAT_CMDL_INFO
2179 if (add_to_showcmd(c))
2180 out_flush();
2181#endif
2182 c = term_vgetc();
2183#ifdef FEAT_CMDL_INFO
2184 clear_showcmd();
2185#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002186 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002187 /* job finished while waiting for a character */
2188 break;
2189
2190 if (prev_c == Ctrl_BSL)
2191 {
2192 if (c == Ctrl_N)
2193 {
2194 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2195 term_enter_normal_mode();
2196 ret = FAIL;
2197 goto theend;
2198 }
2199 /* Send both keys to the terminal. */
2200 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2201 }
2202 else if (c == Ctrl_C)
2203 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002204 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002205 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2206 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002207 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 {
2209 /* "CTRL-W .": send CTRL-W to the job */
2210 c = Ctrl_W;
2211 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002212 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002213 {
2214 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2215 c = Ctrl_BSL;
2216 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 else if (c == 'N')
2218 {
2219 /* CTRL-W N : go to Terminal-Normal mode. */
2220 term_enter_normal_mode();
2221 ret = FAIL;
2222 goto theend;
2223 }
2224 else if (c == '"')
2225 {
2226 term_paste_register(prev_c);
2227 continue;
2228 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002229 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002230 {
2231 stuffcharReadbuff(Ctrl_W);
2232 stuffcharReadbuff(c);
2233 ret = OK;
2234 goto theend;
2235 }
2236 }
2237# ifdef WIN3264
2238 if (!enc_utf8 && has_mbyte && c >= 0x80)
2239 {
2240 WCHAR wc;
2241 char_u mb[3];
2242
2243 mb[0] = (unsigned)c >> 8;
2244 mb[1] = c;
2245 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2246 c = wc;
2247 }
2248# endif
2249 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2250 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002251 if (c == K_MOUSEMOVE)
2252 /* We are sure to come back here, don't reset the cursor color
2253 * and shape to avoid flickering. */
2254 restore_cursor = FALSE;
2255
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 ret = OK;
2257 goto theend;
2258 }
2259 }
2260 ret = FAIL;
2261
2262theend:
2263 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002264 if (restore_cursor)
2265 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002266
2267 /* Move a snapshot of the screen contents to the buffer, so that completion
2268 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002269 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2270 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002271
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002272 return ret;
2273}
2274
2275/*
2276 * Called when a job has finished.
2277 * This updates the title and status, but does not close the vterm, because
2278 * there might still be pending output in the channel.
2279 */
2280 void
2281term_job_ended(job_T *job)
2282{
2283 term_T *term;
2284 int did_one = FALSE;
2285
2286 for (term = first_term; term != NULL; term = term->tl_next)
2287 if (term->tl_job == job)
2288 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002289 VIM_CLEAR(term->tl_title);
2290 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291 redraw_buf_and_status_later(term->tl_buffer, VALID);
2292 did_one = TRUE;
2293 }
2294 if (did_one)
2295 redraw_statuslines();
2296 if (curbuf->b_term != NULL)
2297 {
2298 if (curbuf->b_term->tl_job == job)
2299 maketitle();
2300 update_cursor(curbuf->b_term, TRUE);
2301 }
2302}
2303
2304 static void
2305may_toggle_cursor(term_T *term)
2306{
2307 if (in_terminal_loop == term)
2308 {
2309 if (term->tl_cursor_visible)
2310 cursor_on();
2311 else
2312 cursor_off();
2313 }
2314}
2315
2316/*
2317 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002318 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002319 */
2320 static int
2321color2index(VTermColor *color, int fg, int *boldp)
2322{
2323 int red = color->red;
2324 int blue = color->blue;
2325 int green = color->green;
2326
Bram Moolenaar46359e12017-11-29 22:33:38 +01002327 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002328 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002329 /* First 16 colors and default: use the ANSI index, because these
2330 * colors can be redefined. */
2331 if (t_colors >= 16)
2332 return color->ansi_index;
2333 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002335 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002336 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002337 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2338 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2339 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002340 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002341 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2342 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2343 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2344 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2345 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2346 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2347 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2348 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2349 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2350 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2351 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002352 }
2353 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002354
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002355 if (t_colors >= 256)
2356 {
2357 if (red == blue && red == green)
2358 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002359 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002360 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002361 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2362 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2363 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002364 int i;
2365
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002366 if (red < 5)
2367 return 17; /* 00/00/00 */
2368 if (red > 245) /* ff/ff/ff */
2369 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002370 for (i = 0; i < 23; ++i)
2371 if (red < cutoff[i])
2372 return i + 233;
2373 return 256;
2374 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002375 {
2376 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2377 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002379 /* 216-color cube */
2380 for (ri = 0; ri < 5; ++ri)
2381 if (red < cutoff[ri])
2382 break;
2383 for (gi = 0; gi < 5; ++gi)
2384 if (green < cutoff[gi])
2385 break;
2386 for (bi = 0; bi < 5; ++bi)
2387 if (blue < cutoff[bi])
2388 break;
2389 return 17 + ri * 36 + gi * 6 + bi;
2390 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002391 }
2392 return 0;
2393}
2394
2395/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002396 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 */
2398 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002399vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002400{
2401 int attr = 0;
2402
2403 if (cellattrs.bold)
2404 attr |= HL_BOLD;
2405 if (cellattrs.underline)
2406 attr |= HL_UNDERLINE;
2407 if (cellattrs.italic)
2408 attr |= HL_ITALIC;
2409 if (cellattrs.strike)
2410 attr |= HL_STRIKETHROUGH;
2411 if (cellattrs.reverse)
2412 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002413 return attr;
2414}
2415
2416/*
2417 * Store Vterm attributes in "cell" from highlight flags.
2418 */
2419 static void
2420hl2vtermAttr(int attr, cellattr_T *cell)
2421{
2422 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2423 if (attr & HL_BOLD)
2424 cell->attrs.bold = 1;
2425 if (attr & HL_UNDERLINE)
2426 cell->attrs.underline = 1;
2427 if (attr & HL_ITALIC)
2428 cell->attrs.italic = 1;
2429 if (attr & HL_STRIKETHROUGH)
2430 cell->attrs.strike = 1;
2431 if (attr & HL_INVERSE)
2432 cell->attrs.reverse = 1;
2433}
2434
2435/*
2436 * Convert the attributes of a vterm cell into an attribute index.
2437 */
2438 static int
2439cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2440{
2441 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442
2443#ifdef FEAT_GUI
2444 if (gui.in_use)
2445 {
2446 guicolor_T fg, bg;
2447
2448 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2449 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2450 return get_gui_attr_idx(attr, fg, bg);
2451 }
2452 else
2453#endif
2454#ifdef FEAT_TERMGUICOLORS
2455 if (p_tgc)
2456 {
2457 guicolor_T fg, bg;
2458
2459 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2460 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2461
2462 return get_tgc_attr_idx(attr, fg, bg);
2463 }
2464 else
2465#endif
2466 {
2467 int bold = MAYBE;
2468 int fg = color2index(&cellfg, TRUE, &bold);
2469 int bg = color2index(&cellbg, FALSE, &bold);
2470
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002471 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002472 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002473 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002474 if (fg == 0 && term_default_cterm_fg >= 0)
2475 fg = term_default_cterm_fg + 1;
2476 if (bg == 0 && term_default_cterm_bg >= 0)
2477 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002478 }
2479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 /* with 8 colors set the bold attribute to get a bright foreground */
2481 if (bold == TRUE)
2482 attr |= HL_BOLD;
2483 return get_cterm_attr_idx(attr, fg, bg);
2484 }
2485 return 0;
2486}
2487
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002488 static void
2489set_dirty_snapshot(term_T *term)
2490{
2491 term->tl_dirty_snapshot = TRUE;
2492#ifdef FEAT_TIMERS
2493 if (!term->tl_normal_mode)
2494 {
2495 /* Update the snapshot after 100 msec of not getting updates. */
2496 profile_setlimit(100L, &term->tl_timer_due);
2497 term->tl_timer_set = TRUE;
2498 }
2499#endif
2500}
2501
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002502 static int
2503handle_damage(VTermRect rect, void *user)
2504{
2505 term_T *term = (term_T *)user;
2506
2507 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2508 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002509 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002510 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002511 return 1;
2512}
2513
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002514 static void
2515term_scroll_up(term_T *term, int start_row, int count)
2516{
2517 win_T *wp;
2518 VTermColor fg, bg;
2519 VTermScreenCellAttrs attr;
2520 int clear_attr;
2521
2522 /* Set the color to clear lines with. */
2523 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2524 &fg, &bg);
2525 vim_memset(&attr, 0, sizeof(attr));
2526 clear_attr = cell2attr(attr, fg, bg);
2527
2528 FOR_ALL_WINDOWS(wp)
2529 {
2530 if (wp->w_buffer == term->tl_buffer)
2531 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2532 }
2533}
2534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002535 static int
2536handle_moverect(VTermRect dest, VTermRect src, void *user)
2537{
2538 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002539 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540
2541 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002542 * redrawing the text. But avoid doing this multiple times, postpone until
2543 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 if (dest.start_col == src.start_col
2545 && dest.end_col == src.end_col
2546 && dest.start_row < src.start_row)
2547 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002548 if (dest.start_row == 0)
2549 term->tl_postponed_scroll += count;
2550 else
2551 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002553
2554 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2555 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002556 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002557
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002558 /* Note sure if the scrolling will work correctly, let's do a complete
2559 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002560 redraw_buf_later(term->tl_buffer, NOT_VALID);
2561 return 1;
2562}
2563
2564 static int
2565handle_movecursor(
2566 VTermPos pos,
2567 VTermPos oldpos UNUSED,
2568 int visible,
2569 void *user)
2570{
2571 term_T *term = (term_T *)user;
2572 win_T *wp;
2573
2574 term->tl_cursor_pos = pos;
2575 term->tl_cursor_visible = visible;
2576
2577 FOR_ALL_WINDOWS(wp)
2578 {
2579 if (wp->w_buffer == term->tl_buffer)
2580 position_cursor(wp, &pos);
2581 }
2582 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2583 {
2584 may_toggle_cursor(term);
2585 update_cursor(term, term->tl_cursor_visible);
2586 }
2587
2588 return 1;
2589}
2590
2591 static int
2592handle_settermprop(
2593 VTermProp prop,
2594 VTermValue *value,
2595 void *user)
2596{
2597 term_T *term = (term_T *)user;
2598
2599 switch (prop)
2600 {
2601 case VTERM_PROP_TITLE:
2602 vim_free(term->tl_title);
2603 /* a blank title isn't useful, make it empty, so that "running" is
2604 * displayed */
2605 if (*skipwhite((char_u *)value->string) == NUL)
2606 term->tl_title = NULL;
2607#ifdef WIN3264
2608 else if (!enc_utf8 && enc_codepage > 0)
2609 {
2610 WCHAR *ret = NULL;
2611 int length = 0;
2612
2613 MultiByteToWideChar_alloc(CP_UTF8, 0,
2614 (char*)value->string, (int)STRLEN(value->string),
2615 &ret, &length);
2616 if (ret != NULL)
2617 {
2618 WideCharToMultiByte_alloc(enc_codepage, 0,
2619 ret, length, (char**)&term->tl_title,
2620 &length, 0, 0);
2621 vim_free(ret);
2622 }
2623 }
2624#endif
2625 else
2626 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002627 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 if (term == curbuf->b_term)
2629 maketitle();
2630 break;
2631
2632 case VTERM_PROP_CURSORVISIBLE:
2633 term->tl_cursor_visible = value->boolean;
2634 may_toggle_cursor(term);
2635 out_flush();
2636 break;
2637
2638 case VTERM_PROP_CURSORBLINK:
2639 term->tl_cursor_blink = value->boolean;
2640 may_set_cursor_props(term);
2641 break;
2642
2643 case VTERM_PROP_CURSORSHAPE:
2644 term->tl_cursor_shape = value->number;
2645 may_set_cursor_props(term);
2646 break;
2647
2648 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002649 if (desired_cursor_color == term->tl_cursor_color)
2650 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002651 vim_free(term->tl_cursor_color);
2652 if (*value->string == NUL)
2653 term->tl_cursor_color = NULL;
2654 else
2655 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2656 may_set_cursor_props(term);
2657 break;
2658
2659 case VTERM_PROP_ALTSCREEN:
2660 /* TODO: do anything else? */
2661 term->tl_using_altscreen = value->boolean;
2662 break;
2663
2664 default:
2665 break;
2666 }
2667 /* Always return 1, otherwise vterm doesn't store the value internally. */
2668 return 1;
2669}
2670
2671/*
2672 * The job running in the terminal resized the terminal.
2673 */
2674 static int
2675handle_resize(int rows, int cols, void *user)
2676{
2677 term_T *term = (term_T *)user;
2678 win_T *wp;
2679
2680 term->tl_rows = rows;
2681 term->tl_cols = cols;
2682 if (term->tl_vterm_size_changed)
2683 /* Size was set by vterm_set_size(), don't set the window size. */
2684 term->tl_vterm_size_changed = FALSE;
2685 else
2686 {
2687 FOR_ALL_WINDOWS(wp)
2688 {
2689 if (wp->w_buffer == term->tl_buffer)
2690 {
2691 win_setheight_win(rows, wp);
2692 win_setwidth_win(cols, wp);
2693 }
2694 }
2695 redraw_buf_later(term->tl_buffer, NOT_VALID);
2696 }
2697 return 1;
2698}
2699
2700/*
2701 * Handle a line that is pushed off the top of the screen.
2702 */
2703 static int
2704handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2705{
2706 term_T *term = (term_T *)user;
2707
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002708 /* First remove the lines that were appended before, the pushed line goes
2709 * above it. */
2710 cleanup_scrollback(term);
2711
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002712 /* If the number of lines that are stored goes over 'termscrollback' then
2713 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002714 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002715 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002716 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002717 int i;
2718
2719 curbuf = term->tl_buffer;
2720 for (i = 0; i < todo; ++i)
2721 {
2722 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2723 ml_delete(1, FALSE);
2724 }
2725 curbuf = curwin->w_buffer;
2726
2727 term->tl_scrollback.ga_len -= todo;
2728 mch_memmove(term->tl_scrollback.ga_data,
2729 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2730 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002731 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002732 }
2733
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002734 if (ga_grow(&term->tl_scrollback, 1) == OK)
2735 {
2736 cellattr_T *p = NULL;
2737 int len = 0;
2738 int i;
2739 int c;
2740 int col;
2741 sb_line_T *line;
2742 garray_T ga;
2743 cellattr_T fill_attr = term->tl_default_color;
2744
2745 /* do not store empty cells at the end */
2746 for (i = 0; i < cols; ++i)
2747 if (cells[i].chars[0] != 0)
2748 len = i + 1;
2749 else
2750 cell2cellattr(&cells[i], &fill_attr);
2751
2752 ga_init2(&ga, 1, 100);
2753 if (len > 0)
2754 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2755 if (p != NULL)
2756 {
2757 for (col = 0; col < len; col += cells[col].width)
2758 {
2759 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2760 {
2761 ga.ga_len = 0;
2762 break;
2763 }
2764 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2765 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2766 (char_u *)ga.ga_data + ga.ga_len);
2767 cell2cellattr(&cells[col], &p[col]);
2768 }
2769 }
2770 if (ga_grow(&ga, 1) == FAIL)
2771 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2772 else
2773 {
2774 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2775 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2776 }
2777 ga_clear(&ga);
2778
2779 line = (sb_line_T *)term->tl_scrollback.ga_data
2780 + term->tl_scrollback.ga_len;
2781 line->sb_cols = len;
2782 line->sb_cells = p;
2783 line->sb_fill_attr = fill_attr;
2784 ++term->tl_scrollback.ga_len;
2785 ++term->tl_scrollback_scrolled;
2786 }
2787 return 0; /* ignored */
2788}
2789
2790static VTermScreenCallbacks screen_callbacks = {
2791 handle_damage, /* damage */
2792 handle_moverect, /* moverect */
2793 handle_movecursor, /* movecursor */
2794 handle_settermprop, /* settermprop */
2795 NULL, /* bell */
2796 handle_resize, /* resize */
2797 handle_pushline, /* sb_pushline */
2798 NULL /* sb_popline */
2799};
2800
2801/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002802 * Do the work after the channel of a terminal was closed.
2803 * Must be called only when updating_screen is FALSE.
2804 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2805 */
2806 static int
2807term_after_channel_closed(term_T *term)
2808{
2809 /* Unless in Terminal-Normal mode: clear the vterm. */
2810 if (!term->tl_normal_mode)
2811 {
2812 int fnum = term->tl_buffer->b_fnum;
2813
2814 cleanup_vterm(term);
2815
2816 if (term->tl_finish == TL_FINISH_CLOSE)
2817 {
2818 aco_save_T aco;
2819
2820 /* ++close or term_finish == "close" */
2821 ch_log(NULL, "terminal job finished, closing window");
2822 aucmd_prepbuf(&aco, term->tl_buffer);
2823 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2824 aucmd_restbuf(&aco);
2825 return TRUE;
2826 }
2827 if (term->tl_finish == TL_FINISH_OPEN
2828 && term->tl_buffer->b_nwindows == 0)
2829 {
2830 char buf[50];
2831
2832 /* TODO: use term_opencmd */
2833 ch_log(NULL, "terminal job finished, opening window");
2834 vim_snprintf(buf, sizeof(buf),
2835 term->tl_opencmd == NULL
2836 ? "botright sbuf %d"
2837 : (char *)term->tl_opencmd, fnum);
2838 do_cmdline_cmd((char_u *)buf);
2839 }
2840 else
2841 ch_log(NULL, "terminal job finished");
2842 }
2843
2844 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2845 return FALSE;
2846}
2847
2848/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849 * Called when a channel has been closed.
2850 * If this was a channel for a terminal window then finish it up.
2851 */
2852 void
2853term_channel_closed(channel_T *ch)
2854{
2855 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002856 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002857 int did_one = FALSE;
2858
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002859 for (term = first_term; term != NULL; term = next_term)
2860 {
2861 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 if (term->tl_job == ch->ch_job)
2863 {
2864 term->tl_channel_closed = TRUE;
2865 did_one = TRUE;
2866
Bram Moolenaard23a8232018-02-10 18:45:26 +01002867 VIM_CLEAR(term->tl_title);
2868 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002869#ifdef WIN3264
2870 if (term->tl_out_fd != NULL)
2871 {
2872 fclose(term->tl_out_fd);
2873 term->tl_out_fd = NULL;
2874 }
2875#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002877 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002879 /* Cannot open or close windows now. Can happen when
2880 * 'lazyredraw' is set. */
2881 term->tl_channel_recently_closed = TRUE;
2882 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 }
2884
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002885 if (term_after_channel_closed(term))
2886 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002887 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002888 }
2889
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002890 if (did_one)
2891 {
2892 redraw_statuslines();
2893
2894 /* Need to break out of vgetc(). */
2895 ins_char_typebuf(K_IGNORE);
2896 typebuf_was_filled = TRUE;
2897
2898 term = curbuf->b_term;
2899 if (term != NULL)
2900 {
2901 if (term->tl_job == ch->ch_job)
2902 maketitle();
2903 update_cursor(term, term->tl_cursor_visible);
2904 }
2905 }
2906}
2907
2908/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002909 * To be called after resetting updating_screen: handle any terminal where the
2910 * channel was closed.
2911 */
2912 void
2913term_check_channel_closed_recently()
2914{
2915 term_T *term;
2916 term_T *next_term;
2917
2918 for (term = first_term; term != NULL; term = next_term)
2919 {
2920 next_term = term->tl_next;
2921 if (term->tl_channel_recently_closed)
2922 {
2923 term->tl_channel_recently_closed = FALSE;
2924 if (term_after_channel_closed(term))
2925 // start over, the list may have changed
2926 next_term = first_term;
2927 }
2928 }
2929}
2930
2931/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002932 * Fill one screen line from a line of the terminal.
2933 * Advances "pos" to past the last column.
2934 */
2935 static void
2936term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2937{
2938 int off = screen_get_current_line_off();
2939
2940 for (pos->col = 0; pos->col < max_col; )
2941 {
2942 VTermScreenCell cell;
2943 int c;
2944
2945 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2946 vim_memset(&cell, 0, sizeof(cell));
2947
2948 c = cell.chars[0];
2949 if (c == NUL)
2950 {
2951 ScreenLines[off] = ' ';
2952 if (enc_utf8)
2953 ScreenLinesUC[off] = NUL;
2954 }
2955 else
2956 {
2957 if (enc_utf8)
2958 {
2959 int i;
2960
2961 /* composing chars */
2962 for (i = 0; i < Screen_mco
2963 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2964 {
2965 ScreenLinesC[i][off] = cell.chars[i + 1];
2966 if (cell.chars[i + 1] == 0)
2967 break;
2968 }
2969 if (c >= 0x80 || (Screen_mco > 0
2970 && ScreenLinesC[0][off] != 0))
2971 {
2972 ScreenLines[off] = ' ';
2973 ScreenLinesUC[off] = c;
2974 }
2975 else
2976 {
2977 ScreenLines[off] = c;
2978 ScreenLinesUC[off] = NUL;
2979 }
2980 }
2981#ifdef WIN3264
2982 else if (has_mbyte && c >= 0x80)
2983 {
2984 char_u mb[MB_MAXBYTES+1];
2985 WCHAR wc = c;
2986
2987 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2988 (char*)mb, 2, 0, 0) > 1)
2989 {
2990 ScreenLines[off] = mb[0];
2991 ScreenLines[off + 1] = mb[1];
2992 cell.width = mb_ptr2cells(mb);
2993 }
2994 else
2995 ScreenLines[off] = c;
2996 }
2997#endif
2998 else
2999 ScreenLines[off] = c;
3000 }
3001 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3002
3003 ++pos->col;
3004 ++off;
3005 if (cell.width == 2)
3006 {
3007 if (enc_utf8)
3008 ScreenLinesUC[off] = NUL;
3009
3010 /* don't set the second byte to NUL for a DBCS encoding, it
3011 * has been set above */
3012 if (enc_utf8 || !has_mbyte)
3013 ScreenLines[off] = NUL;
3014
3015 ++pos->col;
3016 ++off;
3017 }
3018 }
3019}
3020
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003021#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003022 static void
3023update_system_term(term_T *term)
3024{
3025 VTermPos pos;
3026 VTermScreen *screen;
3027
3028 if (term->tl_vterm == NULL)
3029 return;
3030 screen = vterm_obtain_screen(term->tl_vterm);
3031
3032 /* Scroll up to make more room for terminal lines if needed. */
3033 while (term->tl_toprow > 0
3034 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3035 {
3036 int save_p_more = p_more;
3037
3038 p_more = FALSE;
3039 msg_row = Rows - 1;
3040 msg_puts((char_u *)"\n");
3041 p_more = save_p_more;
3042 --term->tl_toprow;
3043 }
3044
3045 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3046 && pos.row < Rows; ++pos.row)
3047 {
3048 if (pos.row < term->tl_rows)
3049 {
3050 int max_col = MIN(Columns, term->tl_cols);
3051
3052 term_line2screenline(screen, &pos, max_col);
3053 }
3054 else
3055 pos.col = 0;
3056
3057 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3058 }
3059
3060 term->tl_dirty_row_start = MAX_ROW;
3061 term->tl_dirty_row_end = 0;
3062 update_cursor(term, TRUE);
3063}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003064#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003065
3066/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003067 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3068 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069 * Terminal-Normal mode.
3070 */
3071 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003072term_do_update_window(win_T *wp)
3073{
3074 term_T *term = wp->w_buffer->b_term;
3075
3076 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3077}
3078
3079/*
3080 * Called to update a window that contains an active terminal.
3081 */
3082 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083term_update_window(win_T *wp)
3084{
3085 term_T *term = wp->w_buffer->b_term;
3086 VTerm *vterm;
3087 VTermScreen *screen;
3088 VTermState *state;
3089 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003090 int rows, cols;
3091 int newrows, newcols;
3092 int minsize;
3093 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003094
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 vterm = term->tl_vterm;
3096 screen = vterm_obtain_screen(vterm);
3097 state = vterm_obtain_state(vterm);
3098
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003099 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3100 * SOME_VALID only redraw what was marked dirty. */
3101 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003102 {
3103 term->tl_dirty_row_start = 0;
3104 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003105
3106 if (term->tl_postponed_scroll > 0
3107 && term->tl_postponed_scroll < term->tl_rows / 3)
3108 /* Scrolling is usually faster than redrawing, when there are only
3109 * a few lines to scroll. */
3110 term_scroll_up(term, 0, term->tl_postponed_scroll);
3111 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003112 }
3113
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003114 /*
3115 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003116 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003117 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003118 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119
Bram Moolenaar498c2562018-04-15 23:45:15 +02003120 newrows = 99999;
3121 newcols = 99999;
3122 FOR_ALL_WINDOWS(twp)
3123 {
3124 /* When more than one window shows the same terminal, use the
3125 * smallest size. */
3126 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003128 newrows = MIN(newrows, twp->w_height);
3129 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003131 }
3132 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3133 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3134
3135 if (term->tl_rows != newrows || term->tl_cols != newcols)
3136 {
3137
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138
3139 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003140 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003141 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003142 newrows);
3143 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003144 }
3145
3146 /* The cursor may have been moved when resizing. */
3147 vterm_state_get_cursorpos(state, &pos);
3148 position_cursor(wp, &pos);
3149
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003150 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3151 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003152 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 if (pos.row < term->tl_rows)
3154 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003155 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156
Bram Moolenaar13568252018-03-16 20:46:58 +01003157 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003158 }
3159 else
3160 pos.col = 0;
3161
Bram Moolenaarf118d482018-03-13 13:14:00 +01003162 screen_line(wp->w_winrow + pos.row
3163#ifdef FEAT_MENU
3164 + winbar_height(wp)
3165#endif
3166 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003167 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003168 term->tl_dirty_row_start = MAX_ROW;
3169 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003170}
3171
3172/*
3173 * Return TRUE if "wp" is a terminal window where the job has finished.
3174 */
3175 int
3176term_is_finished(buf_T *buf)
3177{
3178 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3179}
3180
3181/*
3182 * Return TRUE if "wp" is a terminal window where the job has finished or we
3183 * are in Terminal-Normal mode, thus we show the buffer contents.
3184 */
3185 int
3186term_show_buffer(buf_T *buf)
3187{
3188 term_T *term = buf->b_term;
3189
3190 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3191}
3192
3193/*
3194 * The current buffer is going to be changed. If there is terminal
3195 * highlighting remove it now.
3196 */
3197 void
3198term_change_in_curbuf(void)
3199{
3200 term_T *term = curbuf->b_term;
3201
3202 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3203 {
3204 free_scrollback(term);
3205 redraw_buf_later(term->tl_buffer, NOT_VALID);
3206
3207 /* The buffer is now like a normal buffer, it cannot be easily
3208 * abandoned when changed. */
3209 set_string_option_direct((char_u *)"buftype", -1,
3210 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3211 }
3212}
3213
3214/*
3215 * Get the screen attribute for a position in the buffer.
3216 * Use a negative "col" to get the filler background color.
3217 */
3218 int
3219term_get_attr(buf_T *buf, linenr_T lnum, int col)
3220{
3221 term_T *term = buf->b_term;
3222 sb_line_T *line;
3223 cellattr_T *cellattr;
3224
3225 if (lnum > term->tl_scrollback.ga_len)
3226 cellattr = &term->tl_default_color;
3227 else
3228 {
3229 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3230 if (col < 0 || col >= line->sb_cols)
3231 cellattr = &line->sb_fill_attr;
3232 else
3233 cellattr = line->sb_cells + col;
3234 }
3235 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3236}
3237
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238/*
3239 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003240 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003241 */
3242 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003243cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003244{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003245 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003246}
3247
3248/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003249 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003250 */
3251 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003252init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003253{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003254 VTermColor *fg, *bg;
3255 int fgval, bgval;
3256 int id;
3257
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003258 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3259 term->tl_default_color.width = 1;
3260 fg = &term->tl_default_color.fg;
3261 bg = &term->tl_default_color.bg;
3262
3263 /* Vterm uses a default black background. Set it to white when
3264 * 'background' is "light". */
3265 if (*p_bg == 'l')
3266 {
3267 fgval = 0;
3268 bgval = 255;
3269 }
3270 else
3271 {
3272 fgval = 255;
3273 bgval = 0;
3274 }
3275 fg->red = fg->green = fg->blue = fgval;
3276 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003277 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003278
3279 /* The "Terminal" highlight group overrules the defaults. */
3280 id = syn_name2id((char_u *)"Terminal");
3281
Bram Moolenaar46359e12017-11-29 22:33:38 +01003282 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003283#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3284 if (0
3285# ifdef FEAT_GUI
3286 || gui.in_use
3287# endif
3288# ifdef FEAT_TERMGUICOLORS
3289 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003290# ifdef FEAT_VTP
3291 /* Finally get INVALCOLOR on this execution path */
3292 || (!p_tgc && t_colors >= 256)
3293# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003294# endif
3295 )
3296 {
3297 guicolor_T fg_rgb = INVALCOLOR;
3298 guicolor_T bg_rgb = INVALCOLOR;
3299
3300 if (id != 0)
3301 syn_id2colors(id, &fg_rgb, &bg_rgb);
3302
3303# ifdef FEAT_GUI
3304 if (gui.in_use)
3305 {
3306 if (fg_rgb == INVALCOLOR)
3307 fg_rgb = gui.norm_pixel;
3308 if (bg_rgb == INVALCOLOR)
3309 bg_rgb = gui.back_pixel;
3310 }
3311# ifdef FEAT_TERMGUICOLORS
3312 else
3313# endif
3314# endif
3315# ifdef FEAT_TERMGUICOLORS
3316 {
3317 if (fg_rgb == INVALCOLOR)
3318 fg_rgb = cterm_normal_fg_gui_color;
3319 if (bg_rgb == INVALCOLOR)
3320 bg_rgb = cterm_normal_bg_gui_color;
3321 }
3322# endif
3323 if (fg_rgb != INVALCOLOR)
3324 {
3325 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3326
3327 fg->red = (unsigned)(rgb >> 16);
3328 fg->green = (unsigned)(rgb >> 8) & 255;
3329 fg->blue = (unsigned)rgb & 255;
3330 }
3331 if (bg_rgb != INVALCOLOR)
3332 {
3333 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3334
3335 bg->red = (unsigned)(rgb >> 16);
3336 bg->green = (unsigned)(rgb >> 8) & 255;
3337 bg->blue = (unsigned)rgb & 255;
3338 }
3339 }
3340 else
3341#endif
3342 if (id != 0 && t_colors >= 16)
3343 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003344 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003345 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003346 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003347 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003349 else
3350 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003351#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003353#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354
3355 /* In an MS-Windows console we know the normal colors. */
3356 if (cterm_normal_fg_color > 0)
3357 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003358 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003359# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003360 tmp = fg->red;
3361 fg->red = fg->blue;
3362 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003363# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003364 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003365# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003366 else
3367 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003368# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003369
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003370 if (cterm_normal_bg_color > 0)
3371 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003372 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003373# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003374 tmp = bg->red;
3375 bg->red = bg->blue;
3376 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003377# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003378 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003379# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003380 else
3381 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003382# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003384}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003385
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003386#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3387/*
3388 * Set the 16 ANSI colors from array of RGB values
3389 */
3390 static void
3391set_vterm_palette(VTerm *vterm, long_u *rgb)
3392{
3393 int index = 0;
3394 VTermState *state = vterm_obtain_state(vterm);
3395 for (; index < 16; index++)
3396 {
3397 VTermColor color;
3398 color.red = (unsigned)(rgb[index] >> 16);
3399 color.green = (unsigned)(rgb[index] >> 8) & 255;
3400 color.blue = (unsigned)rgb[index] & 255;
3401 vterm_state_set_palette_color(state, index, &color);
3402 }
3403}
3404
3405/*
3406 * Set the ANSI color palette from a list of colors
3407 */
3408 static int
3409set_ansi_colors_list(VTerm *vterm, list_T *list)
3410{
3411 int n = 0;
3412 long_u rgb[16];
3413 listitem_T *li = list->lv_first;
3414
3415 for (; li != NULL && n < 16; li = li->li_next, n++)
3416 {
3417 char_u *color_name;
3418 guicolor_T guicolor;
3419
3420 color_name = get_tv_string_chk(&li->li_tv);
3421 if (color_name == NULL)
3422 return FAIL;
3423
3424 guicolor = GUI_GET_COLOR(color_name);
3425 if (guicolor == INVALCOLOR)
3426 return FAIL;
3427
3428 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3429 }
3430
3431 if (n != 16 || li != NULL)
3432 return FAIL;
3433
3434 set_vterm_palette(vterm, rgb);
3435
3436 return OK;
3437}
3438
3439/*
3440 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3441 */
3442 static void
3443init_vterm_ansi_colors(VTerm *vterm)
3444{
3445 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3446
3447 if (var != NULL
3448 && (var->di_tv.v_type != VAR_LIST
3449 || var->di_tv.vval.v_list == NULL
3450 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3451 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3452}
3453#endif
3454
Bram Moolenaar52acb112018-03-18 19:20:22 +01003455/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003456 * Handles a "drop" command from the job in the terminal.
3457 * "item" is the file name, "item->li_next" may have options.
3458 */
3459 static void
3460handle_drop_command(listitem_T *item)
3461{
3462 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003463 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003464 int bufnr;
3465 win_T *wp;
3466 tabpage_T *tp;
3467 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003468 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003469
3470 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3471 FOR_ALL_TAB_WINDOWS(tp, wp)
3472 {
3473 if (wp->w_buffer->b_fnum == bufnr)
3474 {
3475 /* buffer is in a window already, go there */
3476 goto_tabpage_win(tp, wp);
3477 return;
3478 }
3479 }
3480
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003481 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003482
3483 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3484 && opt_item->li_tv.vval.v_dict != NULL)
3485 {
3486 dict_T *dict = opt_item->li_tv.vval.v_dict;
3487 char_u *p;
3488
3489 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3490 if (p == NULL)
3491 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3492 if (p != NULL)
3493 {
3494 if (check_ff_value(p) == FAIL)
3495 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3496 else
3497 ea.force_ff = *p;
3498 }
3499 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3500 if (p == NULL)
3501 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3502 if (p != NULL)
3503 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003504 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003505 if (ea.cmd != NULL)
3506 {
3507 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3508 ea.force_enc = 11;
3509 tofree = ea.cmd;
3510 }
3511 }
3512
3513 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3514 if (p != NULL)
3515 get_bad_opt(p, &ea);
3516
3517 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3518 ea.force_bin = FORCE_BIN;
3519 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3520 ea.force_bin = FORCE_BIN;
3521 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3522 ea.force_bin = FORCE_NOBIN;
3523 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3524 ea.force_bin = FORCE_NOBIN;
3525 }
3526
3527 /* open in new window, like ":split fname" */
3528 if (ea.cmd == NULL)
3529 ea.cmd = (char_u *)"split";
3530 ea.arg = fname;
3531 ea.cmdidx = CMD_split;
3532 ex_splitview(&ea);
3533
3534 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003535}
3536
3537/*
3538 * Handles a function call from the job running in a terminal.
3539 * "item" is the function name, "item->li_next" has the arguments.
3540 */
3541 static void
3542handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3543{
3544 char_u *func;
3545 typval_T argvars[2];
3546 typval_T rettv;
3547 int doesrange;
3548
3549 if (item->li_next == NULL)
3550 {
3551 ch_log(channel, "Missing function arguments for call");
3552 return;
3553 }
3554 func = get_tv_string(&item->li_tv);
3555
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003556 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003557 {
3558 ch_log(channel, "Invalid function name: %s", func);
3559 return;
3560 }
3561
3562 argvars[0].v_type = VAR_NUMBER;
3563 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3564 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003565 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003566 2, argvars, /* argv_func */ NULL,
3567 /* firstline */ 1, /* lastline */ 1,
3568 &doesrange, /* evaluate */ TRUE,
3569 /* partial */ NULL, /* selfdict */ NULL) == OK)
3570 {
3571 clear_tv(&rettv);
3572 ch_log(channel, "Function %s called", func);
3573 }
3574 else
3575 ch_log(channel, "Calling function %s failed", func);
3576}
3577
3578/*
3579 * Called by libvterm when it cannot recognize an OSC sequence.
3580 * We recognize a terminal API command.
3581 */
3582 static int
3583parse_osc(const char *command, size_t cmdlen, void *user)
3584{
3585 term_T *term = (term_T *)user;
3586 js_read_T reader;
3587 typval_T tv;
3588 channel_T *channel = term->tl_job == NULL ? NULL
3589 : term->tl_job->jv_channel;
3590
3591 /* We recognize only OSC 5 1 ; {command} */
3592 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3593 return 0; /* not handled */
3594
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003595 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003596 if (reader.js_buf == NULL)
3597 return 1;
3598 reader.js_fill = NULL;
3599 reader.js_used = 0;
3600 if (json_decode(&reader, &tv, 0) == OK
3601 && tv.v_type == VAR_LIST
3602 && tv.vval.v_list != NULL)
3603 {
3604 listitem_T *item = tv.vval.v_list->lv_first;
3605
3606 if (item == NULL)
3607 ch_log(channel, "Missing command");
3608 else
3609 {
3610 char_u *cmd = get_tv_string(&item->li_tv);
3611
Bram Moolenaara997b452018-04-17 23:24:06 +02003612 /* Make sure an invoked command doesn't delete the buffer (and the
3613 * terminal) under our fingers. */
3614 ++term->tl_buffer->b_locked;
3615
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003616 item = item->li_next;
3617 if (item == NULL)
3618 ch_log(channel, "Missing argument for %s", cmd);
3619 else if (STRCMP(cmd, "drop") == 0)
3620 handle_drop_command(item);
3621 else if (STRCMP(cmd, "call") == 0)
3622 handle_call_command(term, channel, item);
3623 else
3624 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003625 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003626 }
3627 }
3628 else
3629 ch_log(channel, "Invalid JSON received");
3630
3631 vim_free(reader.js_buf);
3632 clear_tv(&tv);
3633 return 1;
3634}
3635
3636static VTermParserCallbacks parser_fallbacks = {
3637 NULL, /* text */
3638 NULL, /* control */
3639 NULL, /* escape */
3640 NULL, /* csi */
3641 parse_osc, /* osc */
3642 NULL, /* dcs */
3643 NULL /* resize */
3644};
3645
3646/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003647 * Use Vim's allocation functions for vterm so profiling works.
3648 */
3649 static void *
3650vterm_malloc(size_t size, void *data UNUSED)
3651{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003652 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003653}
3654
3655 static void
3656vterm_memfree(void *ptr, void *data UNUSED)
3657{
3658 vim_free(ptr);
3659}
3660
3661static VTermAllocatorFunctions vterm_allocator = {
3662 &vterm_malloc,
3663 &vterm_memfree
3664};
3665
3666/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003667 * Create a new vterm and initialize it.
3668 */
3669 static void
3670create_vterm(term_T *term, int rows, int cols)
3671{
3672 VTerm *vterm;
3673 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003674 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003675 VTermValue value;
3676
Bram Moolenaar756ef112018-04-10 12:04:27 +02003677 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003678 term->tl_vterm = vterm;
3679 screen = vterm_obtain_screen(vterm);
3680 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3681 /* TODO: depends on 'encoding'. */
3682 vterm_set_utf8(vterm, 1);
3683
3684 init_default_colors(term);
3685
3686 vterm_state_set_default_colors(
3687 vterm_obtain_state(vterm),
3688 &term->tl_default_color.fg,
3689 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003690
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003691 if (t_colors >= 16)
3692 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003694 /* Required to initialize most things. */
3695 vterm_screen_reset(screen, 1 /* hard */);
3696
3697 /* Allow using alternate screen. */
3698 vterm_screen_enable_altscreen(screen, 1);
3699
3700 /* For unix do not use a blinking cursor. In an xterm this causes the
3701 * cursor to blink if it's blinking in the xterm.
3702 * For Windows we respect the system wide setting. */
3703#ifdef WIN3264
3704 if (GetCaretBlinkTime() == INFINITE)
3705 value.boolean = 0;
3706 else
3707 value.boolean = 1;
3708#else
3709 value.boolean = 0;
3710#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003711 state = vterm_obtain_state(vterm);
3712 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3713 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003714}
3715
3716/*
3717 * Return the text to show for the buffer name and status.
3718 */
3719 char_u *
3720term_get_status_text(term_T *term)
3721{
3722 if (term->tl_status_text == NULL)
3723 {
3724 char_u *txt;
3725 size_t len;
3726
3727 if (term->tl_normal_mode)
3728 {
3729 if (term_job_running(term))
3730 txt = (char_u *)_("Terminal");
3731 else
3732 txt = (char_u *)_("Terminal-finished");
3733 }
3734 else if (term->tl_title != NULL)
3735 txt = term->tl_title;
3736 else if (term_none_open(term))
3737 txt = (char_u *)_("active");
3738 else if (term_job_running(term))
3739 txt = (char_u *)_("running");
3740 else
3741 txt = (char_u *)_("finished");
3742 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3743 term->tl_status_text = alloc((int)len);
3744 if (term->tl_status_text != NULL)
3745 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3746 term->tl_buffer->b_fname, txt);
3747 }
3748 return term->tl_status_text;
3749}
3750
3751/*
3752 * Mark references in jobs of terminals.
3753 */
3754 int
3755set_ref_in_term(int copyID)
3756{
3757 int abort = FALSE;
3758 term_T *term;
3759 typval_T tv;
3760
3761 for (term = first_term; term != NULL; term = term->tl_next)
3762 if (term->tl_job != NULL)
3763 {
3764 tv.v_type = VAR_JOB;
3765 tv.vval.v_job = term->tl_job;
3766 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3767 }
3768 return abort;
3769}
3770
3771/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003772 * Cache "Terminal" highlight group colors.
3773 */
3774 void
3775set_terminal_default_colors(int cterm_fg, int cterm_bg)
3776{
3777 term_default_cterm_fg = cterm_fg - 1;
3778 term_default_cterm_bg = cterm_bg - 1;
3779}
3780
3781/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003782 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003783 * Returns NULL when the buffer is not for a terminal window and logs a message
3784 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003785 */
3786 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003787term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003788{
3789 buf_T *buf;
3790
3791 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3792 ++emsg_off;
3793 buf = get_buf_tv(&argvars[0], FALSE);
3794 --emsg_off;
3795 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003796 {
3797 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003798 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003799 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003800 return buf;
3801}
3802
Bram Moolenaard96ff162018-02-18 22:13:29 +01003803 static int
3804same_color(VTermColor *a, VTermColor *b)
3805{
3806 return a->red == b->red
3807 && a->green == b->green
3808 && a->blue == b->blue
3809 && a->ansi_index == b->ansi_index;
3810}
3811
3812 static void
3813dump_term_color(FILE *fd, VTermColor *color)
3814{
3815 fprintf(fd, "%02x%02x%02x%d",
3816 (int)color->red, (int)color->green, (int)color->blue,
3817 (int)color->ansi_index);
3818}
3819
3820/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003821 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003822 *
3823 * Each screen cell in full is:
3824 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3825 * {characters} is a space for an empty cell
3826 * For a double-width character "+" is changed to "*" and the next cell is
3827 * skipped.
3828 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3829 * when "&" use the same as the previous cell.
3830 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3831 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3832 * {color-idx} is a number from 0 to 255
3833 *
3834 * Screen cell with same width, attributes and color as the previous one:
3835 * |{characters}
3836 *
3837 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3838 *
3839 * Repeating the previous screen cell:
3840 * @{count}
3841 */
3842 void
3843f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3844{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003845 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003846 term_T *term;
3847 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003848 int max_height = 0;
3849 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003850 stat_T st;
3851 FILE *fd;
3852 VTermPos pos;
3853 VTermScreen *screen;
3854 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003855 VTermState *state;
3856 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003857
3858 if (check_restricted() || check_secure())
3859 return;
3860 if (buf == NULL)
3861 return;
3862 term = buf->b_term;
3863
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003864 if (argvars[2].v_type != VAR_UNKNOWN)
3865 {
3866 dict_T *d;
3867
3868 if (argvars[2].v_type != VAR_DICT)
3869 {
3870 EMSG(_(e_dictreq));
3871 return;
3872 }
3873 d = argvars[2].vval.v_dict;
3874 if (d != NULL)
3875 {
3876 max_height = get_dict_number(d, (char_u *)"rows");
3877 max_width = get_dict_number(d, (char_u *)"columns");
3878 }
3879 }
3880
Bram Moolenaard96ff162018-02-18 22:13:29 +01003881 fname = get_tv_string_chk(&argvars[1]);
3882 if (fname == NULL)
3883 return;
3884 if (mch_stat((char *)fname, &st) >= 0)
3885 {
3886 EMSG2(_("E953: File exists: %s"), fname);
3887 return;
3888 }
3889
Bram Moolenaard96ff162018-02-18 22:13:29 +01003890 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3891 {
3892 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3893 return;
3894 }
3895
3896 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3897
3898 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003899 state = vterm_obtain_state(term->tl_vterm);
3900 vterm_state_get_cursorpos(state, &cursor_pos);
3901
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003902 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3903 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003904 {
3905 int repeat = 0;
3906
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003907 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3908 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003909 {
3910 VTermScreenCell cell;
3911 int same_attr;
3912 int same_chars = TRUE;
3913 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003914 int is_cursor_pos = (pos.col == cursor_pos.col
3915 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003916
3917 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3918 vim_memset(&cell, 0, sizeof(cell));
3919
3920 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3921 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003922 int c = cell.chars[i];
3923 int pc = prev_cell.chars[i];
3924
3925 /* For the first character NUL is the same as space. */
3926 if (i == 0)
3927 {
3928 c = (c == NUL) ? ' ' : c;
3929 pc = (pc == NUL) ? ' ' : pc;
3930 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003931 if (cell.chars[i] != prev_cell.chars[i])
3932 same_chars = FALSE;
3933 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3934 break;
3935 }
3936 same_attr = vtermAttr2hl(cell.attrs)
3937 == vtermAttr2hl(prev_cell.attrs)
3938 && same_color(&cell.fg, &prev_cell.fg)
3939 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003940 if (same_chars && cell.width == prev_cell.width && same_attr
3941 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003942 {
3943 ++repeat;
3944 }
3945 else
3946 {
3947 if (repeat > 0)
3948 {
3949 fprintf(fd, "@%d", repeat);
3950 repeat = 0;
3951 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003952 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003953
3954 if (cell.chars[0] == NUL)
3955 fputs(" ", fd);
3956 else
3957 {
3958 char_u charbuf[10];
3959 int len;
3960
3961 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3962 && cell.chars[i] != NUL; ++i)
3963 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003964 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003965 fwrite(charbuf, len, 1, fd);
3966 }
3967 }
3968
3969 /* When only the characters differ we don't write anything, the
3970 * following "|", "@" or NL will indicate using the same
3971 * attributes. */
3972 if (cell.width != prev_cell.width || !same_attr)
3973 {
3974 if (cell.width == 2)
3975 {
3976 fputs("*", fd);
3977 ++pos.col;
3978 }
3979 else
3980 fputs("+", fd);
3981
3982 if (same_attr)
3983 {
3984 fputs("&", fd);
3985 }
3986 else
3987 {
3988 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3989 if (same_color(&cell.fg, &prev_cell.fg))
3990 fputs("&", fd);
3991 else
3992 {
3993 fputs("#", fd);
3994 dump_term_color(fd, &cell.fg);
3995 }
3996 if (same_color(&cell.bg, &prev_cell.bg))
3997 fputs("&", fd);
3998 else
3999 {
4000 fputs("#", fd);
4001 dump_term_color(fd, &cell.bg);
4002 }
4003 }
4004 }
4005
4006 prev_cell = cell;
4007 }
4008 }
4009 if (repeat > 0)
4010 fprintf(fd, "@%d", repeat);
4011 fputs("\n", fd);
4012 }
4013
4014 fclose(fd);
4015}
4016
4017/*
4018 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4019 */
4020 static void
4021dump_is_corrupt(garray_T *gap)
4022{
4023 ga_concat(gap, (char_u *)"CORRUPT");
4024}
4025
4026 static void
4027append_cell(garray_T *gap, cellattr_T *cell)
4028{
4029 if (ga_grow(gap, 1) == OK)
4030 {
4031 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4032 ++gap->ga_len;
4033 }
4034}
4035
4036/*
4037 * Read the dump file from "fd" and append lines to the current buffer.
4038 * Return the cell width of the longest line.
4039 */
4040 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004041read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004042{
4043 int c;
4044 garray_T ga_text;
4045 garray_T ga_cell;
4046 char_u *prev_char = NULL;
4047 int attr = 0;
4048 cellattr_T cell;
4049 term_T *term = curbuf->b_term;
4050 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004051 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004052
4053 ga_init2(&ga_text, 1, 90);
4054 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4055 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004056 cursor_pos->row = -1;
4057 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004058
4059 c = fgetc(fd);
4060 for (;;)
4061 {
4062 if (c == EOF)
4063 break;
4064 if (c == '\n')
4065 {
4066 /* End of a line: append it to the buffer. */
4067 if (ga_text.ga_data == NULL)
4068 dump_is_corrupt(&ga_text);
4069 if (ga_grow(&term->tl_scrollback, 1) == OK)
4070 {
4071 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4072 + term->tl_scrollback.ga_len;
4073
4074 if (max_cells < ga_cell.ga_len)
4075 max_cells = ga_cell.ga_len;
4076 line->sb_cols = ga_cell.ga_len;
4077 line->sb_cells = ga_cell.ga_data;
4078 line->sb_fill_attr = term->tl_default_color;
4079 ++term->tl_scrollback.ga_len;
4080 ga_init(&ga_cell);
4081
4082 ga_append(&ga_text, NUL);
4083 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4084 ga_text.ga_len, FALSE);
4085 }
4086 else
4087 ga_clear(&ga_cell);
4088 ga_text.ga_len = 0;
4089
4090 c = fgetc(fd);
4091 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004092 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004093 {
4094 int prev_len = ga_text.ga_len;
4095
Bram Moolenaar9271d052018-02-25 21:39:46 +01004096 if (c == '>')
4097 {
4098 if (cursor_pos->row != -1)
4099 dump_is_corrupt(&ga_text); /* duplicate cursor */
4100 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4101 cursor_pos->col = ga_cell.ga_len;
4102 }
4103
Bram Moolenaard96ff162018-02-18 22:13:29 +01004104 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4105 c = fgetc(fd);
4106 if (c != EOF)
4107 ga_append(&ga_text, c);
4108 for (;;)
4109 {
4110 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004111 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004112 || c == EOF || c == '\n')
4113 break;
4114 ga_append(&ga_text, c);
4115 }
4116
4117 /* save the character for repeating it */
4118 vim_free(prev_char);
4119 if (ga_text.ga_data != NULL)
4120 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4121 ga_text.ga_len - prev_len);
4122
Bram Moolenaar9271d052018-02-25 21:39:46 +01004123 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004124 {
4125 /* use all attributes from previous cell */
4126 }
4127 else if (c == '+' || c == '*')
4128 {
4129 int is_bg;
4130
4131 cell.width = c == '+' ? 1 : 2;
4132
4133 c = fgetc(fd);
4134 if (c == '&')
4135 {
4136 /* use same attr as previous cell */
4137 c = fgetc(fd);
4138 }
4139 else if (isdigit(c))
4140 {
4141 /* get the decimal attribute */
4142 attr = 0;
4143 while (isdigit(c))
4144 {
4145 attr = attr * 10 + (c - '0');
4146 c = fgetc(fd);
4147 }
4148 hl2vtermAttr(attr, &cell);
4149 }
4150 else
4151 dump_is_corrupt(&ga_text);
4152
4153 /* is_bg == 0: fg, is_bg == 1: bg */
4154 for (is_bg = 0; is_bg <= 1; ++is_bg)
4155 {
4156 if (c == '&')
4157 {
4158 /* use same color as previous cell */
4159 c = fgetc(fd);
4160 }
4161 else if (c == '#')
4162 {
4163 int red, green, blue, index = 0;
4164
4165 c = fgetc(fd);
4166 red = hex2nr(c);
4167 c = fgetc(fd);
4168 red = (red << 4) + hex2nr(c);
4169 c = fgetc(fd);
4170 green = hex2nr(c);
4171 c = fgetc(fd);
4172 green = (green << 4) + hex2nr(c);
4173 c = fgetc(fd);
4174 blue = hex2nr(c);
4175 c = fgetc(fd);
4176 blue = (blue << 4) + hex2nr(c);
4177 c = fgetc(fd);
4178 if (!isdigit(c))
4179 dump_is_corrupt(&ga_text);
4180 while (isdigit(c))
4181 {
4182 index = index * 10 + (c - '0');
4183 c = fgetc(fd);
4184 }
4185
4186 if (is_bg)
4187 {
4188 cell.bg.red = red;
4189 cell.bg.green = green;
4190 cell.bg.blue = blue;
4191 cell.bg.ansi_index = index;
4192 }
4193 else
4194 {
4195 cell.fg.red = red;
4196 cell.fg.green = green;
4197 cell.fg.blue = blue;
4198 cell.fg.ansi_index = index;
4199 }
4200 }
4201 else
4202 dump_is_corrupt(&ga_text);
4203 }
4204 }
4205 else
4206 dump_is_corrupt(&ga_text);
4207
4208 append_cell(&ga_cell, &cell);
4209 }
4210 else if (c == '@')
4211 {
4212 if (prev_char == NULL)
4213 dump_is_corrupt(&ga_text);
4214 else
4215 {
4216 int count = 0;
4217
4218 /* repeat previous character, get the count */
4219 for (;;)
4220 {
4221 c = fgetc(fd);
4222 if (!isdigit(c))
4223 break;
4224 count = count * 10 + (c - '0');
4225 }
4226
4227 while (count-- > 0)
4228 {
4229 ga_concat(&ga_text, prev_char);
4230 append_cell(&ga_cell, &cell);
4231 }
4232 }
4233 }
4234 else
4235 {
4236 dump_is_corrupt(&ga_text);
4237 c = fgetc(fd);
4238 }
4239 }
4240
4241 if (ga_text.ga_len > 0)
4242 {
4243 /* trailing characters after last NL */
4244 dump_is_corrupt(&ga_text);
4245 ga_append(&ga_text, NUL);
4246 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4247 ga_text.ga_len, FALSE);
4248 }
4249
4250 ga_clear(&ga_text);
4251 vim_free(prev_char);
4252
4253 return max_cells;
4254}
4255
4256/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004257 * Return an allocated string with at least "text_width" "=" characters and
4258 * "fname" inserted in the middle.
4259 */
4260 static char_u *
4261get_separator(int text_width, char_u *fname)
4262{
4263 int width = MAX(text_width, curwin->w_width);
4264 char_u *textline;
4265 int fname_size;
4266 char_u *p = fname;
4267 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004268 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004269
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004270 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004271 if (textline == NULL)
4272 return NULL;
4273
4274 fname_size = vim_strsize(fname);
4275 if (fname_size < width - 8)
4276 {
4277 /* enough room, don't use the full window width */
4278 width = MAX(text_width, fname_size + 8);
4279 }
4280 else if (fname_size > width - 8)
4281 {
4282 /* full name doesn't fit, use only the tail */
4283 p = gettail(fname);
4284 fname_size = vim_strsize(p);
4285 }
4286 /* skip characters until the name fits */
4287 while (fname_size > width - 8)
4288 {
4289 p += (*mb_ptr2len)(p);
4290 fname_size = vim_strsize(p);
4291 }
4292
4293 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4294 textline[i] = '=';
4295 textline[i++] = ' ';
4296
4297 STRCPY(textline + i, p);
4298 off = STRLEN(textline);
4299 textline[off] = ' ';
4300 for (i = 1; i < (width - fname_size) / 2; ++i)
4301 textline[off + i] = '=';
4302 textline[off + i] = NUL;
4303
4304 return textline;
4305}
4306
4307/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004308 * Common for "term_dumpdiff()" and "term_dumpload()".
4309 */
4310 static void
4311term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4312{
4313 jobopt_T opt;
4314 buf_T *buf;
4315 char_u buf1[NUMBUFLEN];
4316 char_u buf2[NUMBUFLEN];
4317 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004318 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004319 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004321 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004322 char_u *textline = NULL;
4323
4324 /* First open the files. If this fails bail out. */
4325 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4326 if (do_diff)
4327 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4328 if (fname1 == NULL || (do_diff && fname2 == NULL))
4329 {
4330 EMSG(_(e_invarg));
4331 return;
4332 }
4333 fd1 = mch_fopen((char *)fname1, READBIN);
4334 if (fd1 == NULL)
4335 {
4336 EMSG2(_(e_notread), fname1);
4337 return;
4338 }
4339 if (do_diff)
4340 {
4341 fd2 = mch_fopen((char *)fname2, READBIN);
4342 if (fd2 == NULL)
4343 {
4344 fclose(fd1);
4345 EMSG2(_(e_notread), fname2);
4346 return;
4347 }
4348 }
4349
4350 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004351 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4352 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4353 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4354 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4355 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004356
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004357 if (opt.jo_term_name == NULL)
4358 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004359 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004360
Bram Moolenaarb571c632018-03-21 22:27:59 +01004361 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004362 if (fname_tofree != NULL)
4363 {
4364 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4365 opt.jo_term_name = fname_tofree;
4366 }
4367 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004368
Bram Moolenaar13568252018-03-16 20:46:58 +01004369 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004370 if (buf != NULL && buf->b_term != NULL)
4371 {
4372 int i;
4373 linenr_T bot_lnum;
4374 linenr_T lnum;
4375 term_T *term = buf->b_term;
4376 int width;
4377 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004378 VTermPos cursor_pos1;
4379 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004380
Bram Moolenaar52acb112018-03-18 19:20:22 +01004381 init_default_colors(term);
4382
Bram Moolenaard96ff162018-02-18 22:13:29 +01004383 rettv->vval.v_number = buf->b_fnum;
4384
4385 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004386 width = read_dump_file(fd1, &cursor_pos1);
4387
4388 /* position the cursor */
4389 if (cursor_pos1.row >= 0)
4390 {
4391 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4392 coladvance(cursor_pos1.col);
4393 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004394
4395 /* Delete the empty line that was in the empty buffer. */
4396 ml_delete(1, FALSE);
4397
4398 /* For term_dumpload() we are done here. */
4399 if (!do_diff)
4400 goto theend;
4401
4402 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4403
Bram Moolenaar4a696342018-04-05 18:45:26 +02004404 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004405 if (textline == NULL)
4406 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004407 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4408 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4409 vim_free(textline);
4410
4411 textline = get_separator(width, fname2);
4412 if (textline == NULL)
4413 goto theend;
4414 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4415 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004416 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004417
4418 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004419 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004420 if (width2 > width)
4421 {
4422 vim_free(textline);
4423 textline = alloc(width2 + 1);
4424 if (textline == NULL)
4425 goto theend;
4426 width = width2;
4427 textline[width] = NUL;
4428 }
4429 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4430
4431 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4432 {
4433 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4434 {
4435 /* bottom part has fewer rows, fill with "-" */
4436 for (i = 0; i < width; ++i)
4437 textline[i] = '-';
4438 }
4439 else
4440 {
4441 char_u *line1;
4442 char_u *line2;
4443 char_u *p1;
4444 char_u *p2;
4445 int col;
4446 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4447 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4448 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4449 ->sb_cells;
4450
4451 /* Make a copy, getting the second line will invalidate it. */
4452 line1 = vim_strsave(ml_get(lnum));
4453 if (line1 == NULL)
4454 break;
4455 p1 = line1;
4456
4457 line2 = ml_get(lnum + bot_lnum);
4458 p2 = line2;
4459 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4460 {
4461 int len1 = utfc_ptr2len(p1);
4462 int len2 = utfc_ptr2len(p2);
4463
4464 textline[col] = ' ';
4465 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004466 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004467 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004468 else if (lnum == cursor_pos1.row + 1
4469 && col == cursor_pos1.col
4470 && (cursor_pos1.row != cursor_pos2.row
4471 || cursor_pos1.col != cursor_pos2.col))
4472 /* cursor in first but not in second */
4473 textline[col] = '>';
4474 else if (lnum == cursor_pos2.row + 1
4475 && col == cursor_pos2.col
4476 && (cursor_pos1.row != cursor_pos2.row
4477 || cursor_pos1.col != cursor_pos2.col))
4478 /* cursor in second but not in first */
4479 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004480 else if (cellattr1 != NULL && cellattr2 != NULL)
4481 {
4482 if ((cellattr1 + col)->width
4483 != (cellattr2 + col)->width)
4484 textline[col] = 'w';
4485 else if (!same_color(&(cellattr1 + col)->fg,
4486 &(cellattr2 + col)->fg))
4487 textline[col] = 'f';
4488 else if (!same_color(&(cellattr1 + col)->bg,
4489 &(cellattr2 + col)->bg))
4490 textline[col] = 'b';
4491 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4492 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4493 textline[col] = 'a';
4494 }
4495 p1 += len1;
4496 p2 += len2;
4497 /* TODO: handle different width */
4498 }
4499 vim_free(line1);
4500
4501 while (col < width)
4502 {
4503 if (*p1 == NUL && *p2 == NUL)
4504 textline[col] = '?';
4505 else if (*p1 == NUL)
4506 {
4507 textline[col] = '+';
4508 p2 += utfc_ptr2len(p2);
4509 }
4510 else
4511 {
4512 textline[col] = '-';
4513 p1 += utfc_ptr2len(p1);
4514 }
4515 ++col;
4516 }
4517 }
4518 if (add_empty_scrollback(term, &term->tl_default_color,
4519 term->tl_top_diff_rows) == OK)
4520 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4521 ++bot_lnum;
4522 }
4523
4524 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4525 {
4526 /* bottom part has more rows, fill with "+" */
4527 for (i = 0; i < width; ++i)
4528 textline[i] = '+';
4529 if (add_empty_scrollback(term, &term->tl_default_color,
4530 term->tl_top_diff_rows) == OK)
4531 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4532 ++lnum;
4533 ++bot_lnum;
4534 }
4535
4536 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004537
4538 /* looks better without wrapping */
4539 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004540 }
4541
4542theend:
4543 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004544 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004545 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004546 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004547 fclose(fd2);
4548}
4549
4550/*
4551 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4552 * bottom files.
4553 * Return FAIL when this is not possible.
4554 */
4555 int
4556term_swap_diff()
4557{
4558 term_T *term = curbuf->b_term;
4559 linenr_T line_count;
4560 linenr_T top_rows;
4561 linenr_T bot_rows;
4562 linenr_T bot_start;
4563 linenr_T lnum;
4564 char_u *p;
4565 sb_line_T *sb_line;
4566
4567 if (term == NULL
4568 || !term_is_finished(curbuf)
4569 || term->tl_top_diff_rows == 0
4570 || term->tl_scrollback.ga_len == 0)
4571 return FAIL;
4572
4573 line_count = curbuf->b_ml.ml_line_count;
4574 top_rows = term->tl_top_diff_rows;
4575 bot_rows = term->tl_bot_diff_rows;
4576 bot_start = line_count - bot_rows;
4577 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4578
4579 /* move lines from top to above the bottom part */
4580 for (lnum = 1; lnum <= top_rows; ++lnum)
4581 {
4582 p = vim_strsave(ml_get(1));
4583 if (p == NULL)
4584 return OK;
4585 ml_append(bot_start, p, 0, FALSE);
4586 ml_delete(1, FALSE);
4587 vim_free(p);
4588 }
4589
4590 /* move lines from bottom to the top */
4591 for (lnum = 1; lnum <= bot_rows; ++lnum)
4592 {
4593 p = vim_strsave(ml_get(bot_start + lnum));
4594 if (p == NULL)
4595 return OK;
4596 ml_delete(bot_start + lnum, FALSE);
4597 ml_append(lnum - 1, p, 0, FALSE);
4598 vim_free(p);
4599 }
4600
4601 if (top_rows == bot_rows)
4602 {
4603 /* rows counts are equal, can swap cell properties */
4604 for (lnum = 0; lnum < top_rows; ++lnum)
4605 {
4606 sb_line_T temp;
4607
4608 temp = *(sb_line + lnum);
4609 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4610 *(sb_line + bot_start + lnum) = temp;
4611 }
4612 }
4613 else
4614 {
4615 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4616 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4617
4618 /* need to copy cell properties into temp memory */
4619 if (temp != NULL)
4620 {
4621 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4622 mch_memmove(term->tl_scrollback.ga_data,
4623 temp + bot_start,
4624 sizeof(sb_line_T) * bot_rows);
4625 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4626 temp + top_rows,
4627 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4628 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4629 + line_count - top_rows,
4630 temp,
4631 sizeof(sb_line_T) * top_rows);
4632 vim_free(temp);
4633 }
4634 }
4635
4636 term->tl_top_diff_rows = bot_rows;
4637 term->tl_bot_diff_rows = top_rows;
4638
4639 update_screen(NOT_VALID);
4640 return OK;
4641}
4642
4643/*
4644 * "term_dumpdiff(filename, filename, options)" function
4645 */
4646 void
4647f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4648{
4649 term_load_dump(argvars, rettv, TRUE);
4650}
4651
4652/*
4653 * "term_dumpload(filename, options)" function
4654 */
4655 void
4656f_term_dumpload(typval_T *argvars, typval_T *rettv)
4657{
4658 term_load_dump(argvars, rettv, FALSE);
4659}
4660
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004661/*
4662 * "term_getaltscreen(buf)" function
4663 */
4664 void
4665f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4666{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004667 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004668
4669 if (buf == NULL)
4670 return;
4671 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4672}
4673
4674/*
4675 * "term_getattr(attr, name)" function
4676 */
4677 void
4678f_term_getattr(typval_T *argvars, typval_T *rettv)
4679{
4680 int attr;
4681 size_t i;
4682 char_u *name;
4683
4684 static struct {
4685 char *name;
4686 int attr;
4687 } attrs[] = {
4688 {"bold", HL_BOLD},
4689 {"italic", HL_ITALIC},
4690 {"underline", HL_UNDERLINE},
4691 {"strike", HL_STRIKETHROUGH},
4692 {"reverse", HL_INVERSE},
4693 };
4694
4695 attr = get_tv_number(&argvars[0]);
4696 name = get_tv_string_chk(&argvars[1]);
4697 if (name == NULL)
4698 return;
4699
4700 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4701 if (STRCMP(name, attrs[i].name) == 0)
4702 {
4703 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4704 break;
4705 }
4706}
4707
4708/*
4709 * "term_getcursor(buf)" function
4710 */
4711 void
4712f_term_getcursor(typval_T *argvars, typval_T *rettv)
4713{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004714 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004715 term_T *term;
4716 list_T *l;
4717 dict_T *d;
4718
4719 if (rettv_list_alloc(rettv) == FAIL)
4720 return;
4721 if (buf == NULL)
4722 return;
4723 term = buf->b_term;
4724
4725 l = rettv->vval.v_list;
4726 list_append_number(l, term->tl_cursor_pos.row + 1);
4727 list_append_number(l, term->tl_cursor_pos.col + 1);
4728
4729 d = dict_alloc();
4730 if (d != NULL)
4731 {
4732 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4733 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4734 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4735 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4736 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4737 ? (char_u *)"" : term->tl_cursor_color);
4738 list_append_dict(l, d);
4739 }
4740}
4741
4742/*
4743 * "term_getjob(buf)" function
4744 */
4745 void
4746f_term_getjob(typval_T *argvars, typval_T *rettv)
4747{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004748 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004749
4750 rettv->v_type = VAR_JOB;
4751 rettv->vval.v_job = NULL;
4752 if (buf == NULL)
4753 return;
4754
4755 rettv->vval.v_job = buf->b_term->tl_job;
4756 if (rettv->vval.v_job != NULL)
4757 ++rettv->vval.v_job->jv_refcount;
4758}
4759
4760 static int
4761get_row_number(typval_T *tv, term_T *term)
4762{
4763 if (tv->v_type == VAR_STRING
4764 && tv->vval.v_string != NULL
4765 && STRCMP(tv->vval.v_string, ".") == 0)
4766 return term->tl_cursor_pos.row;
4767 return (int)get_tv_number(tv) - 1;
4768}
4769
4770/*
4771 * "term_getline(buf, row)" function
4772 */
4773 void
4774f_term_getline(typval_T *argvars, typval_T *rettv)
4775{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004776 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004777 term_T *term;
4778 int row;
4779
4780 rettv->v_type = VAR_STRING;
4781 if (buf == NULL)
4782 return;
4783 term = buf->b_term;
4784 row = get_row_number(&argvars[1], term);
4785
4786 if (term->tl_vterm == NULL)
4787 {
4788 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4789
4790 /* vterm is finished, get the text from the buffer */
4791 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4792 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4793 }
4794 else
4795 {
4796 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4797 VTermRect rect;
4798 int len;
4799 char_u *p;
4800
4801 if (row < 0 || row >= term->tl_rows)
4802 return;
4803 len = term->tl_cols * MB_MAXBYTES + 1;
4804 p = alloc(len);
4805 if (p == NULL)
4806 return;
4807 rettv->vval.v_string = p;
4808
4809 rect.start_col = 0;
4810 rect.end_col = term->tl_cols;
4811 rect.start_row = row;
4812 rect.end_row = row + 1;
4813 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4814 }
4815}
4816
4817/*
4818 * "term_getscrolled(buf)" function
4819 */
4820 void
4821f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4822{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004823 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004824
4825 if (buf == NULL)
4826 return;
4827 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4828}
4829
4830/*
4831 * "term_getsize(buf)" function
4832 */
4833 void
4834f_term_getsize(typval_T *argvars, typval_T *rettv)
4835{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004836 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004837 list_T *l;
4838
4839 if (rettv_list_alloc(rettv) == FAIL)
4840 return;
4841 if (buf == NULL)
4842 return;
4843
4844 l = rettv->vval.v_list;
4845 list_append_number(l, buf->b_term->tl_rows);
4846 list_append_number(l, buf->b_term->tl_cols);
4847}
4848
4849/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004850 * "term_setsize(buf, rows, cols)" function
4851 */
4852 void
4853f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4854{
4855 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4856 term_T *term;
4857 varnumber_T rows, cols;
4858
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004859 if (buf == NULL)
4860 {
4861 EMSG(_("E955: Not a terminal buffer"));
4862 return;
4863 }
4864 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004865 return;
4866 term = buf->b_term;
4867 rows = get_tv_number(&argvars[1]);
4868 rows = rows <= 0 ? term->tl_rows : rows;
4869 cols = get_tv_number(&argvars[2]);
4870 cols = cols <= 0 ? term->tl_cols : cols;
4871 vterm_set_size(term->tl_vterm, rows, cols);
4872 /* handle_resize() will resize the windows */
4873
4874 /* Get and remember the size we ended up with. Update the pty. */
4875 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4876 term_report_winsize(term, term->tl_rows, term->tl_cols);
4877}
4878
4879/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004880 * "term_getstatus(buf)" function
4881 */
4882 void
4883f_term_getstatus(typval_T *argvars, typval_T *rettv)
4884{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004885 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004886 term_T *term;
4887 char_u val[100];
4888
4889 rettv->v_type = VAR_STRING;
4890 if (buf == NULL)
4891 return;
4892 term = buf->b_term;
4893
4894 if (term_job_running(term))
4895 STRCPY(val, "running");
4896 else
4897 STRCPY(val, "finished");
4898 if (term->tl_normal_mode)
4899 STRCAT(val, ",normal");
4900 rettv->vval.v_string = vim_strsave(val);
4901}
4902
4903/*
4904 * "term_gettitle(buf)" function
4905 */
4906 void
4907f_term_gettitle(typval_T *argvars, typval_T *rettv)
4908{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004909 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004910
4911 rettv->v_type = VAR_STRING;
4912 if (buf == NULL)
4913 return;
4914
4915 if (buf->b_term->tl_title != NULL)
4916 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4917}
4918
4919/*
4920 * "term_gettty(buf)" function
4921 */
4922 void
4923f_term_gettty(typval_T *argvars, typval_T *rettv)
4924{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004925 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004926 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004927 int num = 0;
4928
4929 rettv->v_type = VAR_STRING;
4930 if (buf == NULL)
4931 return;
4932 if (argvars[1].v_type != VAR_UNKNOWN)
4933 num = get_tv_number(&argvars[1]);
4934
4935 switch (num)
4936 {
4937 case 0:
4938 if (buf->b_term->tl_job != NULL)
4939 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004940 break;
4941 case 1:
4942 if (buf->b_term->tl_job != NULL)
4943 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004944 break;
4945 default:
4946 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4947 return;
4948 }
4949 if (p != NULL)
4950 rettv->vval.v_string = vim_strsave(p);
4951}
4952
4953/*
4954 * "term_list()" function
4955 */
4956 void
4957f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4958{
4959 term_T *tp;
4960 list_T *l;
4961
4962 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4963 return;
4964
4965 l = rettv->vval.v_list;
4966 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4967 if (tp != NULL && tp->tl_buffer != NULL)
4968 if (list_append_number(l,
4969 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4970 return;
4971}
4972
4973/*
4974 * "term_scrape(buf, row)" function
4975 */
4976 void
4977f_term_scrape(typval_T *argvars, typval_T *rettv)
4978{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004979 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004980 VTermScreen *screen = NULL;
4981 VTermPos pos;
4982 list_T *l;
4983 term_T *term;
4984 char_u *p;
4985 sb_line_T *line;
4986
4987 if (rettv_list_alloc(rettv) == FAIL)
4988 return;
4989 if (buf == NULL)
4990 return;
4991 term = buf->b_term;
4992
4993 l = rettv->vval.v_list;
4994 pos.row = get_row_number(&argvars[1], term);
4995
4996 if (term->tl_vterm != NULL)
4997 {
4998 screen = vterm_obtain_screen(term->tl_vterm);
4999 p = NULL;
5000 line = NULL;
5001 }
5002 else
5003 {
5004 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5005
5006 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5007 return;
5008 p = ml_get_buf(buf, lnum + 1, FALSE);
5009 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5010 }
5011
5012 for (pos.col = 0; pos.col < term->tl_cols; )
5013 {
5014 dict_T *dcell;
5015 int width;
5016 VTermScreenCellAttrs attrs;
5017 VTermColor fg, bg;
5018 char_u rgb[8];
5019 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5020 int off = 0;
5021 int i;
5022
5023 if (screen == NULL)
5024 {
5025 cellattr_T *cellattr;
5026 int len;
5027
5028 /* vterm has finished, get the cell from scrollback */
5029 if (pos.col >= line->sb_cols)
5030 break;
5031 cellattr = line->sb_cells + pos.col;
5032 width = cellattr->width;
5033 attrs = cellattr->attrs;
5034 fg = cellattr->fg;
5035 bg = cellattr->bg;
5036 len = MB_PTR2LEN(p);
5037 mch_memmove(mbs, p, len);
5038 mbs[len] = NUL;
5039 p += len;
5040 }
5041 else
5042 {
5043 VTermScreenCell cell;
5044 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5045 break;
5046 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5047 {
5048 if (cell.chars[i] == 0)
5049 break;
5050 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5051 }
5052 mbs[off] = NUL;
5053 width = cell.width;
5054 attrs = cell.attrs;
5055 fg = cell.fg;
5056 bg = cell.bg;
5057 }
5058 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005059 if (dcell == NULL)
5060 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005061 list_append_dict(l, dcell);
5062
5063 dict_add_nr_str(dcell, "chars", 0, mbs);
5064
5065 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5066 fg.red, fg.green, fg.blue);
5067 dict_add_nr_str(dcell, "fg", 0, rgb);
5068 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5069 bg.red, bg.green, bg.blue);
5070 dict_add_nr_str(dcell, "bg", 0, rgb);
5071
5072 dict_add_nr_str(dcell, "attr",
5073 cell2attr(attrs, fg, bg), NULL);
5074 dict_add_nr_str(dcell, "width", width, NULL);
5075
5076 ++pos.col;
5077 if (width == 2)
5078 ++pos.col;
5079 }
5080}
5081
5082/*
5083 * "term_sendkeys(buf, keys)" function
5084 */
5085 void
5086f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5087{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005088 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005089 char_u *msg;
5090 term_T *term;
5091
5092 rettv->v_type = VAR_UNKNOWN;
5093 if (buf == NULL)
5094 return;
5095
5096 msg = get_tv_string_chk(&argvars[1]);
5097 if (msg == NULL)
5098 return;
5099 term = buf->b_term;
5100 if (term->tl_vterm == NULL)
5101 return;
5102
5103 while (*msg != NUL)
5104 {
5105 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005106 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005107 }
5108}
5109
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005110#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5111/*
5112 * "term_getansicolors(buf)" function
5113 */
5114 void
5115f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5116{
5117 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5118 term_T *term;
5119 VTermState *state;
5120 VTermColor color;
5121 char_u hexbuf[10];
5122 int index;
5123 list_T *list;
5124
5125 if (rettv_list_alloc(rettv) == FAIL)
5126 return;
5127
5128 if (buf == NULL)
5129 return;
5130 term = buf->b_term;
5131 if (term->tl_vterm == NULL)
5132 return;
5133
5134 list = rettv->vval.v_list;
5135 state = vterm_obtain_state(term->tl_vterm);
5136 for (index = 0; index < 16; index++)
5137 {
5138 vterm_state_get_palette_color(state, index, &color);
5139 sprintf((char *)hexbuf, "#%02x%02x%02x",
5140 color.red, color.green, color.blue);
5141 if (list_append_string(list, hexbuf, 7) == FAIL)
5142 return;
5143 }
5144}
5145
5146/*
5147 * "term_setansicolors(buf, list)" function
5148 */
5149 void
5150f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5151{
5152 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5153 term_T *term;
5154
5155 if (buf == NULL)
5156 return;
5157 term = buf->b_term;
5158 if (term->tl_vterm == NULL)
5159 return;
5160
5161 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5162 {
5163 EMSG(_(e_listreq));
5164 return;
5165 }
5166
5167 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5168 EMSG(_(e_invarg));
5169}
5170#endif
5171
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005172/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005173 * "term_setrestore(buf, command)" function
5174 */
5175 void
5176f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5177{
5178#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005179 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005180 term_T *term;
5181 char_u *cmd;
5182
5183 if (buf == NULL)
5184 return;
5185 term = buf->b_term;
5186 vim_free(term->tl_command);
5187 cmd = get_tv_string_chk(&argvars[1]);
5188 if (cmd != NULL)
5189 term->tl_command = vim_strsave(cmd);
5190 else
5191 term->tl_command = NULL;
5192#endif
5193}
5194
5195/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005196 * "term_setkill(buf, how)" function
5197 */
5198 void
5199f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5200{
5201 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5202 term_T *term;
5203 char_u *how;
5204
5205 if (buf == NULL)
5206 return;
5207 term = buf->b_term;
5208 vim_free(term->tl_kill);
5209 how = get_tv_string_chk(&argvars[1]);
5210 if (how != NULL)
5211 term->tl_kill = vim_strsave(how);
5212 else
5213 term->tl_kill = NULL;
5214}
5215
5216/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005217 * "term_start(command, options)" function
5218 */
5219 void
5220f_term_start(typval_T *argvars, typval_T *rettv)
5221{
5222 jobopt_T opt;
5223 buf_T *buf;
5224
5225 init_job_options(&opt);
5226 if (argvars[1].v_type != VAR_UNKNOWN
5227 && get_job_options(&argvars[1], &opt,
5228 JO_TIMEOUT_ALL + JO_STOPONEXIT
5229 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5230 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5231 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5232 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005233 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005234 + JO2_NORESTORE + JO2_TERM_KILL
5235 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005236 return;
5237
Bram Moolenaar13568252018-03-16 20:46:58 +01005238 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005239
5240 if (buf != NULL && buf->b_term != NULL)
5241 rettv->vval.v_number = buf->b_fnum;
5242}
5243
5244/*
5245 * "term_wait" function
5246 */
5247 void
5248f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5249{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005250 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005251
5252 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005253 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005254 if (buf->b_term->tl_job == NULL)
5255 {
5256 ch_log(NULL, "term_wait(): no job to wait for");
5257 return;
5258 }
5259 if (buf->b_term->tl_job->jv_channel == NULL)
5260 /* channel is closed, nothing to do */
5261 return;
5262
5263 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005264 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005265 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5266 {
5267 /* The job is dead, keep reading channel I/O until the channel is
5268 * closed. buf->b_term may become NULL if the terminal was closed while
5269 * waiting. */
5270 ch_log(NULL, "term_wait(): waiting for channel to close");
5271 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5272 {
5273 mch_check_messages();
5274 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005275 if (!buf_valid(buf))
5276 /* If the terminal is closed when the channel is closed the
5277 * buffer disappears. */
5278 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005279 ui_delay(10L, FALSE);
5280 }
5281 mch_check_messages();
5282 parse_queued_messages();
5283 }
5284 else
5285 {
5286 long wait = 10L;
5287
5288 mch_check_messages();
5289 parse_queued_messages();
5290
5291 /* Wait for some time for any channel I/O. */
5292 if (argvars[1].v_type != VAR_UNKNOWN)
5293 wait = get_tv_number(&argvars[1]);
5294 ui_delay(wait, TRUE);
5295 mch_check_messages();
5296
5297 /* Flushing messages on channels is hopefully sufficient.
5298 * TODO: is there a better way? */
5299 parse_queued_messages();
5300 }
5301}
5302
5303/*
5304 * Called when a channel has sent all the lines to a terminal.
5305 * Send a CTRL-D to mark the end of the text.
5306 */
5307 void
5308term_send_eof(channel_T *ch)
5309{
5310 term_T *term;
5311
5312 for (term = first_term; term != NULL; term = term->tl_next)
5313 if (term->tl_job == ch->ch_job)
5314 {
5315 if (term->tl_eof_chars != NULL)
5316 {
5317 channel_send(ch, PART_IN, term->tl_eof_chars,
5318 (int)STRLEN(term->tl_eof_chars), NULL);
5319 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5320 }
5321# ifdef WIN3264
5322 else
5323 /* Default: CTRL-D */
5324 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5325# endif
5326 }
5327}
5328
5329# if defined(WIN3264) || defined(PROTO)
5330
5331/**************************************
5332 * 2. MS-Windows implementation.
5333 */
5334
5335# ifndef PROTO
5336
5337#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5338#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005339#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005340
5341void* (*winpty_config_new)(UINT64, void*);
5342void* (*winpty_open)(void*, void*);
5343void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5344BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5345void (*winpty_config_set_mouse_mode)(void*, int);
5346void (*winpty_config_set_initial_size)(void*, int, int);
5347LPCWSTR (*winpty_conin_name)(void*);
5348LPCWSTR (*winpty_conout_name)(void*);
5349LPCWSTR (*winpty_conerr_name)(void*);
5350void (*winpty_free)(void*);
5351void (*winpty_config_free)(void*);
5352void (*winpty_spawn_config_free)(void*);
5353void (*winpty_error_free)(void*);
5354LPCWSTR (*winpty_error_msg)(void*);
5355BOOL (*winpty_set_size)(void*, int, int, void*);
5356HANDLE (*winpty_agent_process)(void*);
5357
5358#define WINPTY_DLL "winpty.dll"
5359
5360static HINSTANCE hWinPtyDLL = NULL;
5361# endif
5362
5363 static int
5364dyn_winpty_init(int verbose)
5365{
5366 int i;
5367 static struct
5368 {
5369 char *name;
5370 FARPROC *ptr;
5371 } winpty_entry[] =
5372 {
5373 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5374 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5375 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5376 {"winpty_config_set_mouse_mode",
5377 (FARPROC*)&winpty_config_set_mouse_mode},
5378 {"winpty_config_set_initial_size",
5379 (FARPROC*)&winpty_config_set_initial_size},
5380 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5381 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5382 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5383 {"winpty_free", (FARPROC*)&winpty_free},
5384 {"winpty_open", (FARPROC*)&winpty_open},
5385 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5386 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5387 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5388 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5389 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5390 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5391 {NULL, NULL}
5392 };
5393
5394 /* No need to initialize twice. */
5395 if (hWinPtyDLL)
5396 return OK;
5397 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5398 * winpty.dll. */
5399 if (*p_winptydll != NUL)
5400 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5401 if (!hWinPtyDLL)
5402 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5403 if (!hWinPtyDLL)
5404 {
5405 if (verbose)
5406 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5407 : (char_u *)WINPTY_DLL);
5408 return FAIL;
5409 }
5410 for (i = 0; winpty_entry[i].name != NULL
5411 && winpty_entry[i].ptr != NULL; ++i)
5412 {
5413 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5414 winpty_entry[i].name)) == NULL)
5415 {
5416 if (verbose)
5417 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5418 return FAIL;
5419 }
5420 }
5421
5422 return OK;
5423}
5424
5425/*
5426 * Create a new terminal of "rows" by "cols" cells.
5427 * Store a reference in "term".
5428 * Return OK or FAIL.
5429 */
5430 static int
5431term_and_job_init(
5432 term_T *term,
5433 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005434 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005435 jobopt_T *opt,
5436 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005437{
5438 WCHAR *cmd_wchar = NULL;
5439 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005440 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005441 channel_T *channel = NULL;
5442 job_T *job = NULL;
5443 DWORD error;
5444 HANDLE jo = NULL;
5445 HANDLE child_process_handle;
5446 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005447 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005448 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005449 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005450 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005451
5452 if (dyn_winpty_init(TRUE) == FAIL)
5453 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005454 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5455 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005456
5457 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005458 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005459 cmd = argvar->vval.v_string;
5460 }
5461 else if (argvar->v_type == VAR_LIST)
5462 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005463 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005464 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005465 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005466 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005467 if (cmd == NULL || *cmd == NUL)
5468 {
5469 EMSG(_(e_invarg));
5470 goto failed;
5471 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005472
5473 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005474 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005475 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005476 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005477 if (opt->jo_cwd != NULL)
5478 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005479
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005480 win32_build_env(opt->jo_env, &ga_env, TRUE);
5481 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005482
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005483 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5484 if (term->tl_winpty_config == NULL)
5485 goto failed;
5486
5487 winpty_config_set_mouse_mode(term->tl_winpty_config,
5488 WINPTY_MOUSE_MODE_FORCE);
5489 winpty_config_set_initial_size(term->tl_winpty_config,
5490 term->tl_cols, term->tl_rows);
5491 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5492 if (term->tl_winpty == NULL)
5493 goto failed;
5494
5495 spawn_config = winpty_spawn_config_new(
5496 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5497 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5498 NULL,
5499 cmd_wchar,
5500 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005501 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005502 &winpty_err);
5503 if (spawn_config == NULL)
5504 goto failed;
5505
5506 channel = add_channel();
5507 if (channel == NULL)
5508 goto failed;
5509
5510 job = job_alloc();
5511 if (job == NULL)
5512 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005513 if (argvar->v_type == VAR_STRING)
5514 {
5515 int argc;
5516
5517 build_argv_from_string(cmd, &job->jv_argv, &argc);
5518 }
5519 else
5520 {
5521 int argc;
5522
5523 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5524 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005525
5526 if (opt->jo_set & JO_IN_BUF)
5527 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5528
5529 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5530 &child_thread_handle, &error, &winpty_err))
5531 goto failed;
5532
5533 channel_set_pipes(channel,
5534 (sock_T)CreateFileW(
5535 winpty_conin_name(term->tl_winpty),
5536 GENERIC_WRITE, 0, NULL,
5537 OPEN_EXISTING, 0, NULL),
5538 (sock_T)CreateFileW(
5539 winpty_conout_name(term->tl_winpty),
5540 GENERIC_READ, 0, NULL,
5541 OPEN_EXISTING, 0, NULL),
5542 (sock_T)CreateFileW(
5543 winpty_conerr_name(term->tl_winpty),
5544 GENERIC_READ, 0, NULL,
5545 OPEN_EXISTING, 0, NULL));
5546
5547 /* Write lines with CR instead of NL. */
5548 channel->ch_write_text_mode = TRUE;
5549
5550 jo = CreateJobObject(NULL, NULL);
5551 if (jo == NULL)
5552 goto failed;
5553
5554 if (!AssignProcessToJobObject(jo, child_process_handle))
5555 {
5556 /* Failed, switch the way to terminate process with TerminateProcess. */
5557 CloseHandle(jo);
5558 jo = NULL;
5559 }
5560
5561 winpty_spawn_config_free(spawn_config);
5562 vim_free(cmd_wchar);
5563 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005564 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005565
5566 create_vterm(term, term->tl_rows, term->tl_cols);
5567
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005568#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5569 if (opt->jo_set2 & JO2_ANSI_COLORS)
5570 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5571 else
5572 init_vterm_ansi_colors(term->tl_vterm);
5573#endif
5574
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005575 channel_set_job(channel, job, opt);
5576 job_set_options(job, opt);
5577
5578 job->jv_channel = channel;
5579 job->jv_proc_info.hProcess = child_process_handle;
5580 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5581 job->jv_job_object = jo;
5582 job->jv_status = JOB_STARTED;
5583 job->jv_tty_in = utf16_to_enc(
5584 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5585 job->jv_tty_out = utf16_to_enc(
5586 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5587 ++job->jv_refcount;
5588 term->tl_job = job;
5589
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005590 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5591 * open the file here and handle it in. opt->jo_io was changed in
5592 * setup_job_options(), use the original flags here. */
5593 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5594 {
5595 char_u *fname = opt->jo_io_name[PART_OUT];
5596
5597 ch_log(channel, "Opening output file %s", fname);
5598 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5599 if (term->tl_out_fd == NULL)
5600 EMSG2(_(e_notopen), fname);
5601 }
5602
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005603 return OK;
5604
5605failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005606 ga_clear(&ga_cmd);
5607 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005608 vim_free(cmd_wchar);
5609 vim_free(cwd_wchar);
5610 if (spawn_config != NULL)
5611 winpty_spawn_config_free(spawn_config);
5612 if (channel != NULL)
5613 channel_clear(channel);
5614 if (job != NULL)
5615 {
5616 job->jv_channel = NULL;
5617 job_cleanup(job);
5618 }
5619 term->tl_job = NULL;
5620 if (jo != NULL)
5621 CloseHandle(jo);
5622 if (term->tl_winpty != NULL)
5623 winpty_free(term->tl_winpty);
5624 term->tl_winpty = NULL;
5625 if (term->tl_winpty_config != NULL)
5626 winpty_config_free(term->tl_winpty_config);
5627 term->tl_winpty_config = NULL;
5628 if (winpty_err != NULL)
5629 {
5630 char_u *msg = utf16_to_enc(
5631 (short_u *)winpty_error_msg(winpty_err), NULL);
5632
5633 EMSG(msg);
5634 winpty_error_free(winpty_err);
5635 }
5636 return FAIL;
5637}
5638
5639 static int
5640create_pty_only(term_T *term, jobopt_T *options)
5641{
5642 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5643 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5644 char in_name[80], out_name[80];
5645 channel_T *channel = NULL;
5646
5647 create_vterm(term, term->tl_rows, term->tl_cols);
5648
5649 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5650 GetCurrentProcessId(),
5651 curbuf->b_fnum);
5652 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5653 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5654 PIPE_UNLIMITED_INSTANCES,
5655 0, 0, NMPWAIT_NOWAIT, NULL);
5656 if (hPipeIn == INVALID_HANDLE_VALUE)
5657 goto failed;
5658
5659 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5660 GetCurrentProcessId(),
5661 curbuf->b_fnum);
5662 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5663 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5664 PIPE_UNLIMITED_INSTANCES,
5665 0, 0, 0, NULL);
5666 if (hPipeOut == INVALID_HANDLE_VALUE)
5667 goto failed;
5668
5669 ConnectNamedPipe(hPipeIn, NULL);
5670 ConnectNamedPipe(hPipeOut, NULL);
5671
5672 term->tl_job = job_alloc();
5673 if (term->tl_job == NULL)
5674 goto failed;
5675 ++term->tl_job->jv_refcount;
5676
5677 /* behave like the job is already finished */
5678 term->tl_job->jv_status = JOB_FINISHED;
5679
5680 channel = add_channel();
5681 if (channel == NULL)
5682 goto failed;
5683 term->tl_job->jv_channel = channel;
5684 channel->ch_keep_open = TRUE;
5685 channel->ch_named_pipe = TRUE;
5686
5687 channel_set_pipes(channel,
5688 (sock_T)hPipeIn,
5689 (sock_T)hPipeOut,
5690 (sock_T)hPipeOut);
5691 channel_set_job(channel, term->tl_job, options);
5692 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5693 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5694
5695 return OK;
5696
5697failed:
5698 if (hPipeIn != NULL)
5699 CloseHandle(hPipeIn);
5700 if (hPipeOut != NULL)
5701 CloseHandle(hPipeOut);
5702 return FAIL;
5703}
5704
5705/*
5706 * Free the terminal emulator part of "term".
5707 */
5708 static void
5709term_free_vterm(term_T *term)
5710{
5711 if (term->tl_winpty != NULL)
5712 winpty_free(term->tl_winpty);
5713 term->tl_winpty = NULL;
5714 if (term->tl_winpty_config != NULL)
5715 winpty_config_free(term->tl_winpty_config);
5716 term->tl_winpty_config = NULL;
5717 if (term->tl_vterm != NULL)
5718 vterm_free(term->tl_vterm);
5719 term->tl_vterm = NULL;
5720}
5721
5722/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005723 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005724 */
5725 static void
5726term_report_winsize(term_T *term, int rows, int cols)
5727{
5728 if (term->tl_winpty)
5729 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5730}
5731
5732 int
5733terminal_enabled(void)
5734{
5735 return dyn_winpty_init(FALSE) == OK;
5736}
5737
5738# else
5739
5740/**************************************
5741 * 3. Unix-like implementation.
5742 */
5743
5744/*
5745 * Create a new terminal of "rows" by "cols" cells.
5746 * Start job for "cmd".
5747 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005748 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005749 * Return OK or FAIL.
5750 */
5751 static int
5752term_and_job_init(
5753 term_T *term,
5754 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005755 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005756 jobopt_T *opt,
5757 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005758{
5759 create_vterm(term, term->tl_rows, term->tl_cols);
5760
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005761#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5762 if (opt->jo_set2 & JO2_ANSI_COLORS)
5763 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5764 else
5765 init_vterm_ansi_colors(term->tl_vterm);
5766#endif
5767
Bram Moolenaar13568252018-03-16 20:46:58 +01005768 /* This may change a string in "argvar". */
5769 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005770 if (term->tl_job != NULL)
5771 ++term->tl_job->jv_refcount;
5772
5773 return term->tl_job != NULL
5774 && term->tl_job->jv_channel != NULL
5775 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5776}
5777
5778 static int
5779create_pty_only(term_T *term, jobopt_T *opt)
5780{
5781 create_vterm(term, term->tl_rows, term->tl_cols);
5782
5783 term->tl_job = job_alloc();
5784 if (term->tl_job == NULL)
5785 return FAIL;
5786 ++term->tl_job->jv_refcount;
5787
5788 /* behave like the job is already finished */
5789 term->tl_job->jv_status = JOB_FINISHED;
5790
5791 return mch_create_pty_channel(term->tl_job, opt);
5792}
5793
5794/*
5795 * Free the terminal emulator part of "term".
5796 */
5797 static void
5798term_free_vterm(term_T *term)
5799{
5800 if (term->tl_vterm != NULL)
5801 vterm_free(term->tl_vterm);
5802 term->tl_vterm = NULL;
5803}
5804
5805/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005806 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005807 */
5808 static void
5809term_report_winsize(term_T *term, int rows, int cols)
5810{
5811 /* Use an ioctl() to report the new window size to the job. */
5812 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5813 {
5814 int fd = -1;
5815 int part;
5816
5817 for (part = PART_OUT; part < PART_COUNT; ++part)
5818 {
5819 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5820 if (isatty(fd))
5821 break;
5822 }
5823 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5824 mch_signal_job(term->tl_job, (char_u *)"winch");
5825 }
5826}
5827
5828# endif
5829
5830#endif /* FEAT_TERMINAL */