blob: 817e6b9375f09c55d239fcf8e6205da07abc1a23 [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.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
54/* This is VTermScreenCell without the characters, thus much smaller. */
55typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
63 int sb_cols; /* can differ per line */
64 cellattr_T *sb_cells; /* allocated */
65 cellattr_T sb_fill_attr; /* for short line */
66} sb_line_T;
67
68/* typedef term_T in structs.h */
69struct terminal_S {
70 term_T *tl_next;
71
72 VTerm *tl_vterm;
73 job_T *tl_job;
74 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010075#if defined(FEAT_GUI)
76 int tl_system; /* when non-zero used for :!cmd output */
77 int tl_toprow; /* row with first line of system terminal */
78#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020079
80 /* Set when setting the size of a vterm, reset after redrawing. */
81 int tl_vterm_size_changed;
82
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020083 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
84 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +020085 int tl_channel_recently_closed; // still need to handle tl_finish
86
Bram Moolenaar1dd98332018-03-16 22:54:53 +010087 int tl_finish;
88#define TL_FINISH_UNSET NUL
89#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
90#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
91#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020092 char_u *tl_opencmd;
93 char_u *tl_eof_chars;
94
95#ifdef WIN3264
96 void *tl_winpty_config;
97 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +020098
99 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200100#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100101#if defined(FEAT_SESSION)
102 char_u *tl_command;
103#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100104 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200105
106 /* last known vterm size */
107 int tl_rows;
108 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200109
110 char_u *tl_title; /* NULL or allocated */
111 char_u *tl_status_text; /* NULL or allocated */
112
113 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200114 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200115 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200116 int tl_dirty_snapshot; /* text updated after making snapshot */
117#ifdef FEAT_TIMERS
118 int tl_timer_set;
119 proftime_T tl_timer_due;
120#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200121 int tl_postponed_scroll; /* to be scrolled up */
122
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123 garray_T tl_scrollback;
124 int tl_scrollback_scrolled;
125 cellattr_T tl_default_color;
126
Bram Moolenaard96ff162018-02-18 22:13:29 +0100127 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
128 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130 VTermPos tl_cursor_pos;
131 int tl_cursor_visible;
132 int tl_cursor_blink;
133 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
134 char_u *tl_cursor_color; /* NULL or allocated */
135
136 int tl_using_altscreen;
137};
138
139#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
140#define TMODE_LOOP 2 /* CTRL-W N used */
141
142/*
143 * List of all active terminals.
144 */
145static term_T *first_term = NULL;
146
147/* Terminal active in terminal_loop(). */
148static term_T *in_terminal_loop = NULL;
149
150#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
151#define KEY_BUF_LEN 200
152
153/*
154 * Functions with separate implementation for MS-Windows and Unix-like systems.
155 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200156static 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 +0200157static int create_pty_only(term_T *term, jobopt_T *opt);
158static void term_report_winsize(term_T *term, int rows, int cols);
159static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100160#ifdef FEAT_GUI
161static void update_system_term(term_T *term);
162#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200163
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100164/* The character that we know (or assume) that the terminal expects for the
165 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200166static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200167
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100168/* "Terminal" highlight group colors. */
169static int term_default_cterm_fg = -1;
170static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200171
Bram Moolenaard317b382018-02-08 22:33:31 +0100172/* Store the last set and the desired cursor properties, so that we only update
173 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200174static char_u *last_set_cursor_color = NULL;
175static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100176static int last_set_cursor_shape = -1;
177static int desired_cursor_shape = -1;
178static int last_set_cursor_blink = -1;
179static int desired_cursor_blink = -1;
180
181
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182/**************************************
183 * 1. Generic code for all systems.
184 */
185
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200186 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200187cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
188{
189 if (lhs_color != NULL && rhs_color != NULL)
190 return STRCMP(lhs_color, rhs_color) == 0;
191 return lhs_color == NULL && rhs_color == NULL;
192}
193
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200194 static void
195cursor_color_copy(char_u **to_color, char_u *from_color)
196{
197 // Avoid a free & alloc if the value is already right.
198 if (cursor_color_equal(*to_color, from_color))
199 return;
200 vim_free(*to_color);
201 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
202}
203
204 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200205cursor_color_get(char_u *color)
206{
207 return (color == NULL) ? (char_u *)"" : color;
208}
209
210
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200211/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200212 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200213 * current window.
214 * Sets "rows" and/or "cols" to zero when it should follow the window size.
215 * Return TRUE if the size is the minimum size: "24*80".
216 */
217 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200218parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200219{
220 int minsize = FALSE;
221
222 *rows = 0;
223 *cols = 0;
224
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200225 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200226 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200227 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200228
229 /* Syntax of value was already checked when it's set. */
230 if (p == NULL)
231 {
232 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200233 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200234 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200235 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200236 *cols = atoi((char *)p + 1);
237 }
238 return minsize;
239}
240
241/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200242 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243 */
244 static void
245set_term_and_win_size(term_T *term)
246{
Bram Moolenaar13568252018-03-16 20:46:58 +0100247#ifdef FEAT_GUI
248 if (term->tl_system)
249 {
250 /* Use the whole screen for the system command. However, it will start
251 * at the command line and scroll up as needed, using tl_toprow. */
252 term->tl_rows = Rows;
253 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200254 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100255 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100256#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200257 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200258 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200259 if (term->tl_rows != 0)
260 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
261 if (term->tl_cols != 0)
262 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200263 }
264 if (term->tl_rows == 0)
265 term->tl_rows = curwin->w_height;
266 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200267 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268 if (term->tl_cols == 0)
269 term->tl_cols = curwin->w_width;
270 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200271 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200272}
273
274/*
275 * Initialize job options for a terminal job.
276 * Caller may overrule some of them.
277 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100278 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200279init_job_options(jobopt_T *opt)
280{
281 clear_job_options(opt);
282
283 opt->jo_mode = MODE_RAW;
284 opt->jo_out_mode = MODE_RAW;
285 opt->jo_err_mode = MODE_RAW;
286 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
287}
288
289/*
290 * Set job options mandatory for a terminal job.
291 */
292 static void
293setup_job_options(jobopt_T *opt, int rows, int cols)
294{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200295#ifndef WIN3264
296 /* Win32: Redirecting the job output won't work, thus always connect stdout
297 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200298 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200299#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 {
301 /* Connect stdout to the terminal. */
302 opt->jo_io[PART_OUT] = JIO_BUFFER;
303 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
304 opt->jo_modifiable[PART_OUT] = 0;
305 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
306 }
307
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200308#ifndef WIN3264
309 /* Win32: Redirecting the job output won't work, thus always connect stderr
310 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200312#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200313 {
314 /* Connect stderr to the terminal. */
315 opt->jo_io[PART_ERR] = JIO_BUFFER;
316 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
317 opt->jo_modifiable[PART_ERR] = 0;
318 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
319 }
320
321 opt->jo_pty = TRUE;
322 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
323 opt->jo_term_rows = rows;
324 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
325 opt->jo_term_cols = cols;
326}
327
328/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100329 * Close a terminal buffer (and its window). Used when creating the terminal
330 * fails.
331 */
332 static void
333term_close_buffer(buf_T *buf, buf_T *old_curbuf)
334{
335 free_terminal(buf);
336 if (old_curbuf != NULL)
337 {
338 --curbuf->b_nwindows;
339 curbuf = old_curbuf;
340 curwin->w_buffer = curbuf;
341 ++curbuf->b_nwindows;
342 }
343
344 /* Wiping out the buffer will also close the window and call
345 * free_terminal(). */
346 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
347}
348
349/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200350 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100351 * Use either "argvar" or "argv", the other must be NULL.
352 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
353 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200354 * Returns NULL when failed.
355 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100356 buf_T *
357term_start(
358 typval_T *argvar,
359 char **argv,
360 jobopt_T *opt,
361 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200362{
363 exarg_T split_ea;
364 win_T *old_curwin = curwin;
365 term_T *term;
366 buf_T *old_curbuf = NULL;
367 int res;
368 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100369 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200370 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200371
372 if (check_restricted() || check_secure())
373 return NULL;
374
375 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
376 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
377 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
378 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
379 {
380 EMSG(_(e_invarg));
381 return NULL;
382 }
383
384 term = (term_T *)alloc_clear(sizeof(term_T));
385 if (term == NULL)
386 return NULL;
387 term->tl_dirty_row_end = MAX_ROW;
388 term->tl_cursor_visible = TRUE;
389 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
390 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100391#ifdef FEAT_GUI
392 term->tl_system = (flags & TERM_START_SYSTEM);
393#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200394 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
395
396 vim_memset(&split_ea, 0, sizeof(split_ea));
397 if (opt->jo_curwin)
398 {
399 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100400 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200401 {
402 no_write_message();
403 vim_free(term);
404 return NULL;
405 }
406 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100407 ECMD_HIDE
408 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
409 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410 {
411 vim_free(term);
412 return NULL;
413 }
414 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100415 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200416 {
417 buf_T *buf;
418
419 /* Create a new buffer without a window. Make it the current buffer for
420 * a moment to be able to do the initialisations. */
421 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
422 BLN_NEW | BLN_LISTED);
423 if (buf == NULL || ml_open(buf) == FAIL)
424 {
425 vim_free(term);
426 return NULL;
427 }
428 old_curbuf = curbuf;
429 --curbuf->b_nwindows;
430 curbuf = buf;
431 curwin->w_buffer = buf;
432 ++curbuf->b_nwindows;
433 }
434 else
435 {
436 /* Open a new window or tab. */
437 split_ea.cmdidx = CMD_new;
438 split_ea.cmd = (char_u *)"new";
439 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100440 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200441 {
442 split_ea.line2 = opt->jo_term_rows;
443 split_ea.addr_count = 1;
444 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100445 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200446 {
447 split_ea.line2 = opt->jo_term_cols;
448 split_ea.addr_count = 1;
449 }
450
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100451 if (vertical)
452 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200453 ex_splitview(&split_ea);
454 if (curwin == old_curwin)
455 {
456 /* split failed */
457 vim_free(term);
458 return NULL;
459 }
460 }
461 term->tl_buffer = curbuf;
462 curbuf->b_term = term;
463
464 if (!opt->jo_hidden)
465 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100466 /* Only one size was taken care of with :new, do the other one. With
467 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100468 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100470 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200471 win_setwidth(opt->jo_term_cols);
472 }
473
474 /* Link the new terminal in the list of active terminals. */
475 term->tl_next = first_term;
476 first_term = term;
477
478 if (opt->jo_term_name != NULL)
479 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100480 else if (argv != NULL)
481 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200482 else
483 {
484 int i;
485 size_t len;
486 char_u *cmd, *p;
487
488 if (argvar->v_type == VAR_STRING)
489 {
490 cmd = argvar->vval.v_string;
491 if (cmd == NULL)
492 cmd = (char_u *)"";
493 else if (STRCMP(cmd, "NONE") == 0)
494 cmd = (char_u *)"pty";
495 }
496 else if (argvar->v_type != VAR_LIST
497 || argvar->vval.v_list == NULL
498 || argvar->vval.v_list->lv_len < 1
499 || (cmd = get_tv_string_chk(
500 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
501 cmd = (char_u*)"";
502
503 len = STRLEN(cmd) + 10;
504 p = alloc((int)len);
505
506 for (i = 0; p != NULL; ++i)
507 {
508 /* Prepend a ! to the command name to avoid the buffer name equals
509 * the executable, otherwise ":w!" would overwrite it. */
510 if (i == 0)
511 vim_snprintf((char *)p, len, "!%s", cmd);
512 else
513 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
514 if (buflist_findname(p) == NULL)
515 {
516 vim_free(curbuf->b_ffname);
517 curbuf->b_ffname = p;
518 break;
519 }
520 }
521 }
522 curbuf->b_fname = curbuf->b_ffname;
523
524 if (opt->jo_term_opencmd != NULL)
525 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
526
527 if (opt->jo_eof_chars != NULL)
528 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
529
530 set_string_option_direct((char_u *)"buftype", -1,
531 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
532
533 /* Mark the buffer as not modifiable. It can only be made modifiable after
534 * the job finished. */
535 curbuf->b_p_ma = FALSE;
536
537 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200538#ifdef WIN3264
539 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
540#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200541 setup_job_options(opt, term->tl_rows, term->tl_cols);
542
Bram Moolenaar13568252018-03-16 20:46:58 +0100543 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100544 return curbuf;
545
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100546#if defined(FEAT_SESSION)
547 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100548 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100549 {
550 term->tl_command = vim_strsave((char_u *)"NONE");
551 }
552 else if (argvar->v_type == VAR_STRING)
553 {
554 char_u *cmd = argvar->vval.v_string;
555
556 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
557 term->tl_command = vim_strsave(cmd);
558 }
559 else if (argvar->v_type == VAR_LIST
560 && argvar->vval.v_list != NULL
561 && argvar->vval.v_list->lv_len > 0)
562 {
563 garray_T ga;
564 listitem_T *item;
565
566 ga_init2(&ga, 1, 100);
567 for (item = argvar->vval.v_list->lv_first;
568 item != NULL; item = item->li_next)
569 {
570 char_u *s = get_tv_string_chk(&item->li_tv);
571 char_u *p;
572
573 if (s == NULL)
574 break;
575 p = vim_strsave_fnameescape(s, FALSE);
576 if (p == NULL)
577 break;
578 ga_concat(&ga, p);
579 vim_free(p);
580 ga_append(&ga, ' ');
581 }
582 if (item == NULL)
583 {
584 ga_append(&ga, NUL);
585 term->tl_command = ga.ga_data;
586 }
587 else
588 ga_clear(&ga);
589 }
590#endif
591
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100592 if (opt->jo_term_kill != NULL)
593 {
594 char_u *p = skiptowhite(opt->jo_term_kill);
595
596 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
597 }
598
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100600 if (argv == NULL
601 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200602 && argvar->vval.v_string != NULL
603 && STRCMP(argvar->vval.v_string, "NONE") == 0)
604 res = create_pty_only(term, opt);
605 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200606 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607
608 newbuf = curbuf;
609 if (res == OK)
610 {
611 /* Get and remember the size we ended up with. Update the pty. */
612 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
613 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100614#ifdef FEAT_GUI
615 if (term->tl_system)
616 {
617 /* display first line below typed command */
618 term->tl_toprow = msg_row + 1;
619 term->tl_dirty_row_end = 0;
620 }
621#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622
623 /* Make sure we don't get stuck on sending keys to the job, it leads to
624 * a deadlock if the job is waiting for Vim to read. */
625 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
626
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200627 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200628 {
629 --curbuf->b_nwindows;
630 curbuf = old_curbuf;
631 curwin->w_buffer = curbuf;
632 ++curbuf->b_nwindows;
633 }
634 }
635 else
636 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100637 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200638 return NULL;
639 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100640
Bram Moolenaar13568252018-03-16 20:46:58 +0100641 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642 return newbuf;
643}
644
645/*
646 * ":terminal": open a terminal window and execute a job in it.
647 */
648 void
649ex_terminal(exarg_T *eap)
650{
651 typval_T argvar[2];
652 jobopt_T opt;
653 char_u *cmd;
654 char_u *tofree = NULL;
655
656 init_job_options(&opt);
657
658 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100659 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 {
661 char_u *p, *ep;
662
663 cmd += 2;
664 p = skiptowhite(cmd);
665 ep = vim_strchr(cmd, '=');
666 if (ep != NULL && ep < p)
667 p = ep;
668
669 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
670 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100671 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
672 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
674 opt.jo_term_finish = 'o';
675 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
676 opt.jo_curwin = 1;
677 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
678 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100679 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
680 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100681 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
682 && ep != NULL)
683 {
684 opt.jo_set2 |= JO2_TERM_KILL;
685 opt.jo_term_kill = ep + 1;
686 p = skiptowhite(cmd);
687 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200688 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
689 && ep != NULL && isdigit(ep[1]))
690 {
691 opt.jo_set2 |= JO2_TERM_ROWS;
692 opt.jo_term_rows = atoi((char *)ep + 1);
693 p = skiptowhite(cmd);
694 }
695 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
696 && ep != NULL && isdigit(ep[1]))
697 {
698 opt.jo_set2 |= JO2_TERM_COLS;
699 opt.jo_term_cols = atoi((char *)ep + 1);
700 p = skiptowhite(cmd);
701 }
702 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
703 && ep != NULL)
704 {
705 char_u *buf = NULL;
706 char_u *keys;
707
708 p = skiptowhite(cmd);
709 *p = NUL;
710 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
711 opt.jo_set2 |= JO2_EOF_CHARS;
712 opt.jo_eof_chars = vim_strsave(keys);
713 vim_free(buf);
714 *p = ' ';
715 }
716 else
717 {
718 if (*p)
719 *p = NUL;
720 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100721 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200722 }
723 cmd = skipwhite(p);
724 }
725 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100726 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727 /* Make a copy of 'shell', an autocommand may change the option. */
728 tofree = cmd = vim_strsave(p_sh);
729
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100730 /* default to close when the shell exits */
731 if (opt.jo_term_finish == NUL)
732 opt.jo_term_finish = 'c';
733 }
734
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 if (eap->addr_count > 0)
736 {
737 /* Write lines from current buffer to the job. */
738 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
739 opt.jo_io[PART_IN] = JIO_BUFFER;
740 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
741 opt.jo_in_top = eap->line1;
742 opt.jo_in_bot = eap->line2;
743 }
744
745 argvar[0].v_type = VAR_STRING;
746 argvar[0].vval.v_string = cmd;
747 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100748 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100750
751theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752 vim_free(opt.jo_eof_chars);
753}
754
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100755#if defined(FEAT_SESSION) || defined(PROTO)
756/*
757 * Write a :terminal command to the session file to restore the terminal in
758 * window "wp".
759 * Return FAIL if writing fails.
760 */
761 int
762term_write_session(FILE *fd, win_T *wp)
763{
764 term_T *term = wp->w_buffer->b_term;
765
766 /* Create the terminal and run the command. This is not without
767 * risk, but let's assume the user only creates a session when this
768 * will be OK. */
769 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
770 term->tl_cols, term->tl_rows) < 0)
771 return FAIL;
772 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
773 return FAIL;
774
775 return put_eol(fd);
776}
777
778/*
779 * Return TRUE if "buf" has a terminal that should be restored.
780 */
781 int
782term_should_restore(buf_T *buf)
783{
784 term_T *term = buf->b_term;
785
786 return term != NULL && (term->tl_command == NULL
787 || STRCMP(term->tl_command, "NONE") != 0);
788}
789#endif
790
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200791/*
792 * Free the scrollback buffer for "term".
793 */
794 static void
795free_scrollback(term_T *term)
796{
797 int i;
798
799 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
800 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
801 ga_clear(&term->tl_scrollback);
802}
803
804/*
805 * Free a terminal and everything it refers to.
806 * Kills the job if there is one.
807 * Called when wiping out a buffer.
808 */
809 void
810free_terminal(buf_T *buf)
811{
812 term_T *term = buf->b_term;
813 term_T *tp;
814
815 if (term == NULL)
816 return;
817 if (first_term == term)
818 first_term = term->tl_next;
819 else
820 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
821 if (tp->tl_next == term)
822 {
823 tp->tl_next = term->tl_next;
824 break;
825 }
826
827 if (term->tl_job != NULL)
828 {
829 if (term->tl_job->jv_status != JOB_ENDED
830 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100831 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200832 job_stop(term->tl_job, NULL, "kill");
833 job_unref(term->tl_job);
834 }
835
836 free_scrollback(term);
837
838 term_free_vterm(term);
839 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100840#ifdef FEAT_SESSION
841 vim_free(term->tl_command);
842#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100843 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200844 vim_free(term->tl_status_text);
845 vim_free(term->tl_opencmd);
846 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200847#ifdef WIN3264
848 if (term->tl_out_fd != NULL)
849 fclose(term->tl_out_fd);
850#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200851 vim_free(term->tl_cursor_color);
852 vim_free(term);
853 buf->b_term = NULL;
854 if (in_terminal_loop == term)
855 in_terminal_loop = NULL;
856}
857
858/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100859 * Get the part that is connected to the tty. Normally this is PART_IN, but
860 * when writing buffer lines to the job it can be another. This makes it
861 * possible to do "1,5term vim -".
862 */
863 static ch_part_T
864get_tty_part(term_T *term)
865{
866#ifdef UNIX
867 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
868 int i;
869
870 for (i = 0; i < 3; ++i)
871 {
872 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
873
874 if (isatty(fd))
875 return parts[i];
876 }
877#endif
878 return PART_IN;
879}
880
881/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200882 * Write job output "msg[len]" to the vterm.
883 */
884 static void
885term_write_job_output(term_T *term, char_u *msg, size_t len)
886{
887 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100888 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100890 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200891
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100892 /* flush vterm buffer when vterm responded to control sequence */
893 if (prevlen != vterm_output_get_buffer_current(vterm))
894 {
895 char buf[KEY_BUF_LEN];
896 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
897
898 if (curlen > 0)
899 channel_send(term->tl_job->jv_channel, get_tty_part(term),
900 (char_u *)buf, (int)curlen, NULL);
901 }
902
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200903 /* this invokes the damage callbacks */
904 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
905}
906
907 static void
908update_cursor(term_T *term, int redraw)
909{
910 if (term->tl_normal_mode)
911 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100912#ifdef FEAT_GUI
913 if (term->tl_system)
914 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
915 term->tl_cursor_pos.col);
916 else
917#endif
918 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 if (redraw)
920 {
921 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
922 cursor_on();
923 out_flush();
924#ifdef FEAT_GUI
925 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100926 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200927 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100928 gui_mch_flush();
929 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200930#endif
931 }
932}
933
934/*
935 * Invoked when "msg" output from a job was received. Write it to the terminal
936 * of "buffer".
937 */
938 void
939write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
940{
941 size_t len = STRLEN(msg);
942 term_T *term = buffer->b_term;
943
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200944#ifdef WIN3264
945 /* Win32: Cannot redirect output of the job, intercept it here and write to
946 * the file. */
947 if (term->tl_out_fd != NULL)
948 {
949 ch_log(channel, "Writing %d bytes to output file", (int)len);
950 fwrite(msg, len, 1, term->tl_out_fd);
951 return;
952 }
953#endif
954
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200955 if (term->tl_vterm == NULL)
956 {
957 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
958 return;
959 }
960 ch_log(channel, "writing %d bytes to terminal", (int)len);
961 term_write_job_output(term, msg, len);
962
Bram Moolenaar13568252018-03-16 20:46:58 +0100963#ifdef FEAT_GUI
964 if (term->tl_system)
965 {
966 /* show system output, scrolling up the screen as needed */
967 update_system_term(term);
968 update_cursor(term, TRUE);
969 }
970 else
971#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200972 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
973 * contents, thus no screen update is needed. */
974 if (!term->tl_normal_mode)
975 {
976 /* TODO: only update once in a while. */
977 ch_log(term->tl_job->jv_channel, "updating screen");
978 if (buffer == curbuf)
979 {
980 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200981 /* update_screen() can be slow, check the terminal wasn't closed
982 * already */
983 if (buffer == curbuf && curbuf->b_term != NULL)
984 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200985 }
986 else
987 redraw_after_callback(TRUE);
988 }
989}
990
991/*
992 * Send a mouse position and click to the vterm
993 */
994 static int
995term_send_mouse(VTerm *vterm, int button, int pressed)
996{
997 VTermModifier mod = VTERM_MOD_NONE;
998
999 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001000 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001001 if (button != 0)
1002 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001003 return TRUE;
1004}
1005
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001006static int enter_mouse_col = -1;
1007static int enter_mouse_row = -1;
1008
1009/*
1010 * Handle a mouse click, drag or release.
1011 * Return TRUE when a mouse event is sent to the terminal.
1012 */
1013 static int
1014term_mouse_click(VTerm *vterm, int key)
1015{
1016#if defined(FEAT_CLIPBOARD)
1017 /* For modeless selection mouse drag and release events are ignored, unless
1018 * they are preceded with a mouse down event */
1019 static int ignore_drag_release = TRUE;
1020 VTermMouseState mouse_state;
1021
1022 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1023 if (mouse_state.flags == 0)
1024 {
1025 /* Terminal is not using the mouse, use modeless selection. */
1026 switch (key)
1027 {
1028 case K_LEFTDRAG:
1029 case K_LEFTRELEASE:
1030 case K_RIGHTDRAG:
1031 case K_RIGHTRELEASE:
1032 /* Ignore drag and release events when the button-down wasn't
1033 * seen before. */
1034 if (ignore_drag_release)
1035 {
1036 int save_mouse_col, save_mouse_row;
1037
1038 if (enter_mouse_col < 0)
1039 break;
1040
1041 /* mouse click in the window gave us focus, handle that
1042 * click now */
1043 save_mouse_col = mouse_col;
1044 save_mouse_row = mouse_row;
1045 mouse_col = enter_mouse_col;
1046 mouse_row = enter_mouse_row;
1047 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1048 mouse_col = save_mouse_col;
1049 mouse_row = save_mouse_row;
1050 }
1051 /* FALLTHROUGH */
1052 case K_LEFTMOUSE:
1053 case K_RIGHTMOUSE:
1054 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1055 ignore_drag_release = TRUE;
1056 else
1057 ignore_drag_release = FALSE;
1058 /* Should we call mouse_has() here? */
1059 if (clip_star.available)
1060 {
1061 int button, is_click, is_drag;
1062
1063 button = get_mouse_button(KEY2TERMCAP1(key),
1064 &is_click, &is_drag);
1065 if (mouse_model_popup() && button == MOUSE_LEFT
1066 && (mod_mask & MOD_MASK_SHIFT))
1067 {
1068 /* Translate shift-left to right button. */
1069 button = MOUSE_RIGHT;
1070 mod_mask &= ~MOD_MASK_SHIFT;
1071 }
1072 clip_modeless(button, is_click, is_drag);
1073 }
1074 break;
1075
1076 case K_MIDDLEMOUSE:
1077 if (clip_star.available)
1078 insert_reg('*', TRUE);
1079 break;
1080 }
1081 enter_mouse_col = -1;
1082 return FALSE;
1083 }
1084#endif
1085 enter_mouse_col = -1;
1086
1087 switch (key)
1088 {
1089 case K_LEFTMOUSE:
1090 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1091 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1092 case K_LEFTRELEASE:
1093 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1094 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1095 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1096 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1097 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1098 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1099 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1100 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1101 }
1102 return TRUE;
1103}
1104
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001105/*
1106 * Convert typed key "c" into bytes to send to the job.
1107 * Return the number of bytes in "buf".
1108 */
1109 static int
1110term_convert_key(term_T *term, int c, char *buf)
1111{
1112 VTerm *vterm = term->tl_vterm;
1113 VTermKey key = VTERM_KEY_NONE;
1114 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001115 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001116
1117 switch (c)
1118 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001119 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1120
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001121 /* don't use VTERM_KEY_BACKSPACE, it always
1122 * becomes 0x7f DEL */
1123 case K_BS: c = term_backspace_char; break;
1124
1125 case ESC: key = VTERM_KEY_ESCAPE; break;
1126 case K_DEL: key = VTERM_KEY_DEL; break;
1127 case K_DOWN: key = VTERM_KEY_DOWN; break;
1128 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1129 key = VTERM_KEY_DOWN; break;
1130 case K_END: key = VTERM_KEY_END; break;
1131 case K_S_END: mod = VTERM_MOD_SHIFT;
1132 key = VTERM_KEY_END; break;
1133 case K_C_END: mod = VTERM_MOD_CTRL;
1134 key = VTERM_KEY_END; break;
1135 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1136 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1137 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1138 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1139 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1140 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1141 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1142 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1143 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1144 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1145 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1146 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1147 case K_HOME: key = VTERM_KEY_HOME; break;
1148 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1149 key = VTERM_KEY_HOME; break;
1150 case K_C_HOME: mod = VTERM_MOD_CTRL;
1151 key = VTERM_KEY_HOME; break;
1152 case K_INS: key = VTERM_KEY_INS; break;
1153 case K_K0: key = VTERM_KEY_KP_0; break;
1154 case K_K1: key = VTERM_KEY_KP_1; break;
1155 case K_K2: key = VTERM_KEY_KP_2; break;
1156 case K_K3: key = VTERM_KEY_KP_3; break;
1157 case K_K4: key = VTERM_KEY_KP_4; break;
1158 case K_K5: key = VTERM_KEY_KP_5; break;
1159 case K_K6: key = VTERM_KEY_KP_6; break;
1160 case K_K7: key = VTERM_KEY_KP_7; break;
1161 case K_K8: key = VTERM_KEY_KP_8; break;
1162 case K_K9: key = VTERM_KEY_KP_9; break;
1163 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1164 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1165 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1166 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1167 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1168 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1169 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1170 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1171 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1172 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1173 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1174 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1175 case K_LEFT: key = VTERM_KEY_LEFT; break;
1176 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1177 key = VTERM_KEY_LEFT; break;
1178 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1179 key = VTERM_KEY_LEFT; break;
1180 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1181 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1182 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1183 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1184 key = VTERM_KEY_RIGHT; break;
1185 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1186 key = VTERM_KEY_RIGHT; break;
1187 case K_UP: key = VTERM_KEY_UP; break;
1188 case K_S_UP: mod = VTERM_MOD_SHIFT;
1189 key = VTERM_KEY_UP; break;
1190 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001191 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1192 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001193
Bram Moolenaara42ad572017-11-16 13:08:04 +01001194 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1195 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001196 case K_MOUSELEFT: /* TODO */ return 0;
1197 case K_MOUSERIGHT: /* TODO */ return 0;
1198
1199 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001200 case K_LEFTMOUSE_NM:
1201 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001202 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001203 case K_LEFTRELEASE_NM:
1204 case K_MOUSEMOVE:
1205 case K_MIDDLEMOUSE:
1206 case K_MIDDLEDRAG:
1207 case K_MIDDLERELEASE:
1208 case K_RIGHTMOUSE:
1209 case K_RIGHTDRAG:
1210 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1211 return 0;
1212 other = TRUE;
1213 break;
1214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001215 case K_X1MOUSE: /* TODO */ return 0;
1216 case K_X1DRAG: /* TODO */ return 0;
1217 case K_X1RELEASE: /* TODO */ return 0;
1218 case K_X2MOUSE: /* TODO */ return 0;
1219 case K_X2DRAG: /* TODO */ return 0;
1220 case K_X2RELEASE: /* TODO */ return 0;
1221
1222 case K_IGNORE: return 0;
1223 case K_NOP: return 0;
1224 case K_UNDO: return 0;
1225 case K_HELP: return 0;
1226 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1227 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1228 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1229 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1230 case K_SELECT: return 0;
1231#ifdef FEAT_GUI
1232 case K_VER_SCROLLBAR: return 0;
1233 case K_HOR_SCROLLBAR: return 0;
1234#endif
1235#ifdef FEAT_GUI_TABLINE
1236 case K_TABLINE: return 0;
1237 case K_TABMENU: return 0;
1238#endif
1239#ifdef FEAT_NETBEANS_INTG
1240 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1241#endif
1242#ifdef FEAT_DND
1243 case K_DROP: return 0;
1244#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001245 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001246 case K_PS: vterm_keyboard_start_paste(vterm);
1247 other = TRUE;
1248 break;
1249 case K_PE: vterm_keyboard_end_paste(vterm);
1250 other = TRUE;
1251 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001252 }
1253
1254 /*
1255 * Convert special keys to vterm keys:
1256 * - Write keys to vterm: vterm_keyboard_key()
1257 * - Write output to channel.
1258 * TODO: use mod_mask
1259 */
1260 if (key != VTERM_KEY_NONE)
1261 /* Special key, let vterm convert it. */
1262 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001263 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001264 /* Normal character, let vterm convert it. */
1265 vterm_keyboard_unichar(vterm, c, mod);
1266
1267 /* Read back the converted escape sequence. */
1268 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1269}
1270
1271/*
1272 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001273 * If "check_job_status" is TRUE update the job status.
1274 */
1275 static int
1276term_job_running_check(term_T *term, int check_job_status)
1277{
1278 /* Also consider the job finished when the channel is closed, to avoid a
1279 * race condition when updating the title. */
1280 if (term != NULL
1281 && term->tl_job != NULL
1282 && channel_is_open(term->tl_job->jv_channel))
1283 {
1284 if (check_job_status)
1285 job_status(term->tl_job);
1286 return (term->tl_job->jv_status == JOB_STARTED
1287 || term->tl_job->jv_channel->ch_keep_open);
1288 }
1289 return FALSE;
1290}
1291
1292/*
1293 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 */
1295 int
1296term_job_running(term_T *term)
1297{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001298 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001299}
1300
1301/*
1302 * Return TRUE if "term" has an active channel and used ":term NONE".
1303 */
1304 int
1305term_none_open(term_T *term)
1306{
1307 /* Also consider the job finished when the channel is closed, to avoid a
1308 * race condition when updating the title. */
1309 return term != NULL
1310 && term->tl_job != NULL
1311 && channel_is_open(term->tl_job->jv_channel)
1312 && term->tl_job->jv_channel->ch_keep_open;
1313}
1314
1315/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001316 * Used when exiting: kill the job in "buf" if so desired.
1317 * Return OK when the job finished.
1318 * Return FAIL when the job is still running.
1319 */
1320 int
1321term_try_stop_job(buf_T *buf)
1322{
1323 int count;
1324 char *how = (char *)buf->b_term->tl_kill;
1325
1326#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1327 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1328 {
1329 char_u buff[DIALOG_MSG_SIZE];
1330 int ret;
1331
1332 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1333 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1334 if (ret == VIM_YES)
1335 how = "kill";
1336 else if (ret == VIM_CANCEL)
1337 return FAIL;
1338 }
1339#endif
1340 if (how == NULL || *how == NUL)
1341 return FAIL;
1342
1343 job_stop(buf->b_term->tl_job, NULL, how);
1344
1345 /* wait for up to a second for the job to die */
1346 for (count = 0; count < 100; ++count)
1347 {
1348 /* buffer, terminal and job may be cleaned up while waiting */
1349 if (!buf_valid(buf)
1350 || buf->b_term == NULL
1351 || buf->b_term->tl_job == NULL)
1352 return OK;
1353
1354 /* call job_status() to update jv_status */
1355 job_status(buf->b_term->tl_job);
1356 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1357 return OK;
1358 ui_delay(10L, FALSE);
1359 mch_check_messages();
1360 parse_queued_messages();
1361 }
1362 return FAIL;
1363}
1364
1365/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 * Add the last line of the scrollback buffer to the buffer in the window.
1367 */
1368 static void
1369add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1370{
1371 buf_T *buf = term->tl_buffer;
1372 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1373 linenr_T lnum = buf->b_ml.ml_line_count;
1374
1375#ifdef WIN3264
1376 if (!enc_utf8 && enc_codepage > 0)
1377 {
1378 WCHAR *ret = NULL;
1379 int length = 0;
1380
1381 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1382 &ret, &length);
1383 if (ret != NULL)
1384 {
1385 WideCharToMultiByte_alloc(enc_codepage, 0,
1386 ret, length, (char **)&text, &len, 0, 0);
1387 vim_free(ret);
1388 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1389 vim_free(text);
1390 }
1391 }
1392 else
1393#endif
1394 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1395 if (empty)
1396 {
1397 /* Delete the empty line that was in the empty buffer. */
1398 curbuf = buf;
1399 ml_delete(1, FALSE);
1400 curbuf = curwin->w_buffer;
1401 }
1402}
1403
1404 static void
1405cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1406{
1407 attr->width = cell->width;
1408 attr->attrs = cell->attrs;
1409 attr->fg = cell->fg;
1410 attr->bg = cell->bg;
1411}
1412
1413 static int
1414equal_celattr(cellattr_T *a, cellattr_T *b)
1415{
1416 /* Comparing the colors should be sufficient. */
1417 return a->fg.red == b->fg.red
1418 && a->fg.green == b->fg.green
1419 && a->fg.blue == b->fg.blue
1420 && a->bg.red == b->bg.red
1421 && a->bg.green == b->bg.green
1422 && a->bg.blue == b->bg.blue;
1423}
1424
Bram Moolenaard96ff162018-02-18 22:13:29 +01001425/*
1426 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1427 * line at this position. Otherwise at the end.
1428 */
1429 static int
1430add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1431{
1432 if (ga_grow(&term->tl_scrollback, 1) == OK)
1433 {
1434 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1435 + term->tl_scrollback.ga_len;
1436
1437 if (lnum > 0)
1438 {
1439 int i;
1440
1441 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1442 {
1443 *line = *(line - 1);
1444 --line;
1445 }
1446 }
1447 line->sb_cols = 0;
1448 line->sb_cells = NULL;
1449 line->sb_fill_attr = *fill_attr;
1450 ++term->tl_scrollback.ga_len;
1451 return OK;
1452 }
1453 return FALSE;
1454}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001455
1456/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001457 * Remove the terminal contents from the scrollback and the buffer.
1458 * Used before adding a new scrollback line or updating the buffer for lines
1459 * displayed in the terminal.
1460 */
1461 static void
1462cleanup_scrollback(term_T *term)
1463{
1464 sb_line_T *line;
1465 garray_T *gap;
1466
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001467 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001468 gap = &term->tl_scrollback;
1469 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1470 && gap->ga_len > 0)
1471 {
1472 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1473 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1474 vim_free(line->sb_cells);
1475 --gap->ga_len;
1476 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001477 curbuf = curwin->w_buffer;
1478 if (curbuf == term->tl_buffer)
1479 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001480}
1481
1482/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001483 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001484 */
1485 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001486update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001488 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001489 int len;
1490 int lines_skipped = 0;
1491 VTermPos pos;
1492 VTermScreenCell cell;
1493 cellattr_T fill_attr, new_fill_attr;
1494 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001495
1496 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1497 "Adding terminal window snapshot to buffer");
1498
1499 /* First remove the lines that were appended before, they might be
1500 * outdated. */
1501 cleanup_scrollback(term);
1502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001503 screen = vterm_obtain_screen(term->tl_vterm);
1504 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001505 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1506 {
1507 len = 0;
1508 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1509 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1510 && cell.chars[0] != NUL)
1511 {
1512 len = pos.col + 1;
1513 new_fill_attr = term->tl_default_color;
1514 }
1515 else
1516 /* Assume the last attr is the filler attr. */
1517 cell2cellattr(&cell, &new_fill_attr);
1518
1519 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1520 ++lines_skipped;
1521 else
1522 {
1523 while (lines_skipped > 0)
1524 {
1525 /* Line was skipped, add an empty line. */
1526 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001527 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001528 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001529 }
1530
1531 if (len == 0)
1532 p = NULL;
1533 else
1534 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1535 if ((p != NULL || len == 0)
1536 && ga_grow(&term->tl_scrollback, 1) == OK)
1537 {
1538 garray_T ga;
1539 int width;
1540 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1541 + term->tl_scrollback.ga_len;
1542
1543 ga_init2(&ga, 1, 100);
1544 for (pos.col = 0; pos.col < len; pos.col += width)
1545 {
1546 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1547 {
1548 width = 1;
1549 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1550 if (ga_grow(&ga, 1) == OK)
1551 ga.ga_len += utf_char2bytes(' ',
1552 (char_u *)ga.ga_data + ga.ga_len);
1553 }
1554 else
1555 {
1556 width = cell.width;
1557
1558 cell2cellattr(&cell, &p[pos.col]);
1559
1560 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1561 {
1562 int i;
1563 int c;
1564
1565 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1566 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1567 (char_u *)ga.ga_data + ga.ga_len);
1568 }
1569 }
1570 }
1571 line->sb_cols = len;
1572 line->sb_cells = p;
1573 line->sb_fill_attr = new_fill_attr;
1574 fill_attr = new_fill_attr;
1575 ++term->tl_scrollback.ga_len;
1576
1577 if (ga_grow(&ga, 1) == FAIL)
1578 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1579 else
1580 {
1581 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1582 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1583 }
1584 ga_clear(&ga);
1585 }
1586 else
1587 vim_free(p);
1588 }
1589 }
1590
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001591 term->tl_dirty_snapshot = FALSE;
1592#ifdef FEAT_TIMERS
1593 term->tl_timer_set = FALSE;
1594#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001595}
1596
1597/*
1598 * If needed, add the current lines of the terminal to scrollback and to the
1599 * buffer. Called after the job has ended and when switching to
1600 * Terminal-Normal mode.
1601 * When "redraw" is TRUE redraw the windows that show the terminal.
1602 */
1603 static void
1604may_move_terminal_to_buffer(term_T *term, int redraw)
1605{
1606 win_T *wp;
1607
1608 if (term->tl_vterm == NULL)
1609 return;
1610
1611 /* Update the snapshot only if something changes or the buffer does not
1612 * have all the lines. */
1613 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1614 <= term->tl_scrollback_scrolled)
1615 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001616
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617 /* Obtain the current background color. */
1618 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1619 &term->tl_default_color.fg, &term->tl_default_color.bg);
1620
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001621 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001622 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001623 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001624 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001626 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1627 wp->w_cursor.col = 0;
1628 wp->w_valid = 0;
1629 if (wp->w_cursor.lnum >= wp->w_height)
1630 {
1631 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001632
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001633 if (wp->w_topline < min_topline)
1634 wp->w_topline = min_topline;
1635 }
1636 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001638 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001639}
1640
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001641#if defined(FEAT_TIMERS) || defined(PROTO)
1642/*
1643 * Check if any terminal timer expired. If so, copy text from the terminal to
1644 * the buffer.
1645 * Return the time until the next timer will expire.
1646 */
1647 int
1648term_check_timers(int next_due_arg, proftime_T *now)
1649{
1650 term_T *term;
1651 int next_due = next_due_arg;
1652
1653 for (term = first_term; term != NULL; term = term->tl_next)
1654 {
1655 if (term->tl_timer_set && !term->tl_normal_mode)
1656 {
1657 long this_due = proftime_time_left(&term->tl_timer_due, now);
1658
1659 if (this_due <= 1)
1660 {
1661 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001662 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001663 }
1664 else if (next_due == -1 || next_due > this_due)
1665 next_due = this_due;
1666 }
1667 }
1668
1669 return next_due;
1670}
1671#endif
1672
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 static void
1674set_terminal_mode(term_T *term, int normal_mode)
1675{
1676 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001677 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001678 if (term->tl_buffer == curbuf)
1679 maketitle();
1680}
1681
1682/*
1683 * Called after the job if finished and Terminal mode is not active:
1684 * Move the vterm contents into the scrollback buffer and free the vterm.
1685 */
1686 static void
1687cleanup_vterm(term_T *term)
1688{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001689 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001690 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001691 term_free_vterm(term);
1692 set_terminal_mode(term, FALSE);
1693}
1694
1695/*
1696 * Switch from Terminal-Job mode to Terminal-Normal mode.
1697 * Suspends updating the terminal window.
1698 */
1699 static void
1700term_enter_normal_mode(void)
1701{
1702 term_T *term = curbuf->b_term;
1703
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001704 set_terminal_mode(term, TRUE);
1705
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001707 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001708
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001709 /* Move the window cursor to the position of the cursor in the
1710 * terminal. */
1711 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1712 + term->tl_cursor_pos.row + 1;
1713 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001714 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1715 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001716
1717 /* Display the same lines as in the terminal. */
1718 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1719}
1720
1721/*
1722 * Returns TRUE if the current window contains a terminal and we are in
1723 * Terminal-Normal mode.
1724 */
1725 int
1726term_in_normal_mode(void)
1727{
1728 term_T *term = curbuf->b_term;
1729
1730 return term != NULL && term->tl_normal_mode;
1731}
1732
1733/*
1734 * Switch from Terminal-Normal mode to Terminal-Job mode.
1735 * Restores updating the terminal window.
1736 */
1737 void
1738term_enter_job_mode()
1739{
1740 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001741
1742 set_terminal_mode(term, FALSE);
1743
1744 if (term->tl_channel_closed)
1745 cleanup_vterm(term);
1746 redraw_buf_and_status_later(curbuf, NOT_VALID);
1747}
1748
1749/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001750 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751 * Note: while waiting a terminal may be closed and freed if the channel is
1752 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001753 */
1754 static int
1755term_vgetc()
1756{
1757 int c;
1758 int save_State = State;
1759
1760 State = TERMINAL;
1761 got_int = FALSE;
1762#ifdef WIN3264
1763 ctrl_break_was_pressed = FALSE;
1764#endif
1765 c = vgetc();
1766 got_int = FALSE;
1767 State = save_State;
1768 return c;
1769}
1770
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001771static int mouse_was_outside = FALSE;
1772
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001773/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774 * Send keys to terminal.
1775 * Return FAIL when the key needs to be handled in Normal mode.
1776 * Return OK when the key was dropped or sent to the terminal.
1777 */
1778 int
1779send_keys_to_term(term_T *term, int c, int typed)
1780{
1781 char msg[KEY_BUF_LEN];
1782 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001783 int dragging_outside = FALSE;
1784
1785 /* Catch keys that need to be handled as in Normal mode. */
1786 switch (c)
1787 {
1788 case NUL:
1789 case K_ZERO:
1790 if (typed)
1791 stuffcharReadbuff(c);
1792 return FAIL;
1793
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001794 case K_TABLINE:
1795 stuffcharReadbuff(c);
1796 return FAIL;
1797
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001798 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001799 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001800 return FAIL;
1801
1802 case K_LEFTDRAG:
1803 case K_MIDDLEDRAG:
1804 case K_RIGHTDRAG:
1805 case K_X1DRAG:
1806 case K_X2DRAG:
1807 dragging_outside = mouse_was_outside;
1808 /* FALLTHROUGH */
1809 case K_LEFTMOUSE:
1810 case K_LEFTMOUSE_NM:
1811 case K_LEFTRELEASE:
1812 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001813 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001814 case K_MIDDLEMOUSE:
1815 case K_MIDDLERELEASE:
1816 case K_RIGHTMOUSE:
1817 case K_RIGHTRELEASE:
1818 case K_X1MOUSE:
1819 case K_X1RELEASE:
1820 case K_X2MOUSE:
1821 case K_X2RELEASE:
1822
1823 case K_MOUSEUP:
1824 case K_MOUSEDOWN:
1825 case K_MOUSELEFT:
1826 case K_MOUSERIGHT:
1827 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001828 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001829 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001830 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001831 || dragging_outside)
1832 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001833 /* click or scroll outside the current window or on status line
1834 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001835 if (typed)
1836 {
1837 stuffcharReadbuff(c);
1838 mouse_was_outside = TRUE;
1839 }
1840 return FAIL;
1841 }
1842 }
1843 if (typed)
1844 mouse_was_outside = FALSE;
1845
1846 /* Convert the typed key to a sequence of bytes for the job. */
1847 len = term_convert_key(term, c, msg);
1848 if (len > 0)
1849 /* TODO: if FAIL is returned, stop? */
1850 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1851 (char_u *)msg, (int)len, NULL);
1852
1853 return OK;
1854}
1855
1856 static void
1857position_cursor(win_T *wp, VTermPos *pos)
1858{
1859 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1860 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1861 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1862}
1863
1864/*
1865 * Handle CTRL-W "": send register contents to the job.
1866 */
1867 static void
1868term_paste_register(int prev_c UNUSED)
1869{
1870 int c;
1871 list_T *l;
1872 listitem_T *item;
1873 long reglen = 0;
1874 int type;
1875
1876#ifdef FEAT_CMDL_INFO
1877 if (add_to_showcmd(prev_c))
1878 if (add_to_showcmd('"'))
1879 out_flush();
1880#endif
1881 c = term_vgetc();
1882#ifdef FEAT_CMDL_INFO
1883 clear_showcmd();
1884#endif
1885 if (!term_use_loop())
1886 /* job finished while waiting for a character */
1887 return;
1888
1889 /* CTRL-W "= prompt for expression to evaluate. */
1890 if (c == '=' && get_expr_register() != '=')
1891 return;
1892 if (!term_use_loop())
1893 /* job finished while waiting for a character */
1894 return;
1895
1896 l = (list_T *)get_reg_contents(c, GREG_LIST);
1897 if (l != NULL)
1898 {
1899 type = get_reg_type(c, &reglen);
1900 for (item = l->lv_first; item != NULL; item = item->li_next)
1901 {
1902 char_u *s = get_tv_string(&item->li_tv);
1903#ifdef WIN3264
1904 char_u *tmp = s;
1905
1906 if (!enc_utf8 && enc_codepage > 0)
1907 {
1908 WCHAR *ret = NULL;
1909 int length = 0;
1910
1911 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1912 (int)STRLEN(s), &ret, &length);
1913 if (ret != NULL)
1914 {
1915 WideCharToMultiByte_alloc(CP_UTF8, 0,
1916 ret, length, (char **)&s, &length, 0, 0);
1917 vim_free(ret);
1918 }
1919 }
1920#endif
1921 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1922 s, (int)STRLEN(s), NULL);
1923#ifdef WIN3264
1924 if (tmp != s)
1925 vim_free(s);
1926#endif
1927
1928 if (item->li_next != NULL || type == MLINE)
1929 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1930 (char_u *)"\r", 1, NULL);
1931 }
1932 list_free(l);
1933 }
1934}
1935
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001936/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001937 * Return TRUE when waiting for a character in the terminal, the cursor of the
1938 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001939 */
1940 int
1941terminal_is_active()
1942{
1943 return in_terminal_loop != NULL;
1944}
1945
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001946#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001947 cursorentry_T *
1948term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1949{
1950 term_T *term = in_terminal_loop;
1951 static cursorentry_T entry;
1952
1953 vim_memset(&entry, 0, sizeof(entry));
1954 entry.shape = entry.mshape =
1955 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1956 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1957 SHAPE_BLOCK;
1958 entry.percentage = 20;
1959 if (term->tl_cursor_blink)
1960 {
1961 entry.blinkwait = 700;
1962 entry.blinkon = 400;
1963 entry.blinkoff = 250;
1964 }
1965 *fg = gui.back_pixel;
1966 if (term->tl_cursor_color == NULL)
1967 *bg = gui.norm_pixel;
1968 else
1969 *bg = color_name2handle(term->tl_cursor_color);
1970 entry.name = "n";
1971 entry.used_for = SHAPE_CURSOR;
1972
1973 return &entry;
1974}
1975#endif
1976
Bram Moolenaard317b382018-02-08 22:33:31 +01001977 static void
1978may_output_cursor_props(void)
1979{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001980 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01001981 || last_set_cursor_shape != desired_cursor_shape
1982 || last_set_cursor_blink != desired_cursor_blink)
1983 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001984 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01001985 last_set_cursor_shape = desired_cursor_shape;
1986 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02001987 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01001988 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1989 /* this will restore the initial cursor style, if possible */
1990 ui_cursor_shape_forced(TRUE);
1991 else
1992 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1993 }
1994}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001995
Bram Moolenaard317b382018-02-08 22:33:31 +01001996/*
1997 * Set the cursor color and shape, if not last set to these.
1998 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001999 static void
2000may_set_cursor_props(term_T *term)
2001{
2002#ifdef FEAT_GUI
2003 /* For the GUI the cursor properties are obtained with
2004 * term_get_cursor_shape(). */
2005 if (gui.in_use)
2006 return;
2007#endif
2008 if (in_terminal_loop == term)
2009 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002010 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002011 desired_cursor_shape = term->tl_cursor_shape;
2012 desired_cursor_blink = term->tl_cursor_blink;
2013 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014 }
2015}
2016
Bram Moolenaard317b382018-02-08 22:33:31 +01002017/*
2018 * Reset the desired cursor properties and restore them when needed.
2019 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002020 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002021prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022{
2023#ifdef FEAT_GUI
2024 if (gui.in_use)
2025 return;
2026#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002027 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002028 desired_cursor_shape = -1;
2029 desired_cursor_blink = -1;
2030 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002031}
2032
2033/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002034 * Returns TRUE if the current window contains a terminal and we are sending
2035 * keys to the job.
2036 * If "check_job_status" is TRUE update the job status.
2037 */
2038 static int
2039term_use_loop_check(int check_job_status)
2040{
2041 term_T *term = curbuf->b_term;
2042
2043 return term != NULL
2044 && !term->tl_normal_mode
2045 && term->tl_vterm != NULL
2046 && term_job_running_check(term, check_job_status);
2047}
2048
2049/*
2050 * Returns TRUE if the current window contains a terminal and we are sending
2051 * keys to the job.
2052 */
2053 int
2054term_use_loop(void)
2055{
2056 return term_use_loop_check(FALSE);
2057}
2058
2059/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002060 * Called when entering a window with the mouse. If this is a terminal window
2061 * we may want to change state.
2062 */
2063 void
2064term_win_entered()
2065{
2066 term_T *term = curbuf->b_term;
2067
2068 if (term != NULL)
2069 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002070 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002071 {
2072 reset_VIsual_and_resel();
2073 if (State & INSERT)
2074 stop_insert_mode = TRUE;
2075 }
2076 mouse_was_outside = FALSE;
2077 enter_mouse_col = mouse_col;
2078 enter_mouse_row = mouse_row;
2079 }
2080}
2081
2082/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002083 * Wait for input and send it to the job.
2084 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2085 * when there is no more typahead.
2086 * Return when the start of a CTRL-W command is typed or anything else that
2087 * should be handled as a Normal mode command.
2088 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2089 * the terminal was closed.
2090 */
2091 int
2092terminal_loop(int blocking)
2093{
2094 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002095 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002096 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002097#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002098 int tty_fd = curbuf->b_term->tl_job->jv_channel
2099 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002100#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002101 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102
2103 /* Remember the terminal we are sending keys to. However, the terminal
2104 * might be closed while waiting for a character, e.g. typing "exit" in a
2105 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2106 * stored reference. */
2107 in_terminal_loop = curbuf->b_term;
2108
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002109 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002110 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002111 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2112 may_set_cursor_props(curbuf->b_term);
2113
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002114 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002115 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002116#ifdef FEAT_GUI
2117 if (!curbuf->b_term->tl_system)
2118#endif
2119 /* TODO: skip screen update when handling a sequence of keys. */
2120 /* Repeat redrawing in case a message is received while redrawing.
2121 */
2122 while (must_redraw != 0)
2123 if (update_screen(0) == FAIL)
2124 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002125 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002126 /* job finished while redrawing */
2127 break;
2128
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002129 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002130 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131
2132 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002133 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002134 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002135 /* Job finished while waiting for a character. Push back the
2136 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002137 if (c != K_IGNORE)
2138 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002139 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002140 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 if (c == K_IGNORE)
2142 continue;
2143
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002144#ifdef UNIX
2145 /*
2146 * The shell or another program may change the tty settings. Getting
2147 * them for every typed character is a bit of overhead, but it's needed
2148 * for the first character typed, e.g. when Vim starts in a shell.
2149 */
2150 if (isatty(tty_fd))
2151 {
2152 ttyinfo_T info;
2153
2154 /* Get the current backspace character of the pty. */
2155 if (get_tty_info(tty_fd, &info) == OK)
2156 term_backspace_char = info.backspace;
2157 }
2158#endif
2159
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002160#ifdef WIN3264
2161 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2162 * Use CTRL-BREAK to kill the job. */
2163 if (ctrl_break_was_pressed)
2164 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2165#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002166 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002167 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002168 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002169#ifdef FEAT_GUI
2170 && !curbuf->b_term->tl_system
2171#endif
2172 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002173 {
2174 int prev_c = c;
2175
2176#ifdef FEAT_CMDL_INFO
2177 if (add_to_showcmd(c))
2178 out_flush();
2179#endif
2180 c = term_vgetc();
2181#ifdef FEAT_CMDL_INFO
2182 clear_showcmd();
2183#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002184 if (!term_use_loop_check(TRUE)
2185 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 /* job finished while waiting for a character */
2187 break;
2188
2189 if (prev_c == Ctrl_BSL)
2190 {
2191 if (c == Ctrl_N)
2192 {
2193 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2194 term_enter_normal_mode();
2195 ret = FAIL;
2196 goto theend;
2197 }
2198 /* Send both keys to the terminal. */
2199 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2200 }
2201 else if (c == Ctrl_C)
2202 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002203 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2205 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002206 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002207 {
2208 /* "CTRL-W .": send CTRL-W to the job */
2209 c = Ctrl_W;
2210 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002211 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002212 {
2213 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2214 c = Ctrl_BSL;
2215 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216 else if (c == 'N')
2217 {
2218 /* CTRL-W N : go to Terminal-Normal mode. */
2219 term_enter_normal_mode();
2220 ret = FAIL;
2221 goto theend;
2222 }
2223 else if (c == '"')
2224 {
2225 term_paste_register(prev_c);
2226 continue;
2227 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002228 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 {
2230 stuffcharReadbuff(Ctrl_W);
2231 stuffcharReadbuff(c);
2232 ret = OK;
2233 goto theend;
2234 }
2235 }
2236# ifdef WIN3264
2237 if (!enc_utf8 && has_mbyte && c >= 0x80)
2238 {
2239 WCHAR wc;
2240 char_u mb[3];
2241
2242 mb[0] = (unsigned)c >> 8;
2243 mb[1] = c;
2244 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2245 c = wc;
2246 }
2247# endif
2248 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2249 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002250 if (c == K_MOUSEMOVE)
2251 /* We are sure to come back here, don't reset the cursor color
2252 * and shape to avoid flickering. */
2253 restore_cursor = FALSE;
2254
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002255 ret = OK;
2256 goto theend;
2257 }
2258 }
2259 ret = FAIL;
2260
2261theend:
2262 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002263 if (restore_cursor)
2264 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002265
2266 /* Move a snapshot of the screen contents to the buffer, so that completion
2267 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002268 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2269 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002270
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271 return ret;
2272}
2273
2274/*
2275 * Called when a job has finished.
2276 * This updates the title and status, but does not close the vterm, because
2277 * there might still be pending output in the channel.
2278 */
2279 void
2280term_job_ended(job_T *job)
2281{
2282 term_T *term;
2283 int did_one = FALSE;
2284
2285 for (term = first_term; term != NULL; term = term->tl_next)
2286 if (term->tl_job == job)
2287 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002288 VIM_CLEAR(term->tl_title);
2289 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002290 redraw_buf_and_status_later(term->tl_buffer, VALID);
2291 did_one = TRUE;
2292 }
2293 if (did_one)
2294 redraw_statuslines();
2295 if (curbuf->b_term != NULL)
2296 {
2297 if (curbuf->b_term->tl_job == job)
2298 maketitle();
2299 update_cursor(curbuf->b_term, TRUE);
2300 }
2301}
2302
2303 static void
2304may_toggle_cursor(term_T *term)
2305{
2306 if (in_terminal_loop == term)
2307 {
2308 if (term->tl_cursor_visible)
2309 cursor_on();
2310 else
2311 cursor_off();
2312 }
2313}
2314
2315/*
2316 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002317 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002318 */
2319 static int
2320color2index(VTermColor *color, int fg, int *boldp)
2321{
2322 int red = color->red;
2323 int blue = color->blue;
2324 int green = color->green;
2325
Bram Moolenaar46359e12017-11-29 22:33:38 +01002326 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002327 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002328 /* First 16 colors and default: use the ANSI index, because these
2329 * colors can be redefined. */
2330 if (t_colors >= 16)
2331 return color->ansi_index;
2332 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002333 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002334 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002335 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002336 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2337 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2338 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002339 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002340 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2341 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2342 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2343 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2344 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2345 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2346 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2347 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2348 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2349 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2350 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 }
2352 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002353
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 if (t_colors >= 256)
2355 {
2356 if (red == blue && red == green)
2357 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002358 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002360 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2361 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2362 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002363 int i;
2364
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002365 if (red < 5)
2366 return 17; /* 00/00/00 */
2367 if (red > 245) /* ff/ff/ff */
2368 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 for (i = 0; i < 23; ++i)
2370 if (red < cutoff[i])
2371 return i + 233;
2372 return 256;
2373 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002374 {
2375 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2376 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002378 /* 216-color cube */
2379 for (ri = 0; ri < 5; ++ri)
2380 if (red < cutoff[ri])
2381 break;
2382 for (gi = 0; gi < 5; ++gi)
2383 if (green < cutoff[gi])
2384 break;
2385 for (bi = 0; bi < 5; ++bi)
2386 if (blue < cutoff[bi])
2387 break;
2388 return 17 + ri * 36 + gi * 6 + bi;
2389 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390 }
2391 return 0;
2392}
2393
2394/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002395 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 */
2397 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002398vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002399{
2400 int attr = 0;
2401
2402 if (cellattrs.bold)
2403 attr |= HL_BOLD;
2404 if (cellattrs.underline)
2405 attr |= HL_UNDERLINE;
2406 if (cellattrs.italic)
2407 attr |= HL_ITALIC;
2408 if (cellattrs.strike)
2409 attr |= HL_STRIKETHROUGH;
2410 if (cellattrs.reverse)
2411 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002412 return attr;
2413}
2414
2415/*
2416 * Store Vterm attributes in "cell" from highlight flags.
2417 */
2418 static void
2419hl2vtermAttr(int attr, cellattr_T *cell)
2420{
2421 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2422 if (attr & HL_BOLD)
2423 cell->attrs.bold = 1;
2424 if (attr & HL_UNDERLINE)
2425 cell->attrs.underline = 1;
2426 if (attr & HL_ITALIC)
2427 cell->attrs.italic = 1;
2428 if (attr & HL_STRIKETHROUGH)
2429 cell->attrs.strike = 1;
2430 if (attr & HL_INVERSE)
2431 cell->attrs.reverse = 1;
2432}
2433
2434/*
2435 * Convert the attributes of a vterm cell into an attribute index.
2436 */
2437 static int
2438cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2439{
2440 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441
2442#ifdef FEAT_GUI
2443 if (gui.in_use)
2444 {
2445 guicolor_T fg, bg;
2446
2447 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2448 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2449 return get_gui_attr_idx(attr, fg, bg);
2450 }
2451 else
2452#endif
2453#ifdef FEAT_TERMGUICOLORS
2454 if (p_tgc)
2455 {
2456 guicolor_T fg, bg;
2457
2458 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2459 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2460
2461 return get_tgc_attr_idx(attr, fg, bg);
2462 }
2463 else
2464#endif
2465 {
2466 int bold = MAYBE;
2467 int fg = color2index(&cellfg, TRUE, &bold);
2468 int bg = color2index(&cellbg, FALSE, &bold);
2469
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002470 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002471 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002472 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002473 if (fg == 0 && term_default_cterm_fg >= 0)
2474 fg = term_default_cterm_fg + 1;
2475 if (bg == 0 && term_default_cterm_bg >= 0)
2476 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002477 }
2478
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 /* with 8 colors set the bold attribute to get a bright foreground */
2480 if (bold == TRUE)
2481 attr |= HL_BOLD;
2482 return get_cterm_attr_idx(attr, fg, bg);
2483 }
2484 return 0;
2485}
2486
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002487 static void
2488set_dirty_snapshot(term_T *term)
2489{
2490 term->tl_dirty_snapshot = TRUE;
2491#ifdef FEAT_TIMERS
2492 if (!term->tl_normal_mode)
2493 {
2494 /* Update the snapshot after 100 msec of not getting updates. */
2495 profile_setlimit(100L, &term->tl_timer_due);
2496 term->tl_timer_set = TRUE;
2497 }
2498#endif
2499}
2500
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002501 static int
2502handle_damage(VTermRect rect, void *user)
2503{
2504 term_T *term = (term_T *)user;
2505
2506 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2507 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002508 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002509 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 return 1;
2511}
2512
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002513 static void
2514term_scroll_up(term_T *term, int start_row, int count)
2515{
2516 win_T *wp;
2517 VTermColor fg, bg;
2518 VTermScreenCellAttrs attr;
2519 int clear_attr;
2520
2521 /* Set the color to clear lines with. */
2522 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2523 &fg, &bg);
2524 vim_memset(&attr, 0, sizeof(attr));
2525 clear_attr = cell2attr(attr, fg, bg);
2526
2527 FOR_ALL_WINDOWS(wp)
2528 {
2529 if (wp->w_buffer == term->tl_buffer)
2530 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2531 }
2532}
2533
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 static int
2535handle_moverect(VTermRect dest, VTermRect src, void *user)
2536{
2537 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002538 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
2540 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002541 * redrawing the text. But avoid doing this multiple times, postpone until
2542 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 if (dest.start_col == src.start_col
2544 && dest.end_col == src.end_col
2545 && dest.start_row < src.start_row)
2546 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002547 if (dest.start_row == 0)
2548 term->tl_postponed_scroll += count;
2549 else
2550 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002552
2553 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2554 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002555 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002556
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002557 /* Note sure if the scrolling will work correctly, let's do a complete
2558 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559 redraw_buf_later(term->tl_buffer, NOT_VALID);
2560 return 1;
2561}
2562
2563 static int
2564handle_movecursor(
2565 VTermPos pos,
2566 VTermPos oldpos UNUSED,
2567 int visible,
2568 void *user)
2569{
2570 term_T *term = (term_T *)user;
2571 win_T *wp;
2572
2573 term->tl_cursor_pos = pos;
2574 term->tl_cursor_visible = visible;
2575
2576 FOR_ALL_WINDOWS(wp)
2577 {
2578 if (wp->w_buffer == term->tl_buffer)
2579 position_cursor(wp, &pos);
2580 }
2581 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2582 {
2583 may_toggle_cursor(term);
2584 update_cursor(term, term->tl_cursor_visible);
2585 }
2586
2587 return 1;
2588}
2589
2590 static int
2591handle_settermprop(
2592 VTermProp prop,
2593 VTermValue *value,
2594 void *user)
2595{
2596 term_T *term = (term_T *)user;
2597
2598 switch (prop)
2599 {
2600 case VTERM_PROP_TITLE:
2601 vim_free(term->tl_title);
2602 /* a blank title isn't useful, make it empty, so that "running" is
2603 * displayed */
2604 if (*skipwhite((char_u *)value->string) == NUL)
2605 term->tl_title = NULL;
2606#ifdef WIN3264
2607 else if (!enc_utf8 && enc_codepage > 0)
2608 {
2609 WCHAR *ret = NULL;
2610 int length = 0;
2611
2612 MultiByteToWideChar_alloc(CP_UTF8, 0,
2613 (char*)value->string, (int)STRLEN(value->string),
2614 &ret, &length);
2615 if (ret != NULL)
2616 {
2617 WideCharToMultiByte_alloc(enc_codepage, 0,
2618 ret, length, (char**)&term->tl_title,
2619 &length, 0, 0);
2620 vim_free(ret);
2621 }
2622 }
2623#endif
2624 else
2625 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002626 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 if (term == curbuf->b_term)
2628 maketitle();
2629 break;
2630
2631 case VTERM_PROP_CURSORVISIBLE:
2632 term->tl_cursor_visible = value->boolean;
2633 may_toggle_cursor(term);
2634 out_flush();
2635 break;
2636
2637 case VTERM_PROP_CURSORBLINK:
2638 term->tl_cursor_blink = value->boolean;
2639 may_set_cursor_props(term);
2640 break;
2641
2642 case VTERM_PROP_CURSORSHAPE:
2643 term->tl_cursor_shape = value->number;
2644 may_set_cursor_props(term);
2645 break;
2646
2647 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002648 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002649 may_set_cursor_props(term);
2650 break;
2651
2652 case VTERM_PROP_ALTSCREEN:
2653 /* TODO: do anything else? */
2654 term->tl_using_altscreen = value->boolean;
2655 break;
2656
2657 default:
2658 break;
2659 }
2660 /* Always return 1, otherwise vterm doesn't store the value internally. */
2661 return 1;
2662}
2663
2664/*
2665 * The job running in the terminal resized the terminal.
2666 */
2667 static int
2668handle_resize(int rows, int cols, void *user)
2669{
2670 term_T *term = (term_T *)user;
2671 win_T *wp;
2672
2673 term->tl_rows = rows;
2674 term->tl_cols = cols;
2675 if (term->tl_vterm_size_changed)
2676 /* Size was set by vterm_set_size(), don't set the window size. */
2677 term->tl_vterm_size_changed = FALSE;
2678 else
2679 {
2680 FOR_ALL_WINDOWS(wp)
2681 {
2682 if (wp->w_buffer == term->tl_buffer)
2683 {
2684 win_setheight_win(rows, wp);
2685 win_setwidth_win(cols, wp);
2686 }
2687 }
2688 redraw_buf_later(term->tl_buffer, NOT_VALID);
2689 }
2690 return 1;
2691}
2692
2693/*
2694 * Handle a line that is pushed off the top of the screen.
2695 */
2696 static int
2697handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2698{
2699 term_T *term = (term_T *)user;
2700
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002701 /* First remove the lines that were appended before, the pushed line goes
2702 * above it. */
2703 cleanup_scrollback(term);
2704
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002705 /* If the number of lines that are stored goes over 'termscrollback' then
2706 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002707 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002708 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002709 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002710 int i;
2711
2712 curbuf = term->tl_buffer;
2713 for (i = 0; i < todo; ++i)
2714 {
2715 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2716 ml_delete(1, FALSE);
2717 }
2718 curbuf = curwin->w_buffer;
2719
2720 term->tl_scrollback.ga_len -= todo;
2721 mch_memmove(term->tl_scrollback.ga_data,
2722 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2723 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002724 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002725 }
2726
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002727 if (ga_grow(&term->tl_scrollback, 1) == OK)
2728 {
2729 cellattr_T *p = NULL;
2730 int len = 0;
2731 int i;
2732 int c;
2733 int col;
2734 sb_line_T *line;
2735 garray_T ga;
2736 cellattr_T fill_attr = term->tl_default_color;
2737
2738 /* do not store empty cells at the end */
2739 for (i = 0; i < cols; ++i)
2740 if (cells[i].chars[0] != 0)
2741 len = i + 1;
2742 else
2743 cell2cellattr(&cells[i], &fill_attr);
2744
2745 ga_init2(&ga, 1, 100);
2746 if (len > 0)
2747 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2748 if (p != NULL)
2749 {
2750 for (col = 0; col < len; col += cells[col].width)
2751 {
2752 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2753 {
2754 ga.ga_len = 0;
2755 break;
2756 }
2757 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2758 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2759 (char_u *)ga.ga_data + ga.ga_len);
2760 cell2cellattr(&cells[col], &p[col]);
2761 }
2762 }
2763 if (ga_grow(&ga, 1) == FAIL)
2764 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2765 else
2766 {
2767 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2768 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2769 }
2770 ga_clear(&ga);
2771
2772 line = (sb_line_T *)term->tl_scrollback.ga_data
2773 + term->tl_scrollback.ga_len;
2774 line->sb_cols = len;
2775 line->sb_cells = p;
2776 line->sb_fill_attr = fill_attr;
2777 ++term->tl_scrollback.ga_len;
2778 ++term->tl_scrollback_scrolled;
2779 }
2780 return 0; /* ignored */
2781}
2782
2783static VTermScreenCallbacks screen_callbacks = {
2784 handle_damage, /* damage */
2785 handle_moverect, /* moverect */
2786 handle_movecursor, /* movecursor */
2787 handle_settermprop, /* settermprop */
2788 NULL, /* bell */
2789 handle_resize, /* resize */
2790 handle_pushline, /* sb_pushline */
2791 NULL /* sb_popline */
2792};
2793
2794/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002795 * Do the work after the channel of a terminal was closed.
2796 * Must be called only when updating_screen is FALSE.
2797 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2798 */
2799 static int
2800term_after_channel_closed(term_T *term)
2801{
2802 /* Unless in Terminal-Normal mode: clear the vterm. */
2803 if (!term->tl_normal_mode)
2804 {
2805 int fnum = term->tl_buffer->b_fnum;
2806
2807 cleanup_vterm(term);
2808
2809 if (term->tl_finish == TL_FINISH_CLOSE)
2810 {
2811 aco_save_T aco;
2812
2813 /* ++close or term_finish == "close" */
2814 ch_log(NULL, "terminal job finished, closing window");
2815 aucmd_prepbuf(&aco, term->tl_buffer);
2816 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2817 aucmd_restbuf(&aco);
2818 return TRUE;
2819 }
2820 if (term->tl_finish == TL_FINISH_OPEN
2821 && term->tl_buffer->b_nwindows == 0)
2822 {
2823 char buf[50];
2824
2825 /* TODO: use term_opencmd */
2826 ch_log(NULL, "terminal job finished, opening window");
2827 vim_snprintf(buf, sizeof(buf),
2828 term->tl_opencmd == NULL
2829 ? "botright sbuf %d"
2830 : (char *)term->tl_opencmd, fnum);
2831 do_cmdline_cmd((char_u *)buf);
2832 }
2833 else
2834 ch_log(NULL, "terminal job finished");
2835 }
2836
2837 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2838 return FALSE;
2839}
2840
2841/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002842 * Called when a channel has been closed.
2843 * If this was a channel for a terminal window then finish it up.
2844 */
2845 void
2846term_channel_closed(channel_T *ch)
2847{
2848 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002849 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 int did_one = FALSE;
2851
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002852 for (term = first_term; term != NULL; term = next_term)
2853 {
2854 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 if (term->tl_job == ch->ch_job)
2856 {
2857 term->tl_channel_closed = TRUE;
2858 did_one = TRUE;
2859
Bram Moolenaard23a8232018-02-10 18:45:26 +01002860 VIM_CLEAR(term->tl_title);
2861 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002862#ifdef WIN3264
2863 if (term->tl_out_fd != NULL)
2864 {
2865 fclose(term->tl_out_fd);
2866 term->tl_out_fd = NULL;
2867 }
2868#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002869
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002870 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002871 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002872 /* Cannot open or close windows now. Can happen when
2873 * 'lazyredraw' is set. */
2874 term->tl_channel_recently_closed = TRUE;
2875 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876 }
2877
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002878 if (term_after_channel_closed(term))
2879 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002881 }
2882
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002883 if (did_one)
2884 {
2885 redraw_statuslines();
2886
2887 /* Need to break out of vgetc(). */
2888 ins_char_typebuf(K_IGNORE);
2889 typebuf_was_filled = TRUE;
2890
2891 term = curbuf->b_term;
2892 if (term != NULL)
2893 {
2894 if (term->tl_job == ch->ch_job)
2895 maketitle();
2896 update_cursor(term, term->tl_cursor_visible);
2897 }
2898 }
2899}
2900
2901/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002902 * To be called after resetting updating_screen: handle any terminal where the
2903 * channel was closed.
2904 */
2905 void
2906term_check_channel_closed_recently()
2907{
2908 term_T *term;
2909 term_T *next_term;
2910
2911 for (term = first_term; term != NULL; term = next_term)
2912 {
2913 next_term = term->tl_next;
2914 if (term->tl_channel_recently_closed)
2915 {
2916 term->tl_channel_recently_closed = FALSE;
2917 if (term_after_channel_closed(term))
2918 // start over, the list may have changed
2919 next_term = first_term;
2920 }
2921 }
2922}
2923
2924/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002925 * Fill one screen line from a line of the terminal.
2926 * Advances "pos" to past the last column.
2927 */
2928 static void
2929term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2930{
2931 int off = screen_get_current_line_off();
2932
2933 for (pos->col = 0; pos->col < max_col; )
2934 {
2935 VTermScreenCell cell;
2936 int c;
2937
2938 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2939 vim_memset(&cell, 0, sizeof(cell));
2940
2941 c = cell.chars[0];
2942 if (c == NUL)
2943 {
2944 ScreenLines[off] = ' ';
2945 if (enc_utf8)
2946 ScreenLinesUC[off] = NUL;
2947 }
2948 else
2949 {
2950 if (enc_utf8)
2951 {
2952 int i;
2953
2954 /* composing chars */
2955 for (i = 0; i < Screen_mco
2956 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2957 {
2958 ScreenLinesC[i][off] = cell.chars[i + 1];
2959 if (cell.chars[i + 1] == 0)
2960 break;
2961 }
2962 if (c >= 0x80 || (Screen_mco > 0
2963 && ScreenLinesC[0][off] != 0))
2964 {
2965 ScreenLines[off] = ' ';
2966 ScreenLinesUC[off] = c;
2967 }
2968 else
2969 {
2970 ScreenLines[off] = c;
2971 ScreenLinesUC[off] = NUL;
2972 }
2973 }
2974#ifdef WIN3264
2975 else if (has_mbyte && c >= 0x80)
2976 {
2977 char_u mb[MB_MAXBYTES+1];
2978 WCHAR wc = c;
2979
2980 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2981 (char*)mb, 2, 0, 0) > 1)
2982 {
2983 ScreenLines[off] = mb[0];
2984 ScreenLines[off + 1] = mb[1];
2985 cell.width = mb_ptr2cells(mb);
2986 }
2987 else
2988 ScreenLines[off] = c;
2989 }
2990#endif
2991 else
2992 ScreenLines[off] = c;
2993 }
2994 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2995
2996 ++pos->col;
2997 ++off;
2998 if (cell.width == 2)
2999 {
3000 if (enc_utf8)
3001 ScreenLinesUC[off] = NUL;
3002
3003 /* don't set the second byte to NUL for a DBCS encoding, it
3004 * has been set above */
3005 if (enc_utf8 || !has_mbyte)
3006 ScreenLines[off] = NUL;
3007
3008 ++pos->col;
3009 ++off;
3010 }
3011 }
3012}
3013
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003014#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003015 static void
3016update_system_term(term_T *term)
3017{
3018 VTermPos pos;
3019 VTermScreen *screen;
3020
3021 if (term->tl_vterm == NULL)
3022 return;
3023 screen = vterm_obtain_screen(term->tl_vterm);
3024
3025 /* Scroll up to make more room for terminal lines if needed. */
3026 while (term->tl_toprow > 0
3027 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3028 {
3029 int save_p_more = p_more;
3030
3031 p_more = FALSE;
3032 msg_row = Rows - 1;
3033 msg_puts((char_u *)"\n");
3034 p_more = save_p_more;
3035 --term->tl_toprow;
3036 }
3037
3038 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3039 && pos.row < Rows; ++pos.row)
3040 {
3041 if (pos.row < term->tl_rows)
3042 {
3043 int max_col = MIN(Columns, term->tl_cols);
3044
3045 term_line2screenline(screen, &pos, max_col);
3046 }
3047 else
3048 pos.col = 0;
3049
3050 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3051 }
3052
3053 term->tl_dirty_row_start = MAX_ROW;
3054 term->tl_dirty_row_end = 0;
3055 update_cursor(term, TRUE);
3056}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003057#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003058
3059/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003060 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3061 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003062 * Terminal-Normal mode.
3063 */
3064 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003065term_do_update_window(win_T *wp)
3066{
3067 term_T *term = wp->w_buffer->b_term;
3068
3069 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3070}
3071
3072/*
3073 * Called to update a window that contains an active terminal.
3074 */
3075 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076term_update_window(win_T *wp)
3077{
3078 term_T *term = wp->w_buffer->b_term;
3079 VTerm *vterm;
3080 VTermScreen *screen;
3081 VTermState *state;
3082 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003083 int rows, cols;
3084 int newrows, newcols;
3085 int minsize;
3086 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003088 vterm = term->tl_vterm;
3089 screen = vterm_obtain_screen(vterm);
3090 state = vterm_obtain_state(vterm);
3091
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003092 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3093 * SOME_VALID only redraw what was marked dirty. */
3094 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003095 {
3096 term->tl_dirty_row_start = 0;
3097 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003098
3099 if (term->tl_postponed_scroll > 0
3100 && term->tl_postponed_scroll < term->tl_rows / 3)
3101 /* Scrolling is usually faster than redrawing, when there are only
3102 * a few lines to scroll. */
3103 term_scroll_up(term, 0, term->tl_postponed_scroll);
3104 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003105 }
3106
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003107 /*
3108 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003109 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003111 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112
Bram Moolenaar498c2562018-04-15 23:45:15 +02003113 newrows = 99999;
3114 newcols = 99999;
3115 FOR_ALL_WINDOWS(twp)
3116 {
3117 /* When more than one window shows the same terminal, use the
3118 * smallest size. */
3119 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003121 newrows = MIN(newrows, twp->w_height);
3122 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003123 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003124 }
3125 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3126 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3127
3128 if (term->tl_rows != newrows || term->tl_cols != newcols)
3129 {
3130
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131
3132 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003133 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003135 newrows);
3136 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003137 }
3138
3139 /* The cursor may have been moved when resizing. */
3140 vterm_state_get_cursorpos(state, &pos);
3141 position_cursor(wp, &pos);
3142
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003143 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3144 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003146 if (pos.row < term->tl_rows)
3147 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003148 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003149
Bram Moolenaar13568252018-03-16 20:46:58 +01003150 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003151 }
3152 else
3153 pos.col = 0;
3154
Bram Moolenaarf118d482018-03-13 13:14:00 +01003155 screen_line(wp->w_winrow + pos.row
3156#ifdef FEAT_MENU
3157 + winbar_height(wp)
3158#endif
3159 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003160 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003161 term->tl_dirty_row_start = MAX_ROW;
3162 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163}
3164
3165/*
3166 * Return TRUE if "wp" is a terminal window where the job has finished.
3167 */
3168 int
3169term_is_finished(buf_T *buf)
3170{
3171 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3172}
3173
3174/*
3175 * Return TRUE if "wp" is a terminal window where the job has finished or we
3176 * are in Terminal-Normal mode, thus we show the buffer contents.
3177 */
3178 int
3179term_show_buffer(buf_T *buf)
3180{
3181 term_T *term = buf->b_term;
3182
3183 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3184}
3185
3186/*
3187 * The current buffer is going to be changed. If there is terminal
3188 * highlighting remove it now.
3189 */
3190 void
3191term_change_in_curbuf(void)
3192{
3193 term_T *term = curbuf->b_term;
3194
3195 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3196 {
3197 free_scrollback(term);
3198 redraw_buf_later(term->tl_buffer, NOT_VALID);
3199
3200 /* The buffer is now like a normal buffer, it cannot be easily
3201 * abandoned when changed. */
3202 set_string_option_direct((char_u *)"buftype", -1,
3203 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3204 }
3205}
3206
3207/*
3208 * Get the screen attribute for a position in the buffer.
3209 * Use a negative "col" to get the filler background color.
3210 */
3211 int
3212term_get_attr(buf_T *buf, linenr_T lnum, int col)
3213{
3214 term_T *term = buf->b_term;
3215 sb_line_T *line;
3216 cellattr_T *cellattr;
3217
3218 if (lnum > term->tl_scrollback.ga_len)
3219 cellattr = &term->tl_default_color;
3220 else
3221 {
3222 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3223 if (col < 0 || col >= line->sb_cols)
3224 cellattr = &line->sb_fill_attr;
3225 else
3226 cellattr = line->sb_cells + col;
3227 }
3228 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3229}
3230
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003231/*
3232 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003233 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003234 */
3235 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003236cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003237{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003238 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003239}
3240
3241/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003242 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003243 */
3244 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003245init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003246{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003247 VTermColor *fg, *bg;
3248 int fgval, bgval;
3249 int id;
3250
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003251 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3252 term->tl_default_color.width = 1;
3253 fg = &term->tl_default_color.fg;
3254 bg = &term->tl_default_color.bg;
3255
3256 /* Vterm uses a default black background. Set it to white when
3257 * 'background' is "light". */
3258 if (*p_bg == 'l')
3259 {
3260 fgval = 0;
3261 bgval = 255;
3262 }
3263 else
3264 {
3265 fgval = 255;
3266 bgval = 0;
3267 }
3268 fg->red = fg->green = fg->blue = fgval;
3269 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003270 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003271
3272 /* The "Terminal" highlight group overrules the defaults. */
3273 id = syn_name2id((char_u *)"Terminal");
3274
Bram Moolenaar46359e12017-11-29 22:33:38 +01003275 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003276#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3277 if (0
3278# ifdef FEAT_GUI
3279 || gui.in_use
3280# endif
3281# ifdef FEAT_TERMGUICOLORS
3282 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003283# ifdef FEAT_VTP
3284 /* Finally get INVALCOLOR on this execution path */
3285 || (!p_tgc && t_colors >= 256)
3286# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287# endif
3288 )
3289 {
3290 guicolor_T fg_rgb = INVALCOLOR;
3291 guicolor_T bg_rgb = INVALCOLOR;
3292
3293 if (id != 0)
3294 syn_id2colors(id, &fg_rgb, &bg_rgb);
3295
3296# ifdef FEAT_GUI
3297 if (gui.in_use)
3298 {
3299 if (fg_rgb == INVALCOLOR)
3300 fg_rgb = gui.norm_pixel;
3301 if (bg_rgb == INVALCOLOR)
3302 bg_rgb = gui.back_pixel;
3303 }
3304# ifdef FEAT_TERMGUICOLORS
3305 else
3306# endif
3307# endif
3308# ifdef FEAT_TERMGUICOLORS
3309 {
3310 if (fg_rgb == INVALCOLOR)
3311 fg_rgb = cterm_normal_fg_gui_color;
3312 if (bg_rgb == INVALCOLOR)
3313 bg_rgb = cterm_normal_bg_gui_color;
3314 }
3315# endif
3316 if (fg_rgb != INVALCOLOR)
3317 {
3318 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3319
3320 fg->red = (unsigned)(rgb >> 16);
3321 fg->green = (unsigned)(rgb >> 8) & 255;
3322 fg->blue = (unsigned)rgb & 255;
3323 }
3324 if (bg_rgb != INVALCOLOR)
3325 {
3326 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3327
3328 bg->red = (unsigned)(rgb >> 16);
3329 bg->green = (unsigned)(rgb >> 8) & 255;
3330 bg->blue = (unsigned)rgb & 255;
3331 }
3332 }
3333 else
3334#endif
3335 if (id != 0 && t_colors >= 16)
3336 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003337 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003338 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003339 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003340 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003341 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003342 else
3343 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003344#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003345 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003346#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347
3348 /* In an MS-Windows console we know the normal colors. */
3349 if (cterm_normal_fg_color > 0)
3350 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003351 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003352# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003353 tmp = fg->red;
3354 fg->red = fg->blue;
3355 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003356# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003358# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003359 else
3360 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003361# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003362
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363 if (cterm_normal_bg_color > 0)
3364 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003365 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003366# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 tmp = bg->red;
3368 bg->red = bg->blue;
3369 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003370# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003371 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003372# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003373 else
3374 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003375# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003377}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003378
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003379#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3380/*
3381 * Set the 16 ANSI colors from array of RGB values
3382 */
3383 static void
3384set_vterm_palette(VTerm *vterm, long_u *rgb)
3385{
3386 int index = 0;
3387 VTermState *state = vterm_obtain_state(vterm);
3388 for (; index < 16; index++)
3389 {
3390 VTermColor color;
3391 color.red = (unsigned)(rgb[index] >> 16);
3392 color.green = (unsigned)(rgb[index] >> 8) & 255;
3393 color.blue = (unsigned)rgb[index] & 255;
3394 vterm_state_set_palette_color(state, index, &color);
3395 }
3396}
3397
3398/*
3399 * Set the ANSI color palette from a list of colors
3400 */
3401 static int
3402set_ansi_colors_list(VTerm *vterm, list_T *list)
3403{
3404 int n = 0;
3405 long_u rgb[16];
3406 listitem_T *li = list->lv_first;
3407
3408 for (; li != NULL && n < 16; li = li->li_next, n++)
3409 {
3410 char_u *color_name;
3411 guicolor_T guicolor;
3412
3413 color_name = get_tv_string_chk(&li->li_tv);
3414 if (color_name == NULL)
3415 return FAIL;
3416
3417 guicolor = GUI_GET_COLOR(color_name);
3418 if (guicolor == INVALCOLOR)
3419 return FAIL;
3420
3421 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3422 }
3423
3424 if (n != 16 || li != NULL)
3425 return FAIL;
3426
3427 set_vterm_palette(vterm, rgb);
3428
3429 return OK;
3430}
3431
3432/*
3433 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3434 */
3435 static void
3436init_vterm_ansi_colors(VTerm *vterm)
3437{
3438 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3439
3440 if (var != NULL
3441 && (var->di_tv.v_type != VAR_LIST
3442 || var->di_tv.vval.v_list == NULL
3443 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3444 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3445}
3446#endif
3447
Bram Moolenaar52acb112018-03-18 19:20:22 +01003448/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003449 * Handles a "drop" command from the job in the terminal.
3450 * "item" is the file name, "item->li_next" may have options.
3451 */
3452 static void
3453handle_drop_command(listitem_T *item)
3454{
3455 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003456 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003457 int bufnr;
3458 win_T *wp;
3459 tabpage_T *tp;
3460 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003461 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003462
3463 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3464 FOR_ALL_TAB_WINDOWS(tp, wp)
3465 {
3466 if (wp->w_buffer->b_fnum == bufnr)
3467 {
3468 /* buffer is in a window already, go there */
3469 goto_tabpage_win(tp, wp);
3470 return;
3471 }
3472 }
3473
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003474 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003475
3476 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3477 && opt_item->li_tv.vval.v_dict != NULL)
3478 {
3479 dict_T *dict = opt_item->li_tv.vval.v_dict;
3480 char_u *p;
3481
3482 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3483 if (p == NULL)
3484 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3485 if (p != NULL)
3486 {
3487 if (check_ff_value(p) == FAIL)
3488 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3489 else
3490 ea.force_ff = *p;
3491 }
3492 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3493 if (p == NULL)
3494 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3495 if (p != NULL)
3496 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003497 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003498 if (ea.cmd != NULL)
3499 {
3500 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3501 ea.force_enc = 11;
3502 tofree = ea.cmd;
3503 }
3504 }
3505
3506 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3507 if (p != NULL)
3508 get_bad_opt(p, &ea);
3509
3510 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3511 ea.force_bin = FORCE_BIN;
3512 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3513 ea.force_bin = FORCE_BIN;
3514 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3515 ea.force_bin = FORCE_NOBIN;
3516 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3517 ea.force_bin = FORCE_NOBIN;
3518 }
3519
3520 /* open in new window, like ":split fname" */
3521 if (ea.cmd == NULL)
3522 ea.cmd = (char_u *)"split";
3523 ea.arg = fname;
3524 ea.cmdidx = CMD_split;
3525 ex_splitview(&ea);
3526
3527 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003528}
3529
3530/*
3531 * Handles a function call from the job running in a terminal.
3532 * "item" is the function name, "item->li_next" has the arguments.
3533 */
3534 static void
3535handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3536{
3537 char_u *func;
3538 typval_T argvars[2];
3539 typval_T rettv;
3540 int doesrange;
3541
3542 if (item->li_next == NULL)
3543 {
3544 ch_log(channel, "Missing function arguments for call");
3545 return;
3546 }
3547 func = get_tv_string(&item->li_tv);
3548
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003549 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003550 {
3551 ch_log(channel, "Invalid function name: %s", func);
3552 return;
3553 }
3554
3555 argvars[0].v_type = VAR_NUMBER;
3556 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3557 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003558 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003559 2, argvars, /* argv_func */ NULL,
3560 /* firstline */ 1, /* lastline */ 1,
3561 &doesrange, /* evaluate */ TRUE,
3562 /* partial */ NULL, /* selfdict */ NULL) == OK)
3563 {
3564 clear_tv(&rettv);
3565 ch_log(channel, "Function %s called", func);
3566 }
3567 else
3568 ch_log(channel, "Calling function %s failed", func);
3569}
3570
3571/*
3572 * Called by libvterm when it cannot recognize an OSC sequence.
3573 * We recognize a terminal API command.
3574 */
3575 static int
3576parse_osc(const char *command, size_t cmdlen, void *user)
3577{
3578 term_T *term = (term_T *)user;
3579 js_read_T reader;
3580 typval_T tv;
3581 channel_T *channel = term->tl_job == NULL ? NULL
3582 : term->tl_job->jv_channel;
3583
3584 /* We recognize only OSC 5 1 ; {command} */
3585 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3586 return 0; /* not handled */
3587
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003588 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003589 if (reader.js_buf == NULL)
3590 return 1;
3591 reader.js_fill = NULL;
3592 reader.js_used = 0;
3593 if (json_decode(&reader, &tv, 0) == OK
3594 && tv.v_type == VAR_LIST
3595 && tv.vval.v_list != NULL)
3596 {
3597 listitem_T *item = tv.vval.v_list->lv_first;
3598
3599 if (item == NULL)
3600 ch_log(channel, "Missing command");
3601 else
3602 {
3603 char_u *cmd = get_tv_string(&item->li_tv);
3604
Bram Moolenaara997b452018-04-17 23:24:06 +02003605 /* Make sure an invoked command doesn't delete the buffer (and the
3606 * terminal) under our fingers. */
3607 ++term->tl_buffer->b_locked;
3608
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003609 item = item->li_next;
3610 if (item == NULL)
3611 ch_log(channel, "Missing argument for %s", cmd);
3612 else if (STRCMP(cmd, "drop") == 0)
3613 handle_drop_command(item);
3614 else if (STRCMP(cmd, "call") == 0)
3615 handle_call_command(term, channel, item);
3616 else
3617 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003618 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003619 }
3620 }
3621 else
3622 ch_log(channel, "Invalid JSON received");
3623
3624 vim_free(reader.js_buf);
3625 clear_tv(&tv);
3626 return 1;
3627}
3628
3629static VTermParserCallbacks parser_fallbacks = {
3630 NULL, /* text */
3631 NULL, /* control */
3632 NULL, /* escape */
3633 NULL, /* csi */
3634 parse_osc, /* osc */
3635 NULL, /* dcs */
3636 NULL /* resize */
3637};
3638
3639/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003640 * Use Vim's allocation functions for vterm so profiling works.
3641 */
3642 static void *
3643vterm_malloc(size_t size, void *data UNUSED)
3644{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003645 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003646}
3647
3648 static void
3649vterm_memfree(void *ptr, void *data UNUSED)
3650{
3651 vim_free(ptr);
3652}
3653
3654static VTermAllocatorFunctions vterm_allocator = {
3655 &vterm_malloc,
3656 &vterm_memfree
3657};
3658
3659/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003660 * Create a new vterm and initialize it.
3661 */
3662 static void
3663create_vterm(term_T *term, int rows, int cols)
3664{
3665 VTerm *vterm;
3666 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003667 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003668 VTermValue value;
3669
Bram Moolenaar756ef112018-04-10 12:04:27 +02003670 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003671 term->tl_vterm = vterm;
3672 screen = vterm_obtain_screen(vterm);
3673 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3674 /* TODO: depends on 'encoding'. */
3675 vterm_set_utf8(vterm, 1);
3676
3677 init_default_colors(term);
3678
3679 vterm_state_set_default_colors(
3680 vterm_obtain_state(vterm),
3681 &term->tl_default_color.fg,
3682 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003683
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003684 if (t_colors >= 16)
3685 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3686
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003687 /* Required to initialize most things. */
3688 vterm_screen_reset(screen, 1 /* hard */);
3689
3690 /* Allow using alternate screen. */
3691 vterm_screen_enable_altscreen(screen, 1);
3692
3693 /* For unix do not use a blinking cursor. In an xterm this causes the
3694 * cursor to blink if it's blinking in the xterm.
3695 * For Windows we respect the system wide setting. */
3696#ifdef WIN3264
3697 if (GetCaretBlinkTime() == INFINITE)
3698 value.boolean = 0;
3699 else
3700 value.boolean = 1;
3701#else
3702 value.boolean = 0;
3703#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003704 state = vterm_obtain_state(vterm);
3705 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3706 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003707}
3708
3709/*
3710 * Return the text to show for the buffer name and status.
3711 */
3712 char_u *
3713term_get_status_text(term_T *term)
3714{
3715 if (term->tl_status_text == NULL)
3716 {
3717 char_u *txt;
3718 size_t len;
3719
3720 if (term->tl_normal_mode)
3721 {
3722 if (term_job_running(term))
3723 txt = (char_u *)_("Terminal");
3724 else
3725 txt = (char_u *)_("Terminal-finished");
3726 }
3727 else if (term->tl_title != NULL)
3728 txt = term->tl_title;
3729 else if (term_none_open(term))
3730 txt = (char_u *)_("active");
3731 else if (term_job_running(term))
3732 txt = (char_u *)_("running");
3733 else
3734 txt = (char_u *)_("finished");
3735 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3736 term->tl_status_text = alloc((int)len);
3737 if (term->tl_status_text != NULL)
3738 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3739 term->tl_buffer->b_fname, txt);
3740 }
3741 return term->tl_status_text;
3742}
3743
3744/*
3745 * Mark references in jobs of terminals.
3746 */
3747 int
3748set_ref_in_term(int copyID)
3749{
3750 int abort = FALSE;
3751 term_T *term;
3752 typval_T tv;
3753
3754 for (term = first_term; term != NULL; term = term->tl_next)
3755 if (term->tl_job != NULL)
3756 {
3757 tv.v_type = VAR_JOB;
3758 tv.vval.v_job = term->tl_job;
3759 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3760 }
3761 return abort;
3762}
3763
3764/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003765 * Cache "Terminal" highlight group colors.
3766 */
3767 void
3768set_terminal_default_colors(int cterm_fg, int cterm_bg)
3769{
3770 term_default_cterm_fg = cterm_fg - 1;
3771 term_default_cterm_bg = cterm_bg - 1;
3772}
3773
3774/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003775 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003776 * Returns NULL when the buffer is not for a terminal window and logs a message
3777 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003778 */
3779 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003780term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003781{
3782 buf_T *buf;
3783
3784 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3785 ++emsg_off;
3786 buf = get_buf_tv(&argvars[0], FALSE);
3787 --emsg_off;
3788 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003789 {
3790 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003791 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003792 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003793 return buf;
3794}
3795
Bram Moolenaard96ff162018-02-18 22:13:29 +01003796 static int
3797same_color(VTermColor *a, VTermColor *b)
3798{
3799 return a->red == b->red
3800 && a->green == b->green
3801 && a->blue == b->blue
3802 && a->ansi_index == b->ansi_index;
3803}
3804
3805 static void
3806dump_term_color(FILE *fd, VTermColor *color)
3807{
3808 fprintf(fd, "%02x%02x%02x%d",
3809 (int)color->red, (int)color->green, (int)color->blue,
3810 (int)color->ansi_index);
3811}
3812
3813/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003814 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003815 *
3816 * Each screen cell in full is:
3817 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3818 * {characters} is a space for an empty cell
3819 * For a double-width character "+" is changed to "*" and the next cell is
3820 * skipped.
3821 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3822 * when "&" use the same as the previous cell.
3823 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3824 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3825 * {color-idx} is a number from 0 to 255
3826 *
3827 * Screen cell with same width, attributes and color as the previous one:
3828 * |{characters}
3829 *
3830 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3831 *
3832 * Repeating the previous screen cell:
3833 * @{count}
3834 */
3835 void
3836f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3837{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003838 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003839 term_T *term;
3840 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003841 int max_height = 0;
3842 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003843 stat_T st;
3844 FILE *fd;
3845 VTermPos pos;
3846 VTermScreen *screen;
3847 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003848 VTermState *state;
3849 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003850
3851 if (check_restricted() || check_secure())
3852 return;
3853 if (buf == NULL)
3854 return;
3855 term = buf->b_term;
3856
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003857 if (argvars[2].v_type != VAR_UNKNOWN)
3858 {
3859 dict_T *d;
3860
3861 if (argvars[2].v_type != VAR_DICT)
3862 {
3863 EMSG(_(e_dictreq));
3864 return;
3865 }
3866 d = argvars[2].vval.v_dict;
3867 if (d != NULL)
3868 {
3869 max_height = get_dict_number(d, (char_u *)"rows");
3870 max_width = get_dict_number(d, (char_u *)"columns");
3871 }
3872 }
3873
Bram Moolenaard96ff162018-02-18 22:13:29 +01003874 fname = get_tv_string_chk(&argvars[1]);
3875 if (fname == NULL)
3876 return;
3877 if (mch_stat((char *)fname, &st) >= 0)
3878 {
3879 EMSG2(_("E953: File exists: %s"), fname);
3880 return;
3881 }
3882
Bram Moolenaard96ff162018-02-18 22:13:29 +01003883 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3884 {
3885 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3886 return;
3887 }
3888
3889 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3890
3891 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003892 state = vterm_obtain_state(term->tl_vterm);
3893 vterm_state_get_cursorpos(state, &cursor_pos);
3894
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003895 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3896 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003897 {
3898 int repeat = 0;
3899
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003900 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3901 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003902 {
3903 VTermScreenCell cell;
3904 int same_attr;
3905 int same_chars = TRUE;
3906 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003907 int is_cursor_pos = (pos.col == cursor_pos.col
3908 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003909
3910 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3911 vim_memset(&cell, 0, sizeof(cell));
3912
3913 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3914 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003915 int c = cell.chars[i];
3916 int pc = prev_cell.chars[i];
3917
3918 /* For the first character NUL is the same as space. */
3919 if (i == 0)
3920 {
3921 c = (c == NUL) ? ' ' : c;
3922 pc = (pc == NUL) ? ' ' : pc;
3923 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003924 if (cell.chars[i] != prev_cell.chars[i])
3925 same_chars = FALSE;
3926 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3927 break;
3928 }
3929 same_attr = vtermAttr2hl(cell.attrs)
3930 == vtermAttr2hl(prev_cell.attrs)
3931 && same_color(&cell.fg, &prev_cell.fg)
3932 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003933 if (same_chars && cell.width == prev_cell.width && same_attr
3934 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003935 {
3936 ++repeat;
3937 }
3938 else
3939 {
3940 if (repeat > 0)
3941 {
3942 fprintf(fd, "@%d", repeat);
3943 repeat = 0;
3944 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003945 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003946
3947 if (cell.chars[0] == NUL)
3948 fputs(" ", fd);
3949 else
3950 {
3951 char_u charbuf[10];
3952 int len;
3953
3954 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3955 && cell.chars[i] != NUL; ++i)
3956 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003957 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003958 fwrite(charbuf, len, 1, fd);
3959 }
3960 }
3961
3962 /* When only the characters differ we don't write anything, the
3963 * following "|", "@" or NL will indicate using the same
3964 * attributes. */
3965 if (cell.width != prev_cell.width || !same_attr)
3966 {
3967 if (cell.width == 2)
3968 {
3969 fputs("*", fd);
3970 ++pos.col;
3971 }
3972 else
3973 fputs("+", fd);
3974
3975 if (same_attr)
3976 {
3977 fputs("&", fd);
3978 }
3979 else
3980 {
3981 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3982 if (same_color(&cell.fg, &prev_cell.fg))
3983 fputs("&", fd);
3984 else
3985 {
3986 fputs("#", fd);
3987 dump_term_color(fd, &cell.fg);
3988 }
3989 if (same_color(&cell.bg, &prev_cell.bg))
3990 fputs("&", fd);
3991 else
3992 {
3993 fputs("#", fd);
3994 dump_term_color(fd, &cell.bg);
3995 }
3996 }
3997 }
3998
3999 prev_cell = cell;
4000 }
4001 }
4002 if (repeat > 0)
4003 fprintf(fd, "@%d", repeat);
4004 fputs("\n", fd);
4005 }
4006
4007 fclose(fd);
4008}
4009
4010/*
4011 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4012 */
4013 static void
4014dump_is_corrupt(garray_T *gap)
4015{
4016 ga_concat(gap, (char_u *)"CORRUPT");
4017}
4018
4019 static void
4020append_cell(garray_T *gap, cellattr_T *cell)
4021{
4022 if (ga_grow(gap, 1) == OK)
4023 {
4024 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4025 ++gap->ga_len;
4026 }
4027}
4028
4029/*
4030 * Read the dump file from "fd" and append lines to the current buffer.
4031 * Return the cell width of the longest line.
4032 */
4033 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004034read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004035{
4036 int c;
4037 garray_T ga_text;
4038 garray_T ga_cell;
4039 char_u *prev_char = NULL;
4040 int attr = 0;
4041 cellattr_T cell;
4042 term_T *term = curbuf->b_term;
4043 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004044 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004045
4046 ga_init2(&ga_text, 1, 90);
4047 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4048 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004049 cursor_pos->row = -1;
4050 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004051
4052 c = fgetc(fd);
4053 for (;;)
4054 {
4055 if (c == EOF)
4056 break;
4057 if (c == '\n')
4058 {
4059 /* End of a line: append it to the buffer. */
4060 if (ga_text.ga_data == NULL)
4061 dump_is_corrupt(&ga_text);
4062 if (ga_grow(&term->tl_scrollback, 1) == OK)
4063 {
4064 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4065 + term->tl_scrollback.ga_len;
4066
4067 if (max_cells < ga_cell.ga_len)
4068 max_cells = ga_cell.ga_len;
4069 line->sb_cols = ga_cell.ga_len;
4070 line->sb_cells = ga_cell.ga_data;
4071 line->sb_fill_attr = term->tl_default_color;
4072 ++term->tl_scrollback.ga_len;
4073 ga_init(&ga_cell);
4074
4075 ga_append(&ga_text, NUL);
4076 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4077 ga_text.ga_len, FALSE);
4078 }
4079 else
4080 ga_clear(&ga_cell);
4081 ga_text.ga_len = 0;
4082
4083 c = fgetc(fd);
4084 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004085 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004086 {
4087 int prev_len = ga_text.ga_len;
4088
Bram Moolenaar9271d052018-02-25 21:39:46 +01004089 if (c == '>')
4090 {
4091 if (cursor_pos->row != -1)
4092 dump_is_corrupt(&ga_text); /* duplicate cursor */
4093 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4094 cursor_pos->col = ga_cell.ga_len;
4095 }
4096
Bram Moolenaard96ff162018-02-18 22:13:29 +01004097 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4098 c = fgetc(fd);
4099 if (c != EOF)
4100 ga_append(&ga_text, c);
4101 for (;;)
4102 {
4103 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004104 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004105 || c == EOF || c == '\n')
4106 break;
4107 ga_append(&ga_text, c);
4108 }
4109
4110 /* save the character for repeating it */
4111 vim_free(prev_char);
4112 if (ga_text.ga_data != NULL)
4113 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4114 ga_text.ga_len - prev_len);
4115
Bram Moolenaar9271d052018-02-25 21:39:46 +01004116 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004117 {
4118 /* use all attributes from previous cell */
4119 }
4120 else if (c == '+' || c == '*')
4121 {
4122 int is_bg;
4123
4124 cell.width = c == '+' ? 1 : 2;
4125
4126 c = fgetc(fd);
4127 if (c == '&')
4128 {
4129 /* use same attr as previous cell */
4130 c = fgetc(fd);
4131 }
4132 else if (isdigit(c))
4133 {
4134 /* get the decimal attribute */
4135 attr = 0;
4136 while (isdigit(c))
4137 {
4138 attr = attr * 10 + (c - '0');
4139 c = fgetc(fd);
4140 }
4141 hl2vtermAttr(attr, &cell);
4142 }
4143 else
4144 dump_is_corrupt(&ga_text);
4145
4146 /* is_bg == 0: fg, is_bg == 1: bg */
4147 for (is_bg = 0; is_bg <= 1; ++is_bg)
4148 {
4149 if (c == '&')
4150 {
4151 /* use same color as previous cell */
4152 c = fgetc(fd);
4153 }
4154 else if (c == '#')
4155 {
4156 int red, green, blue, index = 0;
4157
4158 c = fgetc(fd);
4159 red = hex2nr(c);
4160 c = fgetc(fd);
4161 red = (red << 4) + hex2nr(c);
4162 c = fgetc(fd);
4163 green = hex2nr(c);
4164 c = fgetc(fd);
4165 green = (green << 4) + hex2nr(c);
4166 c = fgetc(fd);
4167 blue = hex2nr(c);
4168 c = fgetc(fd);
4169 blue = (blue << 4) + hex2nr(c);
4170 c = fgetc(fd);
4171 if (!isdigit(c))
4172 dump_is_corrupt(&ga_text);
4173 while (isdigit(c))
4174 {
4175 index = index * 10 + (c - '0');
4176 c = fgetc(fd);
4177 }
4178
4179 if (is_bg)
4180 {
4181 cell.bg.red = red;
4182 cell.bg.green = green;
4183 cell.bg.blue = blue;
4184 cell.bg.ansi_index = index;
4185 }
4186 else
4187 {
4188 cell.fg.red = red;
4189 cell.fg.green = green;
4190 cell.fg.blue = blue;
4191 cell.fg.ansi_index = index;
4192 }
4193 }
4194 else
4195 dump_is_corrupt(&ga_text);
4196 }
4197 }
4198 else
4199 dump_is_corrupt(&ga_text);
4200
4201 append_cell(&ga_cell, &cell);
4202 }
4203 else if (c == '@')
4204 {
4205 if (prev_char == NULL)
4206 dump_is_corrupt(&ga_text);
4207 else
4208 {
4209 int count = 0;
4210
4211 /* repeat previous character, get the count */
4212 for (;;)
4213 {
4214 c = fgetc(fd);
4215 if (!isdigit(c))
4216 break;
4217 count = count * 10 + (c - '0');
4218 }
4219
4220 while (count-- > 0)
4221 {
4222 ga_concat(&ga_text, prev_char);
4223 append_cell(&ga_cell, &cell);
4224 }
4225 }
4226 }
4227 else
4228 {
4229 dump_is_corrupt(&ga_text);
4230 c = fgetc(fd);
4231 }
4232 }
4233
4234 if (ga_text.ga_len > 0)
4235 {
4236 /* trailing characters after last NL */
4237 dump_is_corrupt(&ga_text);
4238 ga_append(&ga_text, NUL);
4239 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4240 ga_text.ga_len, FALSE);
4241 }
4242
4243 ga_clear(&ga_text);
4244 vim_free(prev_char);
4245
4246 return max_cells;
4247}
4248
4249/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004250 * Return an allocated string with at least "text_width" "=" characters and
4251 * "fname" inserted in the middle.
4252 */
4253 static char_u *
4254get_separator(int text_width, char_u *fname)
4255{
4256 int width = MAX(text_width, curwin->w_width);
4257 char_u *textline;
4258 int fname_size;
4259 char_u *p = fname;
4260 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004261 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004262
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004263 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004264 if (textline == NULL)
4265 return NULL;
4266
4267 fname_size = vim_strsize(fname);
4268 if (fname_size < width - 8)
4269 {
4270 /* enough room, don't use the full window width */
4271 width = MAX(text_width, fname_size + 8);
4272 }
4273 else if (fname_size > width - 8)
4274 {
4275 /* full name doesn't fit, use only the tail */
4276 p = gettail(fname);
4277 fname_size = vim_strsize(p);
4278 }
4279 /* skip characters until the name fits */
4280 while (fname_size > width - 8)
4281 {
4282 p += (*mb_ptr2len)(p);
4283 fname_size = vim_strsize(p);
4284 }
4285
4286 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4287 textline[i] = '=';
4288 textline[i++] = ' ';
4289
4290 STRCPY(textline + i, p);
4291 off = STRLEN(textline);
4292 textline[off] = ' ';
4293 for (i = 1; i < (width - fname_size) / 2; ++i)
4294 textline[off + i] = '=';
4295 textline[off + i] = NUL;
4296
4297 return textline;
4298}
4299
4300/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004301 * Common for "term_dumpdiff()" and "term_dumpload()".
4302 */
4303 static void
4304term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4305{
4306 jobopt_T opt;
4307 buf_T *buf;
4308 char_u buf1[NUMBUFLEN];
4309 char_u buf2[NUMBUFLEN];
4310 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004311 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004312 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004313 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004314 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004315 char_u *textline = NULL;
4316
4317 /* First open the files. If this fails bail out. */
4318 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4319 if (do_diff)
4320 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4321 if (fname1 == NULL || (do_diff && fname2 == NULL))
4322 {
4323 EMSG(_(e_invarg));
4324 return;
4325 }
4326 fd1 = mch_fopen((char *)fname1, READBIN);
4327 if (fd1 == NULL)
4328 {
4329 EMSG2(_(e_notread), fname1);
4330 return;
4331 }
4332 if (do_diff)
4333 {
4334 fd2 = mch_fopen((char *)fname2, READBIN);
4335 if (fd2 == NULL)
4336 {
4337 fclose(fd1);
4338 EMSG2(_(e_notread), fname2);
4339 return;
4340 }
4341 }
4342
4343 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004344 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4345 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4346 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4347 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4348 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004349
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004350 if (opt.jo_term_name == NULL)
4351 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004352 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004353
Bram Moolenaarb571c632018-03-21 22:27:59 +01004354 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004355 if (fname_tofree != NULL)
4356 {
4357 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4358 opt.jo_term_name = fname_tofree;
4359 }
4360 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004361
Bram Moolenaar13568252018-03-16 20:46:58 +01004362 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004363 if (buf != NULL && buf->b_term != NULL)
4364 {
4365 int i;
4366 linenr_T bot_lnum;
4367 linenr_T lnum;
4368 term_T *term = buf->b_term;
4369 int width;
4370 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004371 VTermPos cursor_pos1;
4372 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373
Bram Moolenaar52acb112018-03-18 19:20:22 +01004374 init_default_colors(term);
4375
Bram Moolenaard96ff162018-02-18 22:13:29 +01004376 rettv->vval.v_number = buf->b_fnum;
4377
4378 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004379 width = read_dump_file(fd1, &cursor_pos1);
4380
4381 /* position the cursor */
4382 if (cursor_pos1.row >= 0)
4383 {
4384 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4385 coladvance(cursor_pos1.col);
4386 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004387
4388 /* Delete the empty line that was in the empty buffer. */
4389 ml_delete(1, FALSE);
4390
4391 /* For term_dumpload() we are done here. */
4392 if (!do_diff)
4393 goto theend;
4394
4395 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4396
Bram Moolenaar4a696342018-04-05 18:45:26 +02004397 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004398 if (textline == NULL)
4399 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004400 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4401 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4402 vim_free(textline);
4403
4404 textline = get_separator(width, fname2);
4405 if (textline == NULL)
4406 goto theend;
4407 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4408 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004409 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004410
4411 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004412 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004413 if (width2 > width)
4414 {
4415 vim_free(textline);
4416 textline = alloc(width2 + 1);
4417 if (textline == NULL)
4418 goto theend;
4419 width = width2;
4420 textline[width] = NUL;
4421 }
4422 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4423
4424 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4425 {
4426 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4427 {
4428 /* bottom part has fewer rows, fill with "-" */
4429 for (i = 0; i < width; ++i)
4430 textline[i] = '-';
4431 }
4432 else
4433 {
4434 char_u *line1;
4435 char_u *line2;
4436 char_u *p1;
4437 char_u *p2;
4438 int col;
4439 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4440 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4441 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4442 ->sb_cells;
4443
4444 /* Make a copy, getting the second line will invalidate it. */
4445 line1 = vim_strsave(ml_get(lnum));
4446 if (line1 == NULL)
4447 break;
4448 p1 = line1;
4449
4450 line2 = ml_get(lnum + bot_lnum);
4451 p2 = line2;
4452 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4453 {
4454 int len1 = utfc_ptr2len(p1);
4455 int len2 = utfc_ptr2len(p2);
4456
4457 textline[col] = ' ';
4458 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004459 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004460 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004461 else if (lnum == cursor_pos1.row + 1
4462 && col == cursor_pos1.col
4463 && (cursor_pos1.row != cursor_pos2.row
4464 || cursor_pos1.col != cursor_pos2.col))
4465 /* cursor in first but not in second */
4466 textline[col] = '>';
4467 else if (lnum == cursor_pos2.row + 1
4468 && col == cursor_pos2.col
4469 && (cursor_pos1.row != cursor_pos2.row
4470 || cursor_pos1.col != cursor_pos2.col))
4471 /* cursor in second but not in first */
4472 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004473 else if (cellattr1 != NULL && cellattr2 != NULL)
4474 {
4475 if ((cellattr1 + col)->width
4476 != (cellattr2 + col)->width)
4477 textline[col] = 'w';
4478 else if (!same_color(&(cellattr1 + col)->fg,
4479 &(cellattr2 + col)->fg))
4480 textline[col] = 'f';
4481 else if (!same_color(&(cellattr1 + col)->bg,
4482 &(cellattr2 + col)->bg))
4483 textline[col] = 'b';
4484 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4485 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4486 textline[col] = 'a';
4487 }
4488 p1 += len1;
4489 p2 += len2;
4490 /* TODO: handle different width */
4491 }
4492 vim_free(line1);
4493
4494 while (col < width)
4495 {
4496 if (*p1 == NUL && *p2 == NUL)
4497 textline[col] = '?';
4498 else if (*p1 == NUL)
4499 {
4500 textline[col] = '+';
4501 p2 += utfc_ptr2len(p2);
4502 }
4503 else
4504 {
4505 textline[col] = '-';
4506 p1 += utfc_ptr2len(p1);
4507 }
4508 ++col;
4509 }
4510 }
4511 if (add_empty_scrollback(term, &term->tl_default_color,
4512 term->tl_top_diff_rows) == OK)
4513 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4514 ++bot_lnum;
4515 }
4516
4517 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4518 {
4519 /* bottom part has more rows, fill with "+" */
4520 for (i = 0; i < width; ++i)
4521 textline[i] = '+';
4522 if (add_empty_scrollback(term, &term->tl_default_color,
4523 term->tl_top_diff_rows) == OK)
4524 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4525 ++lnum;
4526 ++bot_lnum;
4527 }
4528
4529 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004530
4531 /* looks better without wrapping */
4532 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004533 }
4534
4535theend:
4536 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004537 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004538 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004539 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004540 fclose(fd2);
4541}
4542
4543/*
4544 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4545 * bottom files.
4546 * Return FAIL when this is not possible.
4547 */
4548 int
4549term_swap_diff()
4550{
4551 term_T *term = curbuf->b_term;
4552 linenr_T line_count;
4553 linenr_T top_rows;
4554 linenr_T bot_rows;
4555 linenr_T bot_start;
4556 linenr_T lnum;
4557 char_u *p;
4558 sb_line_T *sb_line;
4559
4560 if (term == NULL
4561 || !term_is_finished(curbuf)
4562 || term->tl_top_diff_rows == 0
4563 || term->tl_scrollback.ga_len == 0)
4564 return FAIL;
4565
4566 line_count = curbuf->b_ml.ml_line_count;
4567 top_rows = term->tl_top_diff_rows;
4568 bot_rows = term->tl_bot_diff_rows;
4569 bot_start = line_count - bot_rows;
4570 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4571
4572 /* move lines from top to above the bottom part */
4573 for (lnum = 1; lnum <= top_rows; ++lnum)
4574 {
4575 p = vim_strsave(ml_get(1));
4576 if (p == NULL)
4577 return OK;
4578 ml_append(bot_start, p, 0, FALSE);
4579 ml_delete(1, FALSE);
4580 vim_free(p);
4581 }
4582
4583 /* move lines from bottom to the top */
4584 for (lnum = 1; lnum <= bot_rows; ++lnum)
4585 {
4586 p = vim_strsave(ml_get(bot_start + lnum));
4587 if (p == NULL)
4588 return OK;
4589 ml_delete(bot_start + lnum, FALSE);
4590 ml_append(lnum - 1, p, 0, FALSE);
4591 vim_free(p);
4592 }
4593
4594 if (top_rows == bot_rows)
4595 {
4596 /* rows counts are equal, can swap cell properties */
4597 for (lnum = 0; lnum < top_rows; ++lnum)
4598 {
4599 sb_line_T temp;
4600
4601 temp = *(sb_line + lnum);
4602 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4603 *(sb_line + bot_start + lnum) = temp;
4604 }
4605 }
4606 else
4607 {
4608 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4609 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4610
4611 /* need to copy cell properties into temp memory */
4612 if (temp != NULL)
4613 {
4614 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4615 mch_memmove(term->tl_scrollback.ga_data,
4616 temp + bot_start,
4617 sizeof(sb_line_T) * bot_rows);
4618 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4619 temp + top_rows,
4620 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4621 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4622 + line_count - top_rows,
4623 temp,
4624 sizeof(sb_line_T) * top_rows);
4625 vim_free(temp);
4626 }
4627 }
4628
4629 term->tl_top_diff_rows = bot_rows;
4630 term->tl_bot_diff_rows = top_rows;
4631
4632 update_screen(NOT_VALID);
4633 return OK;
4634}
4635
4636/*
4637 * "term_dumpdiff(filename, filename, options)" function
4638 */
4639 void
4640f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4641{
4642 term_load_dump(argvars, rettv, TRUE);
4643}
4644
4645/*
4646 * "term_dumpload(filename, options)" function
4647 */
4648 void
4649f_term_dumpload(typval_T *argvars, typval_T *rettv)
4650{
4651 term_load_dump(argvars, rettv, FALSE);
4652}
4653
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004654/*
4655 * "term_getaltscreen(buf)" function
4656 */
4657 void
4658f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4659{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004660 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004661
4662 if (buf == NULL)
4663 return;
4664 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4665}
4666
4667/*
4668 * "term_getattr(attr, name)" function
4669 */
4670 void
4671f_term_getattr(typval_T *argvars, typval_T *rettv)
4672{
4673 int attr;
4674 size_t i;
4675 char_u *name;
4676
4677 static struct {
4678 char *name;
4679 int attr;
4680 } attrs[] = {
4681 {"bold", HL_BOLD},
4682 {"italic", HL_ITALIC},
4683 {"underline", HL_UNDERLINE},
4684 {"strike", HL_STRIKETHROUGH},
4685 {"reverse", HL_INVERSE},
4686 };
4687
4688 attr = get_tv_number(&argvars[0]);
4689 name = get_tv_string_chk(&argvars[1]);
4690 if (name == NULL)
4691 return;
4692
4693 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4694 if (STRCMP(name, attrs[i].name) == 0)
4695 {
4696 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4697 break;
4698 }
4699}
4700
4701/*
4702 * "term_getcursor(buf)" function
4703 */
4704 void
4705f_term_getcursor(typval_T *argvars, typval_T *rettv)
4706{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004707 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004708 term_T *term;
4709 list_T *l;
4710 dict_T *d;
4711
4712 if (rettv_list_alloc(rettv) == FAIL)
4713 return;
4714 if (buf == NULL)
4715 return;
4716 term = buf->b_term;
4717
4718 l = rettv->vval.v_list;
4719 list_append_number(l, term->tl_cursor_pos.row + 1);
4720 list_append_number(l, term->tl_cursor_pos.col + 1);
4721
4722 d = dict_alloc();
4723 if (d != NULL)
4724 {
4725 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4726 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4727 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4728 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02004729 dict_add_nr_str(d, "color", 0L, cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004730 list_append_dict(l, d);
4731 }
4732}
4733
4734/*
4735 * "term_getjob(buf)" function
4736 */
4737 void
4738f_term_getjob(typval_T *argvars, typval_T *rettv)
4739{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004740 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004741
4742 rettv->v_type = VAR_JOB;
4743 rettv->vval.v_job = NULL;
4744 if (buf == NULL)
4745 return;
4746
4747 rettv->vval.v_job = buf->b_term->tl_job;
4748 if (rettv->vval.v_job != NULL)
4749 ++rettv->vval.v_job->jv_refcount;
4750}
4751
4752 static int
4753get_row_number(typval_T *tv, term_T *term)
4754{
4755 if (tv->v_type == VAR_STRING
4756 && tv->vval.v_string != NULL
4757 && STRCMP(tv->vval.v_string, ".") == 0)
4758 return term->tl_cursor_pos.row;
4759 return (int)get_tv_number(tv) - 1;
4760}
4761
4762/*
4763 * "term_getline(buf, row)" function
4764 */
4765 void
4766f_term_getline(typval_T *argvars, typval_T *rettv)
4767{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004768 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004769 term_T *term;
4770 int row;
4771
4772 rettv->v_type = VAR_STRING;
4773 if (buf == NULL)
4774 return;
4775 term = buf->b_term;
4776 row = get_row_number(&argvars[1], term);
4777
4778 if (term->tl_vterm == NULL)
4779 {
4780 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4781
4782 /* vterm is finished, get the text from the buffer */
4783 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4784 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4785 }
4786 else
4787 {
4788 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4789 VTermRect rect;
4790 int len;
4791 char_u *p;
4792
4793 if (row < 0 || row >= term->tl_rows)
4794 return;
4795 len = term->tl_cols * MB_MAXBYTES + 1;
4796 p = alloc(len);
4797 if (p == NULL)
4798 return;
4799 rettv->vval.v_string = p;
4800
4801 rect.start_col = 0;
4802 rect.end_col = term->tl_cols;
4803 rect.start_row = row;
4804 rect.end_row = row + 1;
4805 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4806 }
4807}
4808
4809/*
4810 * "term_getscrolled(buf)" function
4811 */
4812 void
4813f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4814{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004815 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004816
4817 if (buf == NULL)
4818 return;
4819 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4820}
4821
4822/*
4823 * "term_getsize(buf)" function
4824 */
4825 void
4826f_term_getsize(typval_T *argvars, typval_T *rettv)
4827{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004828 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004829 list_T *l;
4830
4831 if (rettv_list_alloc(rettv) == FAIL)
4832 return;
4833 if (buf == NULL)
4834 return;
4835
4836 l = rettv->vval.v_list;
4837 list_append_number(l, buf->b_term->tl_rows);
4838 list_append_number(l, buf->b_term->tl_cols);
4839}
4840
4841/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004842 * "term_setsize(buf, rows, cols)" function
4843 */
4844 void
4845f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4846{
4847 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4848 term_T *term;
4849 varnumber_T rows, cols;
4850
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004851 if (buf == NULL)
4852 {
4853 EMSG(_("E955: Not a terminal buffer"));
4854 return;
4855 }
4856 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004857 return;
4858 term = buf->b_term;
4859 rows = get_tv_number(&argvars[1]);
4860 rows = rows <= 0 ? term->tl_rows : rows;
4861 cols = get_tv_number(&argvars[2]);
4862 cols = cols <= 0 ? term->tl_cols : cols;
4863 vterm_set_size(term->tl_vterm, rows, cols);
4864 /* handle_resize() will resize the windows */
4865
4866 /* Get and remember the size we ended up with. Update the pty. */
4867 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4868 term_report_winsize(term, term->tl_rows, term->tl_cols);
4869}
4870
4871/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004872 * "term_getstatus(buf)" function
4873 */
4874 void
4875f_term_getstatus(typval_T *argvars, typval_T *rettv)
4876{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004877 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004878 term_T *term;
4879 char_u val[100];
4880
4881 rettv->v_type = VAR_STRING;
4882 if (buf == NULL)
4883 return;
4884 term = buf->b_term;
4885
4886 if (term_job_running(term))
4887 STRCPY(val, "running");
4888 else
4889 STRCPY(val, "finished");
4890 if (term->tl_normal_mode)
4891 STRCAT(val, ",normal");
4892 rettv->vval.v_string = vim_strsave(val);
4893}
4894
4895/*
4896 * "term_gettitle(buf)" function
4897 */
4898 void
4899f_term_gettitle(typval_T *argvars, typval_T *rettv)
4900{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004901 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004902
4903 rettv->v_type = VAR_STRING;
4904 if (buf == NULL)
4905 return;
4906
4907 if (buf->b_term->tl_title != NULL)
4908 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4909}
4910
4911/*
4912 * "term_gettty(buf)" function
4913 */
4914 void
4915f_term_gettty(typval_T *argvars, typval_T *rettv)
4916{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004917 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004918 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004919 int num = 0;
4920
4921 rettv->v_type = VAR_STRING;
4922 if (buf == NULL)
4923 return;
4924 if (argvars[1].v_type != VAR_UNKNOWN)
4925 num = get_tv_number(&argvars[1]);
4926
4927 switch (num)
4928 {
4929 case 0:
4930 if (buf->b_term->tl_job != NULL)
4931 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004932 break;
4933 case 1:
4934 if (buf->b_term->tl_job != NULL)
4935 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004936 break;
4937 default:
4938 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4939 return;
4940 }
4941 if (p != NULL)
4942 rettv->vval.v_string = vim_strsave(p);
4943}
4944
4945/*
4946 * "term_list()" function
4947 */
4948 void
4949f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4950{
4951 term_T *tp;
4952 list_T *l;
4953
4954 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4955 return;
4956
4957 l = rettv->vval.v_list;
4958 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4959 if (tp != NULL && tp->tl_buffer != NULL)
4960 if (list_append_number(l,
4961 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4962 return;
4963}
4964
4965/*
4966 * "term_scrape(buf, row)" function
4967 */
4968 void
4969f_term_scrape(typval_T *argvars, typval_T *rettv)
4970{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004971 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004972 VTermScreen *screen = NULL;
4973 VTermPos pos;
4974 list_T *l;
4975 term_T *term;
4976 char_u *p;
4977 sb_line_T *line;
4978
4979 if (rettv_list_alloc(rettv) == FAIL)
4980 return;
4981 if (buf == NULL)
4982 return;
4983 term = buf->b_term;
4984
4985 l = rettv->vval.v_list;
4986 pos.row = get_row_number(&argvars[1], term);
4987
4988 if (term->tl_vterm != NULL)
4989 {
4990 screen = vterm_obtain_screen(term->tl_vterm);
4991 p = NULL;
4992 line = NULL;
4993 }
4994 else
4995 {
4996 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4997
4998 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4999 return;
5000 p = ml_get_buf(buf, lnum + 1, FALSE);
5001 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5002 }
5003
5004 for (pos.col = 0; pos.col < term->tl_cols; )
5005 {
5006 dict_T *dcell;
5007 int width;
5008 VTermScreenCellAttrs attrs;
5009 VTermColor fg, bg;
5010 char_u rgb[8];
5011 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5012 int off = 0;
5013 int i;
5014
5015 if (screen == NULL)
5016 {
5017 cellattr_T *cellattr;
5018 int len;
5019
5020 /* vterm has finished, get the cell from scrollback */
5021 if (pos.col >= line->sb_cols)
5022 break;
5023 cellattr = line->sb_cells + pos.col;
5024 width = cellattr->width;
5025 attrs = cellattr->attrs;
5026 fg = cellattr->fg;
5027 bg = cellattr->bg;
5028 len = MB_PTR2LEN(p);
5029 mch_memmove(mbs, p, len);
5030 mbs[len] = NUL;
5031 p += len;
5032 }
5033 else
5034 {
5035 VTermScreenCell cell;
5036 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5037 break;
5038 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5039 {
5040 if (cell.chars[i] == 0)
5041 break;
5042 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5043 }
5044 mbs[off] = NUL;
5045 width = cell.width;
5046 attrs = cell.attrs;
5047 fg = cell.fg;
5048 bg = cell.bg;
5049 }
5050 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005051 if (dcell == NULL)
5052 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005053 list_append_dict(l, dcell);
5054
5055 dict_add_nr_str(dcell, "chars", 0, mbs);
5056
5057 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5058 fg.red, fg.green, fg.blue);
5059 dict_add_nr_str(dcell, "fg", 0, rgb);
5060 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5061 bg.red, bg.green, bg.blue);
5062 dict_add_nr_str(dcell, "bg", 0, rgb);
5063
5064 dict_add_nr_str(dcell, "attr",
5065 cell2attr(attrs, fg, bg), NULL);
5066 dict_add_nr_str(dcell, "width", width, NULL);
5067
5068 ++pos.col;
5069 if (width == 2)
5070 ++pos.col;
5071 }
5072}
5073
5074/*
5075 * "term_sendkeys(buf, keys)" function
5076 */
5077 void
5078f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5079{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005080 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005081 char_u *msg;
5082 term_T *term;
5083
5084 rettv->v_type = VAR_UNKNOWN;
5085 if (buf == NULL)
5086 return;
5087
5088 msg = get_tv_string_chk(&argvars[1]);
5089 if (msg == NULL)
5090 return;
5091 term = buf->b_term;
5092 if (term->tl_vterm == NULL)
5093 return;
5094
5095 while (*msg != NUL)
5096 {
5097 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005098 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005099 }
5100}
5101
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005102#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5103/*
5104 * "term_getansicolors(buf)" function
5105 */
5106 void
5107f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5108{
5109 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5110 term_T *term;
5111 VTermState *state;
5112 VTermColor color;
5113 char_u hexbuf[10];
5114 int index;
5115 list_T *list;
5116
5117 if (rettv_list_alloc(rettv) == FAIL)
5118 return;
5119
5120 if (buf == NULL)
5121 return;
5122 term = buf->b_term;
5123 if (term->tl_vterm == NULL)
5124 return;
5125
5126 list = rettv->vval.v_list;
5127 state = vterm_obtain_state(term->tl_vterm);
5128 for (index = 0; index < 16; index++)
5129 {
5130 vterm_state_get_palette_color(state, index, &color);
5131 sprintf((char *)hexbuf, "#%02x%02x%02x",
5132 color.red, color.green, color.blue);
5133 if (list_append_string(list, hexbuf, 7) == FAIL)
5134 return;
5135 }
5136}
5137
5138/*
5139 * "term_setansicolors(buf, list)" function
5140 */
5141 void
5142f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5143{
5144 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5145 term_T *term;
5146
5147 if (buf == NULL)
5148 return;
5149 term = buf->b_term;
5150 if (term->tl_vterm == NULL)
5151 return;
5152
5153 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5154 {
5155 EMSG(_(e_listreq));
5156 return;
5157 }
5158
5159 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5160 EMSG(_(e_invarg));
5161}
5162#endif
5163
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005164/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005165 * "term_setrestore(buf, command)" function
5166 */
5167 void
5168f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5169{
5170#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005171 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005172 term_T *term;
5173 char_u *cmd;
5174
5175 if (buf == NULL)
5176 return;
5177 term = buf->b_term;
5178 vim_free(term->tl_command);
5179 cmd = get_tv_string_chk(&argvars[1]);
5180 if (cmd != NULL)
5181 term->tl_command = vim_strsave(cmd);
5182 else
5183 term->tl_command = NULL;
5184#endif
5185}
5186
5187/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005188 * "term_setkill(buf, how)" function
5189 */
5190 void
5191f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5192{
5193 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5194 term_T *term;
5195 char_u *how;
5196
5197 if (buf == NULL)
5198 return;
5199 term = buf->b_term;
5200 vim_free(term->tl_kill);
5201 how = get_tv_string_chk(&argvars[1]);
5202 if (how != NULL)
5203 term->tl_kill = vim_strsave(how);
5204 else
5205 term->tl_kill = NULL;
5206}
5207
5208/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005209 * "term_start(command, options)" function
5210 */
5211 void
5212f_term_start(typval_T *argvars, typval_T *rettv)
5213{
5214 jobopt_T opt;
5215 buf_T *buf;
5216
5217 init_job_options(&opt);
5218 if (argvars[1].v_type != VAR_UNKNOWN
5219 && get_job_options(&argvars[1], &opt,
5220 JO_TIMEOUT_ALL + JO_STOPONEXIT
5221 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5222 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5223 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5224 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005225 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005226 + JO2_NORESTORE + JO2_TERM_KILL
5227 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005228 return;
5229
Bram Moolenaar13568252018-03-16 20:46:58 +01005230 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005231
5232 if (buf != NULL && buf->b_term != NULL)
5233 rettv->vval.v_number = buf->b_fnum;
5234}
5235
5236/*
5237 * "term_wait" function
5238 */
5239 void
5240f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5241{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005242 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005243
5244 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005245 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005246 if (buf->b_term->tl_job == NULL)
5247 {
5248 ch_log(NULL, "term_wait(): no job to wait for");
5249 return;
5250 }
5251 if (buf->b_term->tl_job->jv_channel == NULL)
5252 /* channel is closed, nothing to do */
5253 return;
5254
5255 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005256 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005257 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5258 {
5259 /* The job is dead, keep reading channel I/O until the channel is
5260 * closed. buf->b_term may become NULL if the terminal was closed while
5261 * waiting. */
5262 ch_log(NULL, "term_wait(): waiting for channel to close");
5263 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5264 {
5265 mch_check_messages();
5266 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005267 if (!buf_valid(buf))
5268 /* If the terminal is closed when the channel is closed the
5269 * buffer disappears. */
5270 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005271 ui_delay(10L, FALSE);
5272 }
5273 mch_check_messages();
5274 parse_queued_messages();
5275 }
5276 else
5277 {
5278 long wait = 10L;
5279
5280 mch_check_messages();
5281 parse_queued_messages();
5282
5283 /* Wait for some time for any channel I/O. */
5284 if (argvars[1].v_type != VAR_UNKNOWN)
5285 wait = get_tv_number(&argvars[1]);
5286 ui_delay(wait, TRUE);
5287 mch_check_messages();
5288
5289 /* Flushing messages on channels is hopefully sufficient.
5290 * TODO: is there a better way? */
5291 parse_queued_messages();
5292 }
5293}
5294
5295/*
5296 * Called when a channel has sent all the lines to a terminal.
5297 * Send a CTRL-D to mark the end of the text.
5298 */
5299 void
5300term_send_eof(channel_T *ch)
5301{
5302 term_T *term;
5303
5304 for (term = first_term; term != NULL; term = term->tl_next)
5305 if (term->tl_job == ch->ch_job)
5306 {
5307 if (term->tl_eof_chars != NULL)
5308 {
5309 channel_send(ch, PART_IN, term->tl_eof_chars,
5310 (int)STRLEN(term->tl_eof_chars), NULL);
5311 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5312 }
5313# ifdef WIN3264
5314 else
5315 /* Default: CTRL-D */
5316 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5317# endif
5318 }
5319}
5320
5321# if defined(WIN3264) || defined(PROTO)
5322
5323/**************************************
5324 * 2. MS-Windows implementation.
5325 */
5326
5327# ifndef PROTO
5328
5329#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5330#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005331#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005332
5333void* (*winpty_config_new)(UINT64, void*);
5334void* (*winpty_open)(void*, void*);
5335void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5336BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5337void (*winpty_config_set_mouse_mode)(void*, int);
5338void (*winpty_config_set_initial_size)(void*, int, int);
5339LPCWSTR (*winpty_conin_name)(void*);
5340LPCWSTR (*winpty_conout_name)(void*);
5341LPCWSTR (*winpty_conerr_name)(void*);
5342void (*winpty_free)(void*);
5343void (*winpty_config_free)(void*);
5344void (*winpty_spawn_config_free)(void*);
5345void (*winpty_error_free)(void*);
5346LPCWSTR (*winpty_error_msg)(void*);
5347BOOL (*winpty_set_size)(void*, int, int, void*);
5348HANDLE (*winpty_agent_process)(void*);
5349
5350#define WINPTY_DLL "winpty.dll"
5351
5352static HINSTANCE hWinPtyDLL = NULL;
5353# endif
5354
5355 static int
5356dyn_winpty_init(int verbose)
5357{
5358 int i;
5359 static struct
5360 {
5361 char *name;
5362 FARPROC *ptr;
5363 } winpty_entry[] =
5364 {
5365 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5366 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5367 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5368 {"winpty_config_set_mouse_mode",
5369 (FARPROC*)&winpty_config_set_mouse_mode},
5370 {"winpty_config_set_initial_size",
5371 (FARPROC*)&winpty_config_set_initial_size},
5372 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5373 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5374 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5375 {"winpty_free", (FARPROC*)&winpty_free},
5376 {"winpty_open", (FARPROC*)&winpty_open},
5377 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5378 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5379 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5380 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5381 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5382 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5383 {NULL, NULL}
5384 };
5385
5386 /* No need to initialize twice. */
5387 if (hWinPtyDLL)
5388 return OK;
5389 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5390 * winpty.dll. */
5391 if (*p_winptydll != NUL)
5392 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5393 if (!hWinPtyDLL)
5394 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5395 if (!hWinPtyDLL)
5396 {
5397 if (verbose)
5398 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5399 : (char_u *)WINPTY_DLL);
5400 return FAIL;
5401 }
5402 for (i = 0; winpty_entry[i].name != NULL
5403 && winpty_entry[i].ptr != NULL; ++i)
5404 {
5405 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5406 winpty_entry[i].name)) == NULL)
5407 {
5408 if (verbose)
5409 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5410 return FAIL;
5411 }
5412 }
5413
5414 return OK;
5415}
5416
5417/*
5418 * Create a new terminal of "rows" by "cols" cells.
5419 * Store a reference in "term".
5420 * Return OK or FAIL.
5421 */
5422 static int
5423term_and_job_init(
5424 term_T *term,
5425 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005426 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005427 jobopt_T *opt,
5428 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429{
5430 WCHAR *cmd_wchar = NULL;
5431 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005432 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005433 channel_T *channel = NULL;
5434 job_T *job = NULL;
5435 DWORD error;
5436 HANDLE jo = NULL;
5437 HANDLE child_process_handle;
5438 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005439 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005440 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005441 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005442 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005443
5444 if (dyn_winpty_init(TRUE) == FAIL)
5445 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005446 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5447 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005448
5449 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005450 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005451 cmd = argvar->vval.v_string;
5452 }
5453 else if (argvar->v_type == VAR_LIST)
5454 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005455 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005456 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005457 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005458 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005459 if (cmd == NULL || *cmd == NUL)
5460 {
5461 EMSG(_(e_invarg));
5462 goto failed;
5463 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005464
5465 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005466 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005467 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005468 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005469 if (opt->jo_cwd != NULL)
5470 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005471
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005472 win32_build_env(opt->jo_env, &ga_env, TRUE);
5473 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005474
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005475 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5476 if (term->tl_winpty_config == NULL)
5477 goto failed;
5478
5479 winpty_config_set_mouse_mode(term->tl_winpty_config,
5480 WINPTY_MOUSE_MODE_FORCE);
5481 winpty_config_set_initial_size(term->tl_winpty_config,
5482 term->tl_cols, term->tl_rows);
5483 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5484 if (term->tl_winpty == NULL)
5485 goto failed;
5486
5487 spawn_config = winpty_spawn_config_new(
5488 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5489 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5490 NULL,
5491 cmd_wchar,
5492 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005493 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005494 &winpty_err);
5495 if (spawn_config == NULL)
5496 goto failed;
5497
5498 channel = add_channel();
5499 if (channel == NULL)
5500 goto failed;
5501
5502 job = job_alloc();
5503 if (job == NULL)
5504 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005505 if (argvar->v_type == VAR_STRING)
5506 {
5507 int argc;
5508
5509 build_argv_from_string(cmd, &job->jv_argv, &argc);
5510 }
5511 else
5512 {
5513 int argc;
5514
5515 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5516 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005517
5518 if (opt->jo_set & JO_IN_BUF)
5519 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5520
5521 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5522 &child_thread_handle, &error, &winpty_err))
5523 goto failed;
5524
5525 channel_set_pipes(channel,
5526 (sock_T)CreateFileW(
5527 winpty_conin_name(term->tl_winpty),
5528 GENERIC_WRITE, 0, NULL,
5529 OPEN_EXISTING, 0, NULL),
5530 (sock_T)CreateFileW(
5531 winpty_conout_name(term->tl_winpty),
5532 GENERIC_READ, 0, NULL,
5533 OPEN_EXISTING, 0, NULL),
5534 (sock_T)CreateFileW(
5535 winpty_conerr_name(term->tl_winpty),
5536 GENERIC_READ, 0, NULL,
5537 OPEN_EXISTING, 0, NULL));
5538
5539 /* Write lines with CR instead of NL. */
5540 channel->ch_write_text_mode = TRUE;
5541
5542 jo = CreateJobObject(NULL, NULL);
5543 if (jo == NULL)
5544 goto failed;
5545
5546 if (!AssignProcessToJobObject(jo, child_process_handle))
5547 {
5548 /* Failed, switch the way to terminate process with TerminateProcess. */
5549 CloseHandle(jo);
5550 jo = NULL;
5551 }
5552
5553 winpty_spawn_config_free(spawn_config);
5554 vim_free(cmd_wchar);
5555 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005556 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005557
5558 create_vterm(term, term->tl_rows, term->tl_cols);
5559
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005560#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5561 if (opt->jo_set2 & JO2_ANSI_COLORS)
5562 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5563 else
5564 init_vterm_ansi_colors(term->tl_vterm);
5565#endif
5566
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005567 channel_set_job(channel, job, opt);
5568 job_set_options(job, opt);
5569
5570 job->jv_channel = channel;
5571 job->jv_proc_info.hProcess = child_process_handle;
5572 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5573 job->jv_job_object = jo;
5574 job->jv_status = JOB_STARTED;
5575 job->jv_tty_in = utf16_to_enc(
5576 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5577 job->jv_tty_out = utf16_to_enc(
5578 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5579 ++job->jv_refcount;
5580 term->tl_job = job;
5581
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005582 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5583 * open the file here and handle it in. opt->jo_io was changed in
5584 * setup_job_options(), use the original flags here. */
5585 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5586 {
5587 char_u *fname = opt->jo_io_name[PART_OUT];
5588
5589 ch_log(channel, "Opening output file %s", fname);
5590 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5591 if (term->tl_out_fd == NULL)
5592 EMSG2(_(e_notopen), fname);
5593 }
5594
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005595 return OK;
5596
5597failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005598 ga_clear(&ga_cmd);
5599 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005600 vim_free(cmd_wchar);
5601 vim_free(cwd_wchar);
5602 if (spawn_config != NULL)
5603 winpty_spawn_config_free(spawn_config);
5604 if (channel != NULL)
5605 channel_clear(channel);
5606 if (job != NULL)
5607 {
5608 job->jv_channel = NULL;
5609 job_cleanup(job);
5610 }
5611 term->tl_job = NULL;
5612 if (jo != NULL)
5613 CloseHandle(jo);
5614 if (term->tl_winpty != NULL)
5615 winpty_free(term->tl_winpty);
5616 term->tl_winpty = NULL;
5617 if (term->tl_winpty_config != NULL)
5618 winpty_config_free(term->tl_winpty_config);
5619 term->tl_winpty_config = NULL;
5620 if (winpty_err != NULL)
5621 {
5622 char_u *msg = utf16_to_enc(
5623 (short_u *)winpty_error_msg(winpty_err), NULL);
5624
5625 EMSG(msg);
5626 winpty_error_free(winpty_err);
5627 }
5628 return FAIL;
5629}
5630
5631 static int
5632create_pty_only(term_T *term, jobopt_T *options)
5633{
5634 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5635 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5636 char in_name[80], out_name[80];
5637 channel_T *channel = NULL;
5638
5639 create_vterm(term, term->tl_rows, term->tl_cols);
5640
5641 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5642 GetCurrentProcessId(),
5643 curbuf->b_fnum);
5644 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5645 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5646 PIPE_UNLIMITED_INSTANCES,
5647 0, 0, NMPWAIT_NOWAIT, NULL);
5648 if (hPipeIn == INVALID_HANDLE_VALUE)
5649 goto failed;
5650
5651 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5652 GetCurrentProcessId(),
5653 curbuf->b_fnum);
5654 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5655 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5656 PIPE_UNLIMITED_INSTANCES,
5657 0, 0, 0, NULL);
5658 if (hPipeOut == INVALID_HANDLE_VALUE)
5659 goto failed;
5660
5661 ConnectNamedPipe(hPipeIn, NULL);
5662 ConnectNamedPipe(hPipeOut, NULL);
5663
5664 term->tl_job = job_alloc();
5665 if (term->tl_job == NULL)
5666 goto failed;
5667 ++term->tl_job->jv_refcount;
5668
5669 /* behave like the job is already finished */
5670 term->tl_job->jv_status = JOB_FINISHED;
5671
5672 channel = add_channel();
5673 if (channel == NULL)
5674 goto failed;
5675 term->tl_job->jv_channel = channel;
5676 channel->ch_keep_open = TRUE;
5677 channel->ch_named_pipe = TRUE;
5678
5679 channel_set_pipes(channel,
5680 (sock_T)hPipeIn,
5681 (sock_T)hPipeOut,
5682 (sock_T)hPipeOut);
5683 channel_set_job(channel, term->tl_job, options);
5684 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5685 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5686
5687 return OK;
5688
5689failed:
5690 if (hPipeIn != NULL)
5691 CloseHandle(hPipeIn);
5692 if (hPipeOut != NULL)
5693 CloseHandle(hPipeOut);
5694 return FAIL;
5695}
5696
5697/*
5698 * Free the terminal emulator part of "term".
5699 */
5700 static void
5701term_free_vterm(term_T *term)
5702{
5703 if (term->tl_winpty != NULL)
5704 winpty_free(term->tl_winpty);
5705 term->tl_winpty = NULL;
5706 if (term->tl_winpty_config != NULL)
5707 winpty_config_free(term->tl_winpty_config);
5708 term->tl_winpty_config = NULL;
5709 if (term->tl_vterm != NULL)
5710 vterm_free(term->tl_vterm);
5711 term->tl_vterm = NULL;
5712}
5713
5714/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005715 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005716 */
5717 static void
5718term_report_winsize(term_T *term, int rows, int cols)
5719{
5720 if (term->tl_winpty)
5721 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5722}
5723
5724 int
5725terminal_enabled(void)
5726{
5727 return dyn_winpty_init(FALSE) == OK;
5728}
5729
5730# else
5731
5732/**************************************
5733 * 3. Unix-like implementation.
5734 */
5735
5736/*
5737 * Create a new terminal of "rows" by "cols" cells.
5738 * Start job for "cmd".
5739 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005740 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005741 * Return OK or FAIL.
5742 */
5743 static int
5744term_and_job_init(
5745 term_T *term,
5746 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005747 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005748 jobopt_T *opt,
5749 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005750{
5751 create_vterm(term, term->tl_rows, term->tl_cols);
5752
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005753#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5754 if (opt->jo_set2 & JO2_ANSI_COLORS)
5755 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5756 else
5757 init_vterm_ansi_colors(term->tl_vterm);
5758#endif
5759
Bram Moolenaar13568252018-03-16 20:46:58 +01005760 /* This may change a string in "argvar". */
5761 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005762 if (term->tl_job != NULL)
5763 ++term->tl_job->jv_refcount;
5764
5765 return term->tl_job != NULL
5766 && term->tl_job->jv_channel != NULL
5767 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5768}
5769
5770 static int
5771create_pty_only(term_T *term, jobopt_T *opt)
5772{
5773 create_vterm(term, term->tl_rows, term->tl_cols);
5774
5775 term->tl_job = job_alloc();
5776 if (term->tl_job == NULL)
5777 return FAIL;
5778 ++term->tl_job->jv_refcount;
5779
5780 /* behave like the job is already finished */
5781 term->tl_job->jv_status = JOB_FINISHED;
5782
5783 return mch_create_pty_channel(term->tl_job, opt);
5784}
5785
5786/*
5787 * Free the terminal emulator part of "term".
5788 */
5789 static void
5790term_free_vterm(term_T *term)
5791{
5792 if (term->tl_vterm != NULL)
5793 vterm_free(term->tl_vterm);
5794 term->tl_vterm = NULL;
5795}
5796
5797/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005798 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005799 */
5800 static void
5801term_report_winsize(term_T *term, int rows, int cols)
5802{
5803 /* Use an ioctl() to report the new window size to the job. */
5804 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5805 {
5806 int fd = -1;
5807 int part;
5808
5809 for (part = PART_OUT; part < PART_COUNT; ++part)
5810 {
5811 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5812 if (isatty(fd))
5813 break;
5814 }
5815 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5816 mch_signal_job(term->tl_job, (char_u *)"winch");
5817 }
5818}
5819
5820# endif
5821
5822#endif /* FEAT_TERMINAL */