blob: 945adc5c10bb27bb725d35b4925d812afededf42 [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. */
174static char_u *last_set_cursor_color = (char_u *)"";
175static char_u *desired_cursor_color = (char_u *)"";
176static 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
186/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200187 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200188 * current window.
189 * Sets "rows" and/or "cols" to zero when it should follow the window size.
190 * Return TRUE if the size is the minimum size: "24*80".
191 */
192 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200193parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200194{
195 int minsize = FALSE;
196
197 *rows = 0;
198 *cols = 0;
199
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200200 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200201 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200202 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200203
204 /* Syntax of value was already checked when it's set. */
205 if (p == NULL)
206 {
207 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200208 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200209 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200210 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200211 *cols = atoi((char *)p + 1);
212 }
213 return minsize;
214}
215
216/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200217 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200218 */
219 static void
220set_term_and_win_size(term_T *term)
221{
Bram Moolenaar13568252018-03-16 20:46:58 +0100222#ifdef FEAT_GUI
223 if (term->tl_system)
224 {
225 /* Use the whole screen for the system command. However, it will start
226 * at the command line and scroll up as needed, using tl_toprow. */
227 term->tl_rows = Rows;
228 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200229 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100230 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100231#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200232 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200233 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200234 if (term->tl_rows != 0)
235 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
236 if (term->tl_cols != 0)
237 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200238 }
239 if (term->tl_rows == 0)
240 term->tl_rows = curwin->w_height;
241 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200242 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200243 if (term->tl_cols == 0)
244 term->tl_cols = curwin->w_width;
245 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200246 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200247}
248
249/*
250 * Initialize job options for a terminal job.
251 * Caller may overrule some of them.
252 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100253 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200254init_job_options(jobopt_T *opt)
255{
256 clear_job_options(opt);
257
258 opt->jo_mode = MODE_RAW;
259 opt->jo_out_mode = MODE_RAW;
260 opt->jo_err_mode = MODE_RAW;
261 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
262}
263
264/*
265 * Set job options mandatory for a terminal job.
266 */
267 static void
268setup_job_options(jobopt_T *opt, int rows, int cols)
269{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200270#ifndef WIN3264
271 /* Win32: Redirecting the job output won't work, thus always connect stdout
272 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200273 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200274#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275 {
276 /* Connect stdout to the terminal. */
277 opt->jo_io[PART_OUT] = JIO_BUFFER;
278 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
279 opt->jo_modifiable[PART_OUT] = 0;
280 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
281 }
282
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200283#ifndef WIN3264
284 /* Win32: Redirecting the job output won't work, thus always connect stderr
285 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200286 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200287#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200288 {
289 /* Connect stderr to the terminal. */
290 opt->jo_io[PART_ERR] = JIO_BUFFER;
291 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
292 opt->jo_modifiable[PART_ERR] = 0;
293 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
294 }
295
296 opt->jo_pty = TRUE;
297 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
298 opt->jo_term_rows = rows;
299 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
300 opt->jo_term_cols = cols;
301}
302
303/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100304 * Close a terminal buffer (and its window). Used when creating the terminal
305 * fails.
306 */
307 static void
308term_close_buffer(buf_T *buf, buf_T *old_curbuf)
309{
310 free_terminal(buf);
311 if (old_curbuf != NULL)
312 {
313 --curbuf->b_nwindows;
314 curbuf = old_curbuf;
315 curwin->w_buffer = curbuf;
316 ++curbuf->b_nwindows;
317 }
318
319 /* Wiping out the buffer will also close the window and call
320 * free_terminal(). */
321 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
322}
323
324/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200325 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100326 * Use either "argvar" or "argv", the other must be NULL.
327 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
328 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200329 * Returns NULL when failed.
330 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100331 buf_T *
332term_start(
333 typval_T *argvar,
334 char **argv,
335 jobopt_T *opt,
336 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200337{
338 exarg_T split_ea;
339 win_T *old_curwin = curwin;
340 term_T *term;
341 buf_T *old_curbuf = NULL;
342 int res;
343 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100344 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200345 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346
347 if (check_restricted() || check_secure())
348 return NULL;
349
350 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
351 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
352 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
353 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
354 {
355 EMSG(_(e_invarg));
356 return NULL;
357 }
358
359 term = (term_T *)alloc_clear(sizeof(term_T));
360 if (term == NULL)
361 return NULL;
362 term->tl_dirty_row_end = MAX_ROW;
363 term->tl_cursor_visible = TRUE;
364 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
365 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100366#ifdef FEAT_GUI
367 term->tl_system = (flags & TERM_START_SYSTEM);
368#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
370
371 vim_memset(&split_ea, 0, sizeof(split_ea));
372 if (opt->jo_curwin)
373 {
374 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100375 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200376 {
377 no_write_message();
378 vim_free(term);
379 return NULL;
380 }
381 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100382 ECMD_HIDE
383 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
384 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200385 {
386 vim_free(term);
387 return NULL;
388 }
389 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100390 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200391 {
392 buf_T *buf;
393
394 /* Create a new buffer without a window. Make it the current buffer for
395 * a moment to be able to do the initialisations. */
396 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
397 BLN_NEW | BLN_LISTED);
398 if (buf == NULL || ml_open(buf) == FAIL)
399 {
400 vim_free(term);
401 return NULL;
402 }
403 old_curbuf = curbuf;
404 --curbuf->b_nwindows;
405 curbuf = buf;
406 curwin->w_buffer = buf;
407 ++curbuf->b_nwindows;
408 }
409 else
410 {
411 /* Open a new window or tab. */
412 split_ea.cmdidx = CMD_new;
413 split_ea.cmd = (char_u *)"new";
414 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100415 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200416 {
417 split_ea.line2 = opt->jo_term_rows;
418 split_ea.addr_count = 1;
419 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100420 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200421 {
422 split_ea.line2 = opt->jo_term_cols;
423 split_ea.addr_count = 1;
424 }
425
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100426 if (vertical)
427 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 ex_splitview(&split_ea);
429 if (curwin == old_curwin)
430 {
431 /* split failed */
432 vim_free(term);
433 return NULL;
434 }
435 }
436 term->tl_buffer = curbuf;
437 curbuf->b_term = term;
438
439 if (!opt->jo_hidden)
440 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100441 /* Only one size was taken care of with :new, do the other one. With
442 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100443 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200444 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100445 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200446 win_setwidth(opt->jo_term_cols);
447 }
448
449 /* Link the new terminal in the list of active terminals. */
450 term->tl_next = first_term;
451 first_term = term;
452
453 if (opt->jo_term_name != NULL)
454 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100455 else if (argv != NULL)
456 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457 else
458 {
459 int i;
460 size_t len;
461 char_u *cmd, *p;
462
463 if (argvar->v_type == VAR_STRING)
464 {
465 cmd = argvar->vval.v_string;
466 if (cmd == NULL)
467 cmd = (char_u *)"";
468 else if (STRCMP(cmd, "NONE") == 0)
469 cmd = (char_u *)"pty";
470 }
471 else if (argvar->v_type != VAR_LIST
472 || argvar->vval.v_list == NULL
473 || argvar->vval.v_list->lv_len < 1
474 || (cmd = get_tv_string_chk(
475 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
476 cmd = (char_u*)"";
477
478 len = STRLEN(cmd) + 10;
479 p = alloc((int)len);
480
481 for (i = 0; p != NULL; ++i)
482 {
483 /* Prepend a ! to the command name to avoid the buffer name equals
484 * the executable, otherwise ":w!" would overwrite it. */
485 if (i == 0)
486 vim_snprintf((char *)p, len, "!%s", cmd);
487 else
488 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
489 if (buflist_findname(p) == NULL)
490 {
491 vim_free(curbuf->b_ffname);
492 curbuf->b_ffname = p;
493 break;
494 }
495 }
496 }
497 curbuf->b_fname = curbuf->b_ffname;
498
499 if (opt->jo_term_opencmd != NULL)
500 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
501
502 if (opt->jo_eof_chars != NULL)
503 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
504
505 set_string_option_direct((char_u *)"buftype", -1,
506 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
507
508 /* Mark the buffer as not modifiable. It can only be made modifiable after
509 * the job finished. */
510 curbuf->b_p_ma = FALSE;
511
512 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200513#ifdef WIN3264
514 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
515#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200516 setup_job_options(opt, term->tl_rows, term->tl_cols);
517
Bram Moolenaar13568252018-03-16 20:46:58 +0100518 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100519 return curbuf;
520
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100521#if defined(FEAT_SESSION)
522 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100523 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100524 {
525 term->tl_command = vim_strsave((char_u *)"NONE");
526 }
527 else if (argvar->v_type == VAR_STRING)
528 {
529 char_u *cmd = argvar->vval.v_string;
530
531 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
532 term->tl_command = vim_strsave(cmd);
533 }
534 else if (argvar->v_type == VAR_LIST
535 && argvar->vval.v_list != NULL
536 && argvar->vval.v_list->lv_len > 0)
537 {
538 garray_T ga;
539 listitem_T *item;
540
541 ga_init2(&ga, 1, 100);
542 for (item = argvar->vval.v_list->lv_first;
543 item != NULL; item = item->li_next)
544 {
545 char_u *s = get_tv_string_chk(&item->li_tv);
546 char_u *p;
547
548 if (s == NULL)
549 break;
550 p = vim_strsave_fnameescape(s, FALSE);
551 if (p == NULL)
552 break;
553 ga_concat(&ga, p);
554 vim_free(p);
555 ga_append(&ga, ' ');
556 }
557 if (item == NULL)
558 {
559 ga_append(&ga, NUL);
560 term->tl_command = ga.ga_data;
561 }
562 else
563 ga_clear(&ga);
564 }
565#endif
566
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100567 if (opt->jo_term_kill != NULL)
568 {
569 char_u *p = skiptowhite(opt->jo_term_kill);
570
571 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
572 }
573
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200574 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100575 if (argv == NULL
576 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577 && argvar->vval.v_string != NULL
578 && STRCMP(argvar->vval.v_string, "NONE") == 0)
579 res = create_pty_only(term, opt);
580 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200581 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582
583 newbuf = curbuf;
584 if (res == OK)
585 {
586 /* Get and remember the size we ended up with. Update the pty. */
587 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
588 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100589#ifdef FEAT_GUI
590 if (term->tl_system)
591 {
592 /* display first line below typed command */
593 term->tl_toprow = msg_row + 1;
594 term->tl_dirty_row_end = 0;
595 }
596#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200597
598 /* Make sure we don't get stuck on sending keys to the job, it leads to
599 * a deadlock if the job is waiting for Vim to read. */
600 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
601
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200602 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603 {
604 --curbuf->b_nwindows;
605 curbuf = old_curbuf;
606 curwin->w_buffer = curbuf;
607 ++curbuf->b_nwindows;
608 }
609 }
610 else
611 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100612 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200613 return NULL;
614 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100615
Bram Moolenaar13568252018-03-16 20:46:58 +0100616 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 return newbuf;
618}
619
620/*
621 * ":terminal": open a terminal window and execute a job in it.
622 */
623 void
624ex_terminal(exarg_T *eap)
625{
626 typval_T argvar[2];
627 jobopt_T opt;
628 char_u *cmd;
629 char_u *tofree = NULL;
630
631 init_job_options(&opt);
632
633 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100634 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200635 {
636 char_u *p, *ep;
637
638 cmd += 2;
639 p = skiptowhite(cmd);
640 ep = vim_strchr(cmd, '=');
641 if (ep != NULL && ep < p)
642 p = ep;
643
644 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
645 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100646 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
647 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200648 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
649 opt.jo_term_finish = 'o';
650 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
651 opt.jo_curwin = 1;
652 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
653 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100654 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
655 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100656 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
657 && ep != NULL)
658 {
659 opt.jo_set2 |= JO2_TERM_KILL;
660 opt.jo_term_kill = ep + 1;
661 p = skiptowhite(cmd);
662 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
664 && ep != NULL && isdigit(ep[1]))
665 {
666 opt.jo_set2 |= JO2_TERM_ROWS;
667 opt.jo_term_rows = atoi((char *)ep + 1);
668 p = skiptowhite(cmd);
669 }
670 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
671 && ep != NULL && isdigit(ep[1]))
672 {
673 opt.jo_set2 |= JO2_TERM_COLS;
674 opt.jo_term_cols = atoi((char *)ep + 1);
675 p = skiptowhite(cmd);
676 }
677 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
678 && ep != NULL)
679 {
680 char_u *buf = NULL;
681 char_u *keys;
682
683 p = skiptowhite(cmd);
684 *p = NUL;
685 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
686 opt.jo_set2 |= JO2_EOF_CHARS;
687 opt.jo_eof_chars = vim_strsave(keys);
688 vim_free(buf);
689 *p = ' ';
690 }
691 else
692 {
693 if (*p)
694 *p = NUL;
695 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100696 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200697 }
698 cmd = skipwhite(p);
699 }
700 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100701 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200702 /* Make a copy of 'shell', an autocommand may change the option. */
703 tofree = cmd = vim_strsave(p_sh);
704
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100705 /* default to close when the shell exits */
706 if (opt.jo_term_finish == NUL)
707 opt.jo_term_finish = 'c';
708 }
709
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200710 if (eap->addr_count > 0)
711 {
712 /* Write lines from current buffer to the job. */
713 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
714 opt.jo_io[PART_IN] = JIO_BUFFER;
715 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
716 opt.jo_in_top = eap->line1;
717 opt.jo_in_bot = eap->line2;
718 }
719
720 argvar[0].v_type = VAR_STRING;
721 argvar[0].vval.v_string = cmd;
722 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100723 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100725
726theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727 vim_free(opt.jo_eof_chars);
728}
729
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100730#if defined(FEAT_SESSION) || defined(PROTO)
731/*
732 * Write a :terminal command to the session file to restore the terminal in
733 * window "wp".
734 * Return FAIL if writing fails.
735 */
736 int
737term_write_session(FILE *fd, win_T *wp)
738{
739 term_T *term = wp->w_buffer->b_term;
740
741 /* Create the terminal and run the command. This is not without
742 * risk, but let's assume the user only creates a session when this
743 * will be OK. */
744 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
745 term->tl_cols, term->tl_rows) < 0)
746 return FAIL;
747 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
748 return FAIL;
749
750 return put_eol(fd);
751}
752
753/*
754 * Return TRUE if "buf" has a terminal that should be restored.
755 */
756 int
757term_should_restore(buf_T *buf)
758{
759 term_T *term = buf->b_term;
760
761 return term != NULL && (term->tl_command == NULL
762 || STRCMP(term->tl_command, "NONE") != 0);
763}
764#endif
765
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200766/*
767 * Free the scrollback buffer for "term".
768 */
769 static void
770free_scrollback(term_T *term)
771{
772 int i;
773
774 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
775 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
776 ga_clear(&term->tl_scrollback);
777}
778
779/*
780 * Free a terminal and everything it refers to.
781 * Kills the job if there is one.
782 * Called when wiping out a buffer.
783 */
784 void
785free_terminal(buf_T *buf)
786{
787 term_T *term = buf->b_term;
788 term_T *tp;
789
790 if (term == NULL)
791 return;
792 if (first_term == term)
793 first_term = term->tl_next;
794 else
795 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
796 if (tp->tl_next == term)
797 {
798 tp->tl_next = term->tl_next;
799 break;
800 }
801
802 if (term->tl_job != NULL)
803 {
804 if (term->tl_job->jv_status != JOB_ENDED
805 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100806 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 job_stop(term->tl_job, NULL, "kill");
808 job_unref(term->tl_job);
809 }
810
811 free_scrollback(term);
812
813 term_free_vterm(term);
814 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100815#ifdef FEAT_SESSION
816 vim_free(term->tl_command);
817#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100818 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 vim_free(term->tl_status_text);
820 vim_free(term->tl_opencmd);
821 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200822#ifdef WIN3264
823 if (term->tl_out_fd != NULL)
824 fclose(term->tl_out_fd);
825#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100826 if (desired_cursor_color == term->tl_cursor_color)
827 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 vim_free(term->tl_cursor_color);
829 vim_free(term);
830 buf->b_term = NULL;
831 if (in_terminal_loop == term)
832 in_terminal_loop = NULL;
833}
834
835/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100836 * Get the part that is connected to the tty. Normally this is PART_IN, but
837 * when writing buffer lines to the job it can be another. This makes it
838 * possible to do "1,5term vim -".
839 */
840 static ch_part_T
841get_tty_part(term_T *term)
842{
843#ifdef UNIX
844 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
845 int i;
846
847 for (i = 0; i < 3; ++i)
848 {
849 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
850
851 if (isatty(fd))
852 return parts[i];
853 }
854#endif
855 return PART_IN;
856}
857
858/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859 * Write job output "msg[len]" to the vterm.
860 */
861 static void
862term_write_job_output(term_T *term, char_u *msg, size_t len)
863{
864 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100865 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200866
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100867 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200868
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100869 /* flush vterm buffer when vterm responded to control sequence */
870 if (prevlen != vterm_output_get_buffer_current(vterm))
871 {
872 char buf[KEY_BUF_LEN];
873 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
874
875 if (curlen > 0)
876 channel_send(term->tl_job->jv_channel, get_tty_part(term),
877 (char_u *)buf, (int)curlen, NULL);
878 }
879
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880 /* this invokes the damage callbacks */
881 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
882}
883
884 static void
885update_cursor(term_T *term, int redraw)
886{
887 if (term->tl_normal_mode)
888 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100889#ifdef FEAT_GUI
890 if (term->tl_system)
891 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
892 term->tl_cursor_pos.col);
893 else
894#endif
895 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200896 if (redraw)
897 {
898 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
899 cursor_on();
900 out_flush();
901#ifdef FEAT_GUI
902 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100903 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200904 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100905 gui_mch_flush();
906 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200907#endif
908 }
909}
910
911/*
912 * Invoked when "msg" output from a job was received. Write it to the terminal
913 * of "buffer".
914 */
915 void
916write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
917{
918 size_t len = STRLEN(msg);
919 term_T *term = buffer->b_term;
920
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200921#ifdef WIN3264
922 /* Win32: Cannot redirect output of the job, intercept it here and write to
923 * the file. */
924 if (term->tl_out_fd != NULL)
925 {
926 ch_log(channel, "Writing %d bytes to output file", (int)len);
927 fwrite(msg, len, 1, term->tl_out_fd);
928 return;
929 }
930#endif
931
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200932 if (term->tl_vterm == NULL)
933 {
934 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
935 return;
936 }
937 ch_log(channel, "writing %d bytes to terminal", (int)len);
938 term_write_job_output(term, msg, len);
939
Bram Moolenaar13568252018-03-16 20:46:58 +0100940#ifdef FEAT_GUI
941 if (term->tl_system)
942 {
943 /* show system output, scrolling up the screen as needed */
944 update_system_term(term);
945 update_cursor(term, TRUE);
946 }
947 else
948#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200949 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
950 * contents, thus no screen update is needed. */
951 if (!term->tl_normal_mode)
952 {
953 /* TODO: only update once in a while. */
954 ch_log(term->tl_job->jv_channel, "updating screen");
955 if (buffer == curbuf)
956 {
957 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200958 /* update_screen() can be slow, check the terminal wasn't closed
959 * already */
960 if (buffer == curbuf && curbuf->b_term != NULL)
961 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200962 }
963 else
964 redraw_after_callback(TRUE);
965 }
966}
967
968/*
969 * Send a mouse position and click to the vterm
970 */
971 static int
972term_send_mouse(VTerm *vterm, int button, int pressed)
973{
974 VTermModifier mod = VTERM_MOD_NONE;
975
976 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200977 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100978 if (button != 0)
979 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200980 return TRUE;
981}
982
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100983static int enter_mouse_col = -1;
984static int enter_mouse_row = -1;
985
986/*
987 * Handle a mouse click, drag or release.
988 * Return TRUE when a mouse event is sent to the terminal.
989 */
990 static int
991term_mouse_click(VTerm *vterm, int key)
992{
993#if defined(FEAT_CLIPBOARD)
994 /* For modeless selection mouse drag and release events are ignored, unless
995 * they are preceded with a mouse down event */
996 static int ignore_drag_release = TRUE;
997 VTermMouseState mouse_state;
998
999 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1000 if (mouse_state.flags == 0)
1001 {
1002 /* Terminal is not using the mouse, use modeless selection. */
1003 switch (key)
1004 {
1005 case K_LEFTDRAG:
1006 case K_LEFTRELEASE:
1007 case K_RIGHTDRAG:
1008 case K_RIGHTRELEASE:
1009 /* Ignore drag and release events when the button-down wasn't
1010 * seen before. */
1011 if (ignore_drag_release)
1012 {
1013 int save_mouse_col, save_mouse_row;
1014
1015 if (enter_mouse_col < 0)
1016 break;
1017
1018 /* mouse click in the window gave us focus, handle that
1019 * click now */
1020 save_mouse_col = mouse_col;
1021 save_mouse_row = mouse_row;
1022 mouse_col = enter_mouse_col;
1023 mouse_row = enter_mouse_row;
1024 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1025 mouse_col = save_mouse_col;
1026 mouse_row = save_mouse_row;
1027 }
1028 /* FALLTHROUGH */
1029 case K_LEFTMOUSE:
1030 case K_RIGHTMOUSE:
1031 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1032 ignore_drag_release = TRUE;
1033 else
1034 ignore_drag_release = FALSE;
1035 /* Should we call mouse_has() here? */
1036 if (clip_star.available)
1037 {
1038 int button, is_click, is_drag;
1039
1040 button = get_mouse_button(KEY2TERMCAP1(key),
1041 &is_click, &is_drag);
1042 if (mouse_model_popup() && button == MOUSE_LEFT
1043 && (mod_mask & MOD_MASK_SHIFT))
1044 {
1045 /* Translate shift-left to right button. */
1046 button = MOUSE_RIGHT;
1047 mod_mask &= ~MOD_MASK_SHIFT;
1048 }
1049 clip_modeless(button, is_click, is_drag);
1050 }
1051 break;
1052
1053 case K_MIDDLEMOUSE:
1054 if (clip_star.available)
1055 insert_reg('*', TRUE);
1056 break;
1057 }
1058 enter_mouse_col = -1;
1059 return FALSE;
1060 }
1061#endif
1062 enter_mouse_col = -1;
1063
1064 switch (key)
1065 {
1066 case K_LEFTMOUSE:
1067 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1068 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1069 case K_LEFTRELEASE:
1070 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1071 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1072 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1073 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1074 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1075 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1076 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1077 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1078 }
1079 return TRUE;
1080}
1081
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001082/*
1083 * Convert typed key "c" into bytes to send to the job.
1084 * Return the number of bytes in "buf".
1085 */
1086 static int
1087term_convert_key(term_T *term, int c, char *buf)
1088{
1089 VTerm *vterm = term->tl_vterm;
1090 VTermKey key = VTERM_KEY_NONE;
1091 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001092 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093
1094 switch (c)
1095 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001096 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1097
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001098 /* don't use VTERM_KEY_BACKSPACE, it always
1099 * becomes 0x7f DEL */
1100 case K_BS: c = term_backspace_char; break;
1101
1102 case ESC: key = VTERM_KEY_ESCAPE; break;
1103 case K_DEL: key = VTERM_KEY_DEL; break;
1104 case K_DOWN: key = VTERM_KEY_DOWN; break;
1105 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1106 key = VTERM_KEY_DOWN; break;
1107 case K_END: key = VTERM_KEY_END; break;
1108 case K_S_END: mod = VTERM_MOD_SHIFT;
1109 key = VTERM_KEY_END; break;
1110 case K_C_END: mod = VTERM_MOD_CTRL;
1111 key = VTERM_KEY_END; break;
1112 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1113 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1114 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1115 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1116 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1117 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1118 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1119 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1120 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1121 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1122 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1123 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1124 case K_HOME: key = VTERM_KEY_HOME; break;
1125 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1126 key = VTERM_KEY_HOME; break;
1127 case K_C_HOME: mod = VTERM_MOD_CTRL;
1128 key = VTERM_KEY_HOME; break;
1129 case K_INS: key = VTERM_KEY_INS; break;
1130 case K_K0: key = VTERM_KEY_KP_0; break;
1131 case K_K1: key = VTERM_KEY_KP_1; break;
1132 case K_K2: key = VTERM_KEY_KP_2; break;
1133 case K_K3: key = VTERM_KEY_KP_3; break;
1134 case K_K4: key = VTERM_KEY_KP_4; break;
1135 case K_K5: key = VTERM_KEY_KP_5; break;
1136 case K_K6: key = VTERM_KEY_KP_6; break;
1137 case K_K7: key = VTERM_KEY_KP_7; break;
1138 case K_K8: key = VTERM_KEY_KP_8; break;
1139 case K_K9: key = VTERM_KEY_KP_9; break;
1140 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1141 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1142 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1143 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1144 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1145 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1146 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1147 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1148 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1149 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1150 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1151 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1152 case K_LEFT: key = VTERM_KEY_LEFT; break;
1153 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1154 key = VTERM_KEY_LEFT; break;
1155 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1156 key = VTERM_KEY_LEFT; break;
1157 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1158 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1159 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1160 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1161 key = VTERM_KEY_RIGHT; break;
1162 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1163 key = VTERM_KEY_RIGHT; break;
1164 case K_UP: key = VTERM_KEY_UP; break;
1165 case K_S_UP: mod = VTERM_MOD_SHIFT;
1166 key = VTERM_KEY_UP; break;
1167 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001168 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1169 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001170
Bram Moolenaara42ad572017-11-16 13:08:04 +01001171 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1172 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001173 case K_MOUSELEFT: /* TODO */ return 0;
1174 case K_MOUSERIGHT: /* TODO */ return 0;
1175
1176 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001177 case K_LEFTMOUSE_NM:
1178 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001179 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001180 case K_LEFTRELEASE_NM:
1181 case K_MOUSEMOVE:
1182 case K_MIDDLEMOUSE:
1183 case K_MIDDLEDRAG:
1184 case K_MIDDLERELEASE:
1185 case K_RIGHTMOUSE:
1186 case K_RIGHTDRAG:
1187 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1188 return 0;
1189 other = TRUE;
1190 break;
1191
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001192 case K_X1MOUSE: /* TODO */ return 0;
1193 case K_X1DRAG: /* TODO */ return 0;
1194 case K_X1RELEASE: /* TODO */ return 0;
1195 case K_X2MOUSE: /* TODO */ return 0;
1196 case K_X2DRAG: /* TODO */ return 0;
1197 case K_X2RELEASE: /* TODO */ return 0;
1198
1199 case K_IGNORE: return 0;
1200 case K_NOP: return 0;
1201 case K_UNDO: return 0;
1202 case K_HELP: return 0;
1203 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1204 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1205 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1206 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1207 case K_SELECT: return 0;
1208#ifdef FEAT_GUI
1209 case K_VER_SCROLLBAR: return 0;
1210 case K_HOR_SCROLLBAR: return 0;
1211#endif
1212#ifdef FEAT_GUI_TABLINE
1213 case K_TABLINE: return 0;
1214 case K_TABMENU: return 0;
1215#endif
1216#ifdef FEAT_NETBEANS_INTG
1217 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1218#endif
1219#ifdef FEAT_DND
1220 case K_DROP: return 0;
1221#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001222 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001223 case K_PS: vterm_keyboard_start_paste(vterm);
1224 other = TRUE;
1225 break;
1226 case K_PE: vterm_keyboard_end_paste(vterm);
1227 other = TRUE;
1228 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001229 }
1230
1231 /*
1232 * Convert special keys to vterm keys:
1233 * - Write keys to vterm: vterm_keyboard_key()
1234 * - Write output to channel.
1235 * TODO: use mod_mask
1236 */
1237 if (key != VTERM_KEY_NONE)
1238 /* Special key, let vterm convert it. */
1239 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001240 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001241 /* Normal character, let vterm convert it. */
1242 vterm_keyboard_unichar(vterm, c, mod);
1243
1244 /* Read back the converted escape sequence. */
1245 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1246}
1247
1248/*
1249 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001250 * If "check_job_status" is TRUE update the job status.
1251 */
1252 static int
1253term_job_running_check(term_T *term, int check_job_status)
1254{
1255 /* Also consider the job finished when the channel is closed, to avoid a
1256 * race condition when updating the title. */
1257 if (term != NULL
1258 && term->tl_job != NULL
1259 && channel_is_open(term->tl_job->jv_channel))
1260 {
1261 if (check_job_status)
1262 job_status(term->tl_job);
1263 return (term->tl_job->jv_status == JOB_STARTED
1264 || term->tl_job->jv_channel->ch_keep_open);
1265 }
1266 return FALSE;
1267}
1268
1269/*
1270 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001271 */
1272 int
1273term_job_running(term_T *term)
1274{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001275 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001276}
1277
1278/*
1279 * Return TRUE if "term" has an active channel and used ":term NONE".
1280 */
1281 int
1282term_none_open(term_T *term)
1283{
1284 /* Also consider the job finished when the channel is closed, to avoid a
1285 * race condition when updating the title. */
1286 return term != NULL
1287 && term->tl_job != NULL
1288 && channel_is_open(term->tl_job->jv_channel)
1289 && term->tl_job->jv_channel->ch_keep_open;
1290}
1291
1292/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001293 * Used when exiting: kill the job in "buf" if so desired.
1294 * Return OK when the job finished.
1295 * Return FAIL when the job is still running.
1296 */
1297 int
1298term_try_stop_job(buf_T *buf)
1299{
1300 int count;
1301 char *how = (char *)buf->b_term->tl_kill;
1302
1303#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1304 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1305 {
1306 char_u buff[DIALOG_MSG_SIZE];
1307 int ret;
1308
1309 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1310 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1311 if (ret == VIM_YES)
1312 how = "kill";
1313 else if (ret == VIM_CANCEL)
1314 return FAIL;
1315 }
1316#endif
1317 if (how == NULL || *how == NUL)
1318 return FAIL;
1319
1320 job_stop(buf->b_term->tl_job, NULL, how);
1321
1322 /* wait for up to a second for the job to die */
1323 for (count = 0; count < 100; ++count)
1324 {
1325 /* buffer, terminal and job may be cleaned up while waiting */
1326 if (!buf_valid(buf)
1327 || buf->b_term == NULL
1328 || buf->b_term->tl_job == NULL)
1329 return OK;
1330
1331 /* call job_status() to update jv_status */
1332 job_status(buf->b_term->tl_job);
1333 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1334 return OK;
1335 ui_delay(10L, FALSE);
1336 mch_check_messages();
1337 parse_queued_messages();
1338 }
1339 return FAIL;
1340}
1341
1342/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 * Add the last line of the scrollback buffer to the buffer in the window.
1344 */
1345 static void
1346add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1347{
1348 buf_T *buf = term->tl_buffer;
1349 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1350 linenr_T lnum = buf->b_ml.ml_line_count;
1351
1352#ifdef WIN3264
1353 if (!enc_utf8 && enc_codepage > 0)
1354 {
1355 WCHAR *ret = NULL;
1356 int length = 0;
1357
1358 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1359 &ret, &length);
1360 if (ret != NULL)
1361 {
1362 WideCharToMultiByte_alloc(enc_codepage, 0,
1363 ret, length, (char **)&text, &len, 0, 0);
1364 vim_free(ret);
1365 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1366 vim_free(text);
1367 }
1368 }
1369 else
1370#endif
1371 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1372 if (empty)
1373 {
1374 /* Delete the empty line that was in the empty buffer. */
1375 curbuf = buf;
1376 ml_delete(1, FALSE);
1377 curbuf = curwin->w_buffer;
1378 }
1379}
1380
1381 static void
1382cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1383{
1384 attr->width = cell->width;
1385 attr->attrs = cell->attrs;
1386 attr->fg = cell->fg;
1387 attr->bg = cell->bg;
1388}
1389
1390 static int
1391equal_celattr(cellattr_T *a, cellattr_T *b)
1392{
1393 /* Comparing the colors should be sufficient. */
1394 return a->fg.red == b->fg.red
1395 && a->fg.green == b->fg.green
1396 && a->fg.blue == b->fg.blue
1397 && a->bg.red == b->bg.red
1398 && a->bg.green == b->bg.green
1399 && a->bg.blue == b->bg.blue;
1400}
1401
Bram Moolenaard96ff162018-02-18 22:13:29 +01001402/*
1403 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1404 * line at this position. Otherwise at the end.
1405 */
1406 static int
1407add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1408{
1409 if (ga_grow(&term->tl_scrollback, 1) == OK)
1410 {
1411 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1412 + term->tl_scrollback.ga_len;
1413
1414 if (lnum > 0)
1415 {
1416 int i;
1417
1418 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1419 {
1420 *line = *(line - 1);
1421 --line;
1422 }
1423 }
1424 line->sb_cols = 0;
1425 line->sb_cells = NULL;
1426 line->sb_fill_attr = *fill_attr;
1427 ++term->tl_scrollback.ga_len;
1428 return OK;
1429 }
1430 return FALSE;
1431}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001432
1433/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001434 * Remove the terminal contents from the scrollback and the buffer.
1435 * Used before adding a new scrollback line or updating the buffer for lines
1436 * displayed in the terminal.
1437 */
1438 static void
1439cleanup_scrollback(term_T *term)
1440{
1441 sb_line_T *line;
1442 garray_T *gap;
1443
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001444 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001445 gap = &term->tl_scrollback;
1446 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1447 && gap->ga_len > 0)
1448 {
1449 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1450 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1451 vim_free(line->sb_cells);
1452 --gap->ga_len;
1453 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001454 curbuf = curwin->w_buffer;
1455 if (curbuf == term->tl_buffer)
1456 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001457}
1458
1459/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001460 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001461 */
1462 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001463update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001464{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001465 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001466 int len;
1467 int lines_skipped = 0;
1468 VTermPos pos;
1469 VTermScreenCell cell;
1470 cellattr_T fill_attr, new_fill_attr;
1471 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001472
1473 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1474 "Adding terminal window snapshot to buffer");
1475
1476 /* First remove the lines that were appended before, they might be
1477 * outdated. */
1478 cleanup_scrollback(term);
1479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001480 screen = vterm_obtain_screen(term->tl_vterm);
1481 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1483 {
1484 len = 0;
1485 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1486 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1487 && cell.chars[0] != NUL)
1488 {
1489 len = pos.col + 1;
1490 new_fill_attr = term->tl_default_color;
1491 }
1492 else
1493 /* Assume the last attr is the filler attr. */
1494 cell2cellattr(&cell, &new_fill_attr);
1495
1496 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1497 ++lines_skipped;
1498 else
1499 {
1500 while (lines_skipped > 0)
1501 {
1502 /* Line was skipped, add an empty line. */
1503 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001504 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001505 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001506 }
1507
1508 if (len == 0)
1509 p = NULL;
1510 else
1511 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1512 if ((p != NULL || len == 0)
1513 && ga_grow(&term->tl_scrollback, 1) == OK)
1514 {
1515 garray_T ga;
1516 int width;
1517 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1518 + term->tl_scrollback.ga_len;
1519
1520 ga_init2(&ga, 1, 100);
1521 for (pos.col = 0; pos.col < len; pos.col += width)
1522 {
1523 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1524 {
1525 width = 1;
1526 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1527 if (ga_grow(&ga, 1) == OK)
1528 ga.ga_len += utf_char2bytes(' ',
1529 (char_u *)ga.ga_data + ga.ga_len);
1530 }
1531 else
1532 {
1533 width = cell.width;
1534
1535 cell2cellattr(&cell, &p[pos.col]);
1536
1537 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1538 {
1539 int i;
1540 int c;
1541
1542 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1543 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1544 (char_u *)ga.ga_data + ga.ga_len);
1545 }
1546 }
1547 }
1548 line->sb_cols = len;
1549 line->sb_cells = p;
1550 line->sb_fill_attr = new_fill_attr;
1551 fill_attr = new_fill_attr;
1552 ++term->tl_scrollback.ga_len;
1553
1554 if (ga_grow(&ga, 1) == FAIL)
1555 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1556 else
1557 {
1558 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1559 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1560 }
1561 ga_clear(&ga);
1562 }
1563 else
1564 vim_free(p);
1565 }
1566 }
1567
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001568 term->tl_dirty_snapshot = FALSE;
1569#ifdef FEAT_TIMERS
1570 term->tl_timer_set = FALSE;
1571#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001572}
1573
1574/*
1575 * If needed, add the current lines of the terminal to scrollback and to the
1576 * buffer. Called after the job has ended and when switching to
1577 * Terminal-Normal mode.
1578 * When "redraw" is TRUE redraw the windows that show the terminal.
1579 */
1580 static void
1581may_move_terminal_to_buffer(term_T *term, int redraw)
1582{
1583 win_T *wp;
1584
1585 if (term->tl_vterm == NULL)
1586 return;
1587
1588 /* Update the snapshot only if something changes or the buffer does not
1589 * have all the lines. */
1590 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1591 <= term->tl_scrollback_scrolled)
1592 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001593
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001594 /* Obtain the current background color. */
1595 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1596 &term->tl_default_color.fg, &term->tl_default_color.bg);
1597
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001598 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001599 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001600 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001601 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001602 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001603 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1604 wp->w_cursor.col = 0;
1605 wp->w_valid = 0;
1606 if (wp->w_cursor.lnum >= wp->w_height)
1607 {
1608 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001609
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001610 if (wp->w_topline < min_topline)
1611 wp->w_topline = min_topline;
1612 }
1613 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001614 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001616}
1617
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001618#if defined(FEAT_TIMERS) || defined(PROTO)
1619/*
1620 * Check if any terminal timer expired. If so, copy text from the terminal to
1621 * the buffer.
1622 * Return the time until the next timer will expire.
1623 */
1624 int
1625term_check_timers(int next_due_arg, proftime_T *now)
1626{
1627 term_T *term;
1628 int next_due = next_due_arg;
1629
1630 for (term = first_term; term != NULL; term = term->tl_next)
1631 {
1632 if (term->tl_timer_set && !term->tl_normal_mode)
1633 {
1634 long this_due = proftime_time_left(&term->tl_timer_due, now);
1635
1636 if (this_due <= 1)
1637 {
1638 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001639 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001640 }
1641 else if (next_due == -1 || next_due > this_due)
1642 next_due = this_due;
1643 }
1644 }
1645
1646 return next_due;
1647}
1648#endif
1649
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 static void
1651set_terminal_mode(term_T *term, int normal_mode)
1652{
1653 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001654 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001655 if (term->tl_buffer == curbuf)
1656 maketitle();
1657}
1658
1659/*
1660 * Called after the job if finished and Terminal mode is not active:
1661 * Move the vterm contents into the scrollback buffer and free the vterm.
1662 */
1663 static void
1664cleanup_vterm(term_T *term)
1665{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001666 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001667 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001668 term_free_vterm(term);
1669 set_terminal_mode(term, FALSE);
1670}
1671
1672/*
1673 * Switch from Terminal-Job mode to Terminal-Normal mode.
1674 * Suspends updating the terminal window.
1675 */
1676 static void
1677term_enter_normal_mode(void)
1678{
1679 term_T *term = curbuf->b_term;
1680
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001681 set_terminal_mode(term, TRUE);
1682
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001683 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001684 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001685
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001686 /* Move the window cursor to the position of the cursor in the
1687 * terminal. */
1688 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1689 + term->tl_cursor_pos.row + 1;
1690 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001691 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1692 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693
1694 /* Display the same lines as in the terminal. */
1695 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1696}
1697
1698/*
1699 * Returns TRUE if the current window contains a terminal and we are in
1700 * Terminal-Normal mode.
1701 */
1702 int
1703term_in_normal_mode(void)
1704{
1705 term_T *term = curbuf->b_term;
1706
1707 return term != NULL && term->tl_normal_mode;
1708}
1709
1710/*
1711 * Switch from Terminal-Normal mode to Terminal-Job mode.
1712 * Restores updating the terminal window.
1713 */
1714 void
1715term_enter_job_mode()
1716{
1717 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001718
1719 set_terminal_mode(term, FALSE);
1720
1721 if (term->tl_channel_closed)
1722 cleanup_vterm(term);
1723 redraw_buf_and_status_later(curbuf, NOT_VALID);
1724}
1725
1726/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001727 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001728 * Note: while waiting a terminal may be closed and freed if the channel is
1729 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 */
1731 static int
1732term_vgetc()
1733{
1734 int c;
1735 int save_State = State;
1736
1737 State = TERMINAL;
1738 got_int = FALSE;
1739#ifdef WIN3264
1740 ctrl_break_was_pressed = FALSE;
1741#endif
1742 c = vgetc();
1743 got_int = FALSE;
1744 State = save_State;
1745 return c;
1746}
1747
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001748static int mouse_was_outside = FALSE;
1749
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751 * Send keys to terminal.
1752 * Return FAIL when the key needs to be handled in Normal mode.
1753 * Return OK when the key was dropped or sent to the terminal.
1754 */
1755 int
1756send_keys_to_term(term_T *term, int c, int typed)
1757{
1758 char msg[KEY_BUF_LEN];
1759 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001760 int dragging_outside = FALSE;
1761
1762 /* Catch keys that need to be handled as in Normal mode. */
1763 switch (c)
1764 {
1765 case NUL:
1766 case K_ZERO:
1767 if (typed)
1768 stuffcharReadbuff(c);
1769 return FAIL;
1770
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001771 case K_TABLINE:
1772 stuffcharReadbuff(c);
1773 return FAIL;
1774
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001775 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001776 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001777 return FAIL;
1778
1779 case K_LEFTDRAG:
1780 case K_MIDDLEDRAG:
1781 case K_RIGHTDRAG:
1782 case K_X1DRAG:
1783 case K_X2DRAG:
1784 dragging_outside = mouse_was_outside;
1785 /* FALLTHROUGH */
1786 case K_LEFTMOUSE:
1787 case K_LEFTMOUSE_NM:
1788 case K_LEFTRELEASE:
1789 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001790 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001791 case K_MIDDLEMOUSE:
1792 case K_MIDDLERELEASE:
1793 case K_RIGHTMOUSE:
1794 case K_RIGHTRELEASE:
1795 case K_X1MOUSE:
1796 case K_X1RELEASE:
1797 case K_X2MOUSE:
1798 case K_X2RELEASE:
1799
1800 case K_MOUSEUP:
1801 case K_MOUSEDOWN:
1802 case K_MOUSELEFT:
1803 case K_MOUSERIGHT:
1804 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001805 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001806 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001807 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001808 || dragging_outside)
1809 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001810 /* click or scroll outside the current window or on status line
1811 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 if (typed)
1813 {
1814 stuffcharReadbuff(c);
1815 mouse_was_outside = TRUE;
1816 }
1817 return FAIL;
1818 }
1819 }
1820 if (typed)
1821 mouse_was_outside = FALSE;
1822
1823 /* Convert the typed key to a sequence of bytes for the job. */
1824 len = term_convert_key(term, c, msg);
1825 if (len > 0)
1826 /* TODO: if FAIL is returned, stop? */
1827 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1828 (char_u *)msg, (int)len, NULL);
1829
1830 return OK;
1831}
1832
1833 static void
1834position_cursor(win_T *wp, VTermPos *pos)
1835{
1836 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1837 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1838 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1839}
1840
1841/*
1842 * Handle CTRL-W "": send register contents to the job.
1843 */
1844 static void
1845term_paste_register(int prev_c UNUSED)
1846{
1847 int c;
1848 list_T *l;
1849 listitem_T *item;
1850 long reglen = 0;
1851 int type;
1852
1853#ifdef FEAT_CMDL_INFO
1854 if (add_to_showcmd(prev_c))
1855 if (add_to_showcmd('"'))
1856 out_flush();
1857#endif
1858 c = term_vgetc();
1859#ifdef FEAT_CMDL_INFO
1860 clear_showcmd();
1861#endif
1862 if (!term_use_loop())
1863 /* job finished while waiting for a character */
1864 return;
1865
1866 /* CTRL-W "= prompt for expression to evaluate. */
1867 if (c == '=' && get_expr_register() != '=')
1868 return;
1869 if (!term_use_loop())
1870 /* job finished while waiting for a character */
1871 return;
1872
1873 l = (list_T *)get_reg_contents(c, GREG_LIST);
1874 if (l != NULL)
1875 {
1876 type = get_reg_type(c, &reglen);
1877 for (item = l->lv_first; item != NULL; item = item->li_next)
1878 {
1879 char_u *s = get_tv_string(&item->li_tv);
1880#ifdef WIN3264
1881 char_u *tmp = s;
1882
1883 if (!enc_utf8 && enc_codepage > 0)
1884 {
1885 WCHAR *ret = NULL;
1886 int length = 0;
1887
1888 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1889 (int)STRLEN(s), &ret, &length);
1890 if (ret != NULL)
1891 {
1892 WideCharToMultiByte_alloc(CP_UTF8, 0,
1893 ret, length, (char **)&s, &length, 0, 0);
1894 vim_free(ret);
1895 }
1896 }
1897#endif
1898 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1899 s, (int)STRLEN(s), NULL);
1900#ifdef WIN3264
1901 if (tmp != s)
1902 vim_free(s);
1903#endif
1904
1905 if (item->li_next != NULL || type == MLINE)
1906 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1907 (char_u *)"\r", 1, NULL);
1908 }
1909 list_free(l);
1910 }
1911}
1912
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001914 * Return TRUE when waiting for a character in the terminal, the cursor of the
1915 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001916 */
1917 int
1918terminal_is_active()
1919{
1920 return in_terminal_loop != NULL;
1921}
1922
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001923#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001924 cursorentry_T *
1925term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1926{
1927 term_T *term = in_terminal_loop;
1928 static cursorentry_T entry;
1929
1930 vim_memset(&entry, 0, sizeof(entry));
1931 entry.shape = entry.mshape =
1932 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1933 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1934 SHAPE_BLOCK;
1935 entry.percentage = 20;
1936 if (term->tl_cursor_blink)
1937 {
1938 entry.blinkwait = 700;
1939 entry.blinkon = 400;
1940 entry.blinkoff = 250;
1941 }
1942 *fg = gui.back_pixel;
1943 if (term->tl_cursor_color == NULL)
1944 *bg = gui.norm_pixel;
1945 else
1946 *bg = color_name2handle(term->tl_cursor_color);
1947 entry.name = "n";
1948 entry.used_for = SHAPE_CURSOR;
1949
1950 return &entry;
1951}
1952#endif
1953
Bram Moolenaard317b382018-02-08 22:33:31 +01001954 static void
1955may_output_cursor_props(void)
1956{
1957 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1958 || last_set_cursor_shape != desired_cursor_shape
1959 || last_set_cursor_blink != desired_cursor_blink)
1960 {
1961 last_set_cursor_color = desired_cursor_color;
1962 last_set_cursor_shape = desired_cursor_shape;
1963 last_set_cursor_blink = desired_cursor_blink;
1964 term_cursor_color(desired_cursor_color);
1965 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1966 /* this will restore the initial cursor style, if possible */
1967 ui_cursor_shape_forced(TRUE);
1968 else
1969 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1970 }
1971}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001972
Bram Moolenaard317b382018-02-08 22:33:31 +01001973/*
1974 * Set the cursor color and shape, if not last set to these.
1975 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001976 static void
1977may_set_cursor_props(term_T *term)
1978{
1979#ifdef FEAT_GUI
1980 /* For the GUI the cursor properties are obtained with
1981 * term_get_cursor_shape(). */
1982 if (gui.in_use)
1983 return;
1984#endif
1985 if (in_terminal_loop == term)
1986 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001987 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001988 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001990 desired_cursor_color = (char_u *)"";
1991 desired_cursor_shape = term->tl_cursor_shape;
1992 desired_cursor_blink = term->tl_cursor_blink;
1993 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 }
1995}
1996
Bram Moolenaard317b382018-02-08 22:33:31 +01001997/*
1998 * Reset the desired cursor properties and restore them when needed.
1999 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002001prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002{
2003#ifdef FEAT_GUI
2004 if (gui.in_use)
2005 return;
2006#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002007 desired_cursor_color = (char_u *)"";
2008 desired_cursor_shape = -1;
2009 desired_cursor_blink = -1;
2010 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011}
2012
2013/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002014 * Returns TRUE if the current window contains a terminal and we are sending
2015 * keys to the job.
2016 * If "check_job_status" is TRUE update the job status.
2017 */
2018 static int
2019term_use_loop_check(int check_job_status)
2020{
2021 term_T *term = curbuf->b_term;
2022
2023 return term != NULL
2024 && !term->tl_normal_mode
2025 && term->tl_vterm != NULL
2026 && term_job_running_check(term, check_job_status);
2027}
2028
2029/*
2030 * Returns TRUE if the current window contains a terminal and we are sending
2031 * keys to the job.
2032 */
2033 int
2034term_use_loop(void)
2035{
2036 return term_use_loop_check(FALSE);
2037}
2038
2039/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002040 * Called when entering a window with the mouse. If this is a terminal window
2041 * we may want to change state.
2042 */
2043 void
2044term_win_entered()
2045{
2046 term_T *term = curbuf->b_term;
2047
2048 if (term != NULL)
2049 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002050 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002051 {
2052 reset_VIsual_and_resel();
2053 if (State & INSERT)
2054 stop_insert_mode = TRUE;
2055 }
2056 mouse_was_outside = FALSE;
2057 enter_mouse_col = mouse_col;
2058 enter_mouse_row = mouse_row;
2059 }
2060}
2061
2062/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 * Wait for input and send it to the job.
2064 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2065 * when there is no more typahead.
2066 * Return when the start of a CTRL-W command is typed or anything else that
2067 * should be handled as a Normal mode command.
2068 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2069 * the terminal was closed.
2070 */
2071 int
2072terminal_loop(int blocking)
2073{
2074 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002075 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002076 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002077#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002078 int tty_fd = curbuf->b_term->tl_job->jv_channel
2079 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002080#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002081 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002082
2083 /* Remember the terminal we are sending keys to. However, the terminal
2084 * might be closed while waiting for a character, e.g. typing "exit" in a
2085 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2086 * stored reference. */
2087 in_terminal_loop = curbuf->b_term;
2088
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002089 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002090 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002091 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2092 may_set_cursor_props(curbuf->b_term);
2093
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002094 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002095 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002096#ifdef FEAT_GUI
2097 if (!curbuf->b_term->tl_system)
2098#endif
2099 /* TODO: skip screen update when handling a sequence of keys. */
2100 /* Repeat redrawing in case a message is received while redrawing.
2101 */
2102 while (must_redraw != 0)
2103 if (update_screen(0) == FAIL)
2104 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002105 if (!term_use_loop_check(TRUE))
2106 /* job finished while redrawing */
2107 break;
2108
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002109 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002110 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002111
2112 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002113 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002114 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002115 /* Job finished while waiting for a character. Push back the
2116 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002117 if (c != K_IGNORE)
2118 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002119 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002120 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 if (c == K_IGNORE)
2122 continue;
2123
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002124#ifdef UNIX
2125 /*
2126 * The shell or another program may change the tty settings. Getting
2127 * them for every typed character is a bit of overhead, but it's needed
2128 * for the first character typed, e.g. when Vim starts in a shell.
2129 */
2130 if (isatty(tty_fd))
2131 {
2132 ttyinfo_T info;
2133
2134 /* Get the current backspace character of the pty. */
2135 if (get_tty_info(tty_fd, &info) == OK)
2136 term_backspace_char = info.backspace;
2137 }
2138#endif
2139
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140#ifdef WIN3264
2141 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2142 * Use CTRL-BREAK to kill the job. */
2143 if (ctrl_break_was_pressed)
2144 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2145#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002146 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002147 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002148 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002149#ifdef FEAT_GUI
2150 && !curbuf->b_term->tl_system
2151#endif
2152 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002153 {
2154 int prev_c = c;
2155
2156#ifdef FEAT_CMDL_INFO
2157 if (add_to_showcmd(c))
2158 out_flush();
2159#endif
2160 c = term_vgetc();
2161#ifdef FEAT_CMDL_INFO
2162 clear_showcmd();
2163#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002164 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002165 /* job finished while waiting for a character */
2166 break;
2167
2168 if (prev_c == Ctrl_BSL)
2169 {
2170 if (c == Ctrl_N)
2171 {
2172 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2173 term_enter_normal_mode();
2174 ret = FAIL;
2175 goto theend;
2176 }
2177 /* Send both keys to the terminal. */
2178 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2179 }
2180 else if (c == Ctrl_C)
2181 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002182 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2184 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002185 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 {
2187 /* "CTRL-W .": send CTRL-W to the job */
2188 c = Ctrl_W;
2189 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002190 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002191 {
2192 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2193 c = Ctrl_BSL;
2194 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002195 else if (c == 'N')
2196 {
2197 /* CTRL-W N : go to Terminal-Normal mode. */
2198 term_enter_normal_mode();
2199 ret = FAIL;
2200 goto theend;
2201 }
2202 else if (c == '"')
2203 {
2204 term_paste_register(prev_c);
2205 continue;
2206 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002207 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 {
2209 stuffcharReadbuff(Ctrl_W);
2210 stuffcharReadbuff(c);
2211 ret = OK;
2212 goto theend;
2213 }
2214 }
2215# ifdef WIN3264
2216 if (!enc_utf8 && has_mbyte && c >= 0x80)
2217 {
2218 WCHAR wc;
2219 char_u mb[3];
2220
2221 mb[0] = (unsigned)c >> 8;
2222 mb[1] = c;
2223 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2224 c = wc;
2225 }
2226# endif
2227 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2228 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002229 if (c == K_MOUSEMOVE)
2230 /* We are sure to come back here, don't reset the cursor color
2231 * and shape to avoid flickering. */
2232 restore_cursor = FALSE;
2233
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234 ret = OK;
2235 goto theend;
2236 }
2237 }
2238 ret = FAIL;
2239
2240theend:
2241 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002242 if (restore_cursor)
2243 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002244
2245 /* Move a snapshot of the screen contents to the buffer, so that completion
2246 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002247 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2248 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002249
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002250 return ret;
2251}
2252
2253/*
2254 * Called when a job has finished.
2255 * This updates the title and status, but does not close the vterm, because
2256 * there might still be pending output in the channel.
2257 */
2258 void
2259term_job_ended(job_T *job)
2260{
2261 term_T *term;
2262 int did_one = FALSE;
2263
2264 for (term = first_term; term != NULL; term = term->tl_next)
2265 if (term->tl_job == job)
2266 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002267 VIM_CLEAR(term->tl_title);
2268 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 redraw_buf_and_status_later(term->tl_buffer, VALID);
2270 did_one = TRUE;
2271 }
2272 if (did_one)
2273 redraw_statuslines();
2274 if (curbuf->b_term != NULL)
2275 {
2276 if (curbuf->b_term->tl_job == job)
2277 maketitle();
2278 update_cursor(curbuf->b_term, TRUE);
2279 }
2280}
2281
2282 static void
2283may_toggle_cursor(term_T *term)
2284{
2285 if (in_terminal_loop == term)
2286 {
2287 if (term->tl_cursor_visible)
2288 cursor_on();
2289 else
2290 cursor_off();
2291 }
2292}
2293
2294/*
2295 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002296 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 */
2298 static int
2299color2index(VTermColor *color, int fg, int *boldp)
2300{
2301 int red = color->red;
2302 int blue = color->blue;
2303 int green = color->green;
2304
Bram Moolenaar46359e12017-11-29 22:33:38 +01002305 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002306 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002307 /* First 16 colors and default: use the ANSI index, because these
2308 * colors can be redefined. */
2309 if (t_colors >= 16)
2310 return color->ansi_index;
2311 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002312 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002313 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002314 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002315 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2316 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2317 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002318 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002319 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2320 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2321 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2322 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2323 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2324 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2325 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2326 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2327 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2328 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2329 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002330 }
2331 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002332
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002333 if (t_colors >= 256)
2334 {
2335 if (red == blue && red == green)
2336 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002337 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002338 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002339 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2340 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2341 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002342 int i;
2343
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002344 if (red < 5)
2345 return 17; /* 00/00/00 */
2346 if (red > 245) /* ff/ff/ff */
2347 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002348 for (i = 0; i < 23; ++i)
2349 if (red < cutoff[i])
2350 return i + 233;
2351 return 256;
2352 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002353 {
2354 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2355 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002356
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002357 /* 216-color cube */
2358 for (ri = 0; ri < 5; ++ri)
2359 if (red < cutoff[ri])
2360 break;
2361 for (gi = 0; gi < 5; ++gi)
2362 if (green < cutoff[gi])
2363 break;
2364 for (bi = 0; bi < 5; ++bi)
2365 if (blue < cutoff[bi])
2366 break;
2367 return 17 + ri * 36 + gi * 6 + bi;
2368 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 }
2370 return 0;
2371}
2372
2373/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002374 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002375 */
2376 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002377vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002378{
2379 int attr = 0;
2380
2381 if (cellattrs.bold)
2382 attr |= HL_BOLD;
2383 if (cellattrs.underline)
2384 attr |= HL_UNDERLINE;
2385 if (cellattrs.italic)
2386 attr |= HL_ITALIC;
2387 if (cellattrs.strike)
2388 attr |= HL_STRIKETHROUGH;
2389 if (cellattrs.reverse)
2390 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002391 return attr;
2392}
2393
2394/*
2395 * Store Vterm attributes in "cell" from highlight flags.
2396 */
2397 static void
2398hl2vtermAttr(int attr, cellattr_T *cell)
2399{
2400 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2401 if (attr & HL_BOLD)
2402 cell->attrs.bold = 1;
2403 if (attr & HL_UNDERLINE)
2404 cell->attrs.underline = 1;
2405 if (attr & HL_ITALIC)
2406 cell->attrs.italic = 1;
2407 if (attr & HL_STRIKETHROUGH)
2408 cell->attrs.strike = 1;
2409 if (attr & HL_INVERSE)
2410 cell->attrs.reverse = 1;
2411}
2412
2413/*
2414 * Convert the attributes of a vterm cell into an attribute index.
2415 */
2416 static int
2417cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2418{
2419 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002420
2421#ifdef FEAT_GUI
2422 if (gui.in_use)
2423 {
2424 guicolor_T fg, bg;
2425
2426 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2427 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2428 return get_gui_attr_idx(attr, fg, bg);
2429 }
2430 else
2431#endif
2432#ifdef FEAT_TERMGUICOLORS
2433 if (p_tgc)
2434 {
2435 guicolor_T fg, bg;
2436
2437 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2438 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2439
2440 return get_tgc_attr_idx(attr, fg, bg);
2441 }
2442 else
2443#endif
2444 {
2445 int bold = MAYBE;
2446 int fg = color2index(&cellfg, TRUE, &bold);
2447 int bg = color2index(&cellbg, FALSE, &bold);
2448
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002449 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002450 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002451 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002452 if (fg == 0 && term_default_cterm_fg >= 0)
2453 fg = term_default_cterm_fg + 1;
2454 if (bg == 0 && term_default_cterm_bg >= 0)
2455 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002456 }
2457
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002458 /* with 8 colors set the bold attribute to get a bright foreground */
2459 if (bold == TRUE)
2460 attr |= HL_BOLD;
2461 return get_cterm_attr_idx(attr, fg, bg);
2462 }
2463 return 0;
2464}
2465
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002466 static void
2467set_dirty_snapshot(term_T *term)
2468{
2469 term->tl_dirty_snapshot = TRUE;
2470#ifdef FEAT_TIMERS
2471 if (!term->tl_normal_mode)
2472 {
2473 /* Update the snapshot after 100 msec of not getting updates. */
2474 profile_setlimit(100L, &term->tl_timer_due);
2475 term->tl_timer_set = TRUE;
2476 }
2477#endif
2478}
2479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 static int
2481handle_damage(VTermRect rect, void *user)
2482{
2483 term_T *term = (term_T *)user;
2484
2485 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2486 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002487 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002488 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002489 return 1;
2490}
2491
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002492 static void
2493term_scroll_up(term_T *term, int start_row, int count)
2494{
2495 win_T *wp;
2496 VTermColor fg, bg;
2497 VTermScreenCellAttrs attr;
2498 int clear_attr;
2499
2500 /* Set the color to clear lines with. */
2501 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2502 &fg, &bg);
2503 vim_memset(&attr, 0, sizeof(attr));
2504 clear_attr = cell2attr(attr, fg, bg);
2505
2506 FOR_ALL_WINDOWS(wp)
2507 {
2508 if (wp->w_buffer == term->tl_buffer)
2509 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2510 }
2511}
2512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002513 static int
2514handle_moverect(VTermRect dest, VTermRect src, void *user)
2515{
2516 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002517 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518
2519 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002520 * redrawing the text. But avoid doing this multiple times, postpone until
2521 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 if (dest.start_col == src.start_col
2523 && dest.end_col == src.end_col
2524 && dest.start_row < src.start_row)
2525 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002526 if (dest.start_row == 0)
2527 term->tl_postponed_scroll += count;
2528 else
2529 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002531
2532 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2533 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002534 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002535
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002536 /* Note sure if the scrolling will work correctly, let's do a complete
2537 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002538 redraw_buf_later(term->tl_buffer, NOT_VALID);
2539 return 1;
2540}
2541
2542 static int
2543handle_movecursor(
2544 VTermPos pos,
2545 VTermPos oldpos UNUSED,
2546 int visible,
2547 void *user)
2548{
2549 term_T *term = (term_T *)user;
2550 win_T *wp;
2551
2552 term->tl_cursor_pos = pos;
2553 term->tl_cursor_visible = visible;
2554
2555 FOR_ALL_WINDOWS(wp)
2556 {
2557 if (wp->w_buffer == term->tl_buffer)
2558 position_cursor(wp, &pos);
2559 }
2560 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2561 {
2562 may_toggle_cursor(term);
2563 update_cursor(term, term->tl_cursor_visible);
2564 }
2565
2566 return 1;
2567}
2568
2569 static int
2570handle_settermprop(
2571 VTermProp prop,
2572 VTermValue *value,
2573 void *user)
2574{
2575 term_T *term = (term_T *)user;
2576
2577 switch (prop)
2578 {
2579 case VTERM_PROP_TITLE:
2580 vim_free(term->tl_title);
2581 /* a blank title isn't useful, make it empty, so that "running" is
2582 * displayed */
2583 if (*skipwhite((char_u *)value->string) == NUL)
2584 term->tl_title = NULL;
2585#ifdef WIN3264
2586 else if (!enc_utf8 && enc_codepage > 0)
2587 {
2588 WCHAR *ret = NULL;
2589 int length = 0;
2590
2591 MultiByteToWideChar_alloc(CP_UTF8, 0,
2592 (char*)value->string, (int)STRLEN(value->string),
2593 &ret, &length);
2594 if (ret != NULL)
2595 {
2596 WideCharToMultiByte_alloc(enc_codepage, 0,
2597 ret, length, (char**)&term->tl_title,
2598 &length, 0, 0);
2599 vim_free(ret);
2600 }
2601 }
2602#endif
2603 else
2604 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002605 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002606 if (term == curbuf->b_term)
2607 maketitle();
2608 break;
2609
2610 case VTERM_PROP_CURSORVISIBLE:
2611 term->tl_cursor_visible = value->boolean;
2612 may_toggle_cursor(term);
2613 out_flush();
2614 break;
2615
2616 case VTERM_PROP_CURSORBLINK:
2617 term->tl_cursor_blink = value->boolean;
2618 may_set_cursor_props(term);
2619 break;
2620
2621 case VTERM_PROP_CURSORSHAPE:
2622 term->tl_cursor_shape = value->number;
2623 may_set_cursor_props(term);
2624 break;
2625
2626 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002627 if (desired_cursor_color == term->tl_cursor_color)
2628 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002629 vim_free(term->tl_cursor_color);
2630 if (*value->string == NUL)
2631 term->tl_cursor_color = NULL;
2632 else
2633 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2634 may_set_cursor_props(term);
2635 break;
2636
2637 case VTERM_PROP_ALTSCREEN:
2638 /* TODO: do anything else? */
2639 term->tl_using_altscreen = value->boolean;
2640 break;
2641
2642 default:
2643 break;
2644 }
2645 /* Always return 1, otherwise vterm doesn't store the value internally. */
2646 return 1;
2647}
2648
2649/*
2650 * The job running in the terminal resized the terminal.
2651 */
2652 static int
2653handle_resize(int rows, int cols, void *user)
2654{
2655 term_T *term = (term_T *)user;
2656 win_T *wp;
2657
2658 term->tl_rows = rows;
2659 term->tl_cols = cols;
2660 if (term->tl_vterm_size_changed)
2661 /* Size was set by vterm_set_size(), don't set the window size. */
2662 term->tl_vterm_size_changed = FALSE;
2663 else
2664 {
2665 FOR_ALL_WINDOWS(wp)
2666 {
2667 if (wp->w_buffer == term->tl_buffer)
2668 {
2669 win_setheight_win(rows, wp);
2670 win_setwidth_win(cols, wp);
2671 }
2672 }
2673 redraw_buf_later(term->tl_buffer, NOT_VALID);
2674 }
2675 return 1;
2676}
2677
2678/*
2679 * Handle a line that is pushed off the top of the screen.
2680 */
2681 static int
2682handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2683{
2684 term_T *term = (term_T *)user;
2685
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002686 /* First remove the lines that were appended before, the pushed line goes
2687 * above it. */
2688 cleanup_scrollback(term);
2689
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002690 /* If the number of lines that are stored goes over 'termscrollback' then
2691 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002692 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002693 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002694 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002695 int i;
2696
2697 curbuf = term->tl_buffer;
2698 for (i = 0; i < todo; ++i)
2699 {
2700 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2701 ml_delete(1, FALSE);
2702 }
2703 curbuf = curwin->w_buffer;
2704
2705 term->tl_scrollback.ga_len -= todo;
2706 mch_memmove(term->tl_scrollback.ga_data,
2707 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2708 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
Bram Moolenaar4d6cd292018-05-15 23:53:26 +02002709 term->tl_scrollback_scrolled -= todo;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002710 }
2711
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 if (ga_grow(&term->tl_scrollback, 1) == OK)
2713 {
2714 cellattr_T *p = NULL;
2715 int len = 0;
2716 int i;
2717 int c;
2718 int col;
2719 sb_line_T *line;
2720 garray_T ga;
2721 cellattr_T fill_attr = term->tl_default_color;
2722
2723 /* do not store empty cells at the end */
2724 for (i = 0; i < cols; ++i)
2725 if (cells[i].chars[0] != 0)
2726 len = i + 1;
2727 else
2728 cell2cellattr(&cells[i], &fill_attr);
2729
2730 ga_init2(&ga, 1, 100);
2731 if (len > 0)
2732 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2733 if (p != NULL)
2734 {
2735 for (col = 0; col < len; col += cells[col].width)
2736 {
2737 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2738 {
2739 ga.ga_len = 0;
2740 break;
2741 }
2742 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2743 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2744 (char_u *)ga.ga_data + ga.ga_len);
2745 cell2cellattr(&cells[col], &p[col]);
2746 }
2747 }
2748 if (ga_grow(&ga, 1) == FAIL)
2749 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2750 else
2751 {
2752 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2753 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2754 }
2755 ga_clear(&ga);
2756
2757 line = (sb_line_T *)term->tl_scrollback.ga_data
2758 + term->tl_scrollback.ga_len;
2759 line->sb_cols = len;
2760 line->sb_cells = p;
2761 line->sb_fill_attr = fill_attr;
2762 ++term->tl_scrollback.ga_len;
2763 ++term->tl_scrollback_scrolled;
2764 }
2765 return 0; /* ignored */
2766}
2767
2768static VTermScreenCallbacks screen_callbacks = {
2769 handle_damage, /* damage */
2770 handle_moverect, /* moverect */
2771 handle_movecursor, /* movecursor */
2772 handle_settermprop, /* settermprop */
2773 NULL, /* bell */
2774 handle_resize, /* resize */
2775 handle_pushline, /* sb_pushline */
2776 NULL /* sb_popline */
2777};
2778
2779/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002780 * Do the work after the channel of a terminal was closed.
2781 * Must be called only when updating_screen is FALSE.
2782 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2783 */
2784 static int
2785term_after_channel_closed(term_T *term)
2786{
2787 /* Unless in Terminal-Normal mode: clear the vterm. */
2788 if (!term->tl_normal_mode)
2789 {
2790 int fnum = term->tl_buffer->b_fnum;
2791
2792 cleanup_vterm(term);
2793
2794 if (term->tl_finish == TL_FINISH_CLOSE)
2795 {
2796 aco_save_T aco;
2797
2798 /* ++close or term_finish == "close" */
2799 ch_log(NULL, "terminal job finished, closing window");
2800 aucmd_prepbuf(&aco, term->tl_buffer);
2801 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2802 aucmd_restbuf(&aco);
2803 return TRUE;
2804 }
2805 if (term->tl_finish == TL_FINISH_OPEN
2806 && term->tl_buffer->b_nwindows == 0)
2807 {
2808 char buf[50];
2809
2810 /* TODO: use term_opencmd */
2811 ch_log(NULL, "terminal job finished, opening window");
2812 vim_snprintf(buf, sizeof(buf),
2813 term->tl_opencmd == NULL
2814 ? "botright sbuf %d"
2815 : (char *)term->tl_opencmd, fnum);
2816 do_cmdline_cmd((char_u *)buf);
2817 }
2818 else
2819 ch_log(NULL, "terminal job finished");
2820 }
2821
2822 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2823 return FALSE;
2824}
2825
2826/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002827 * Called when a channel has been closed.
2828 * If this was a channel for a terminal window then finish it up.
2829 */
2830 void
2831term_channel_closed(channel_T *ch)
2832{
2833 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002834 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002835 int did_one = FALSE;
2836
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002837 for (term = first_term; term != NULL; term = next_term)
2838 {
2839 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840 if (term->tl_job == ch->ch_job)
2841 {
2842 term->tl_channel_closed = TRUE;
2843 did_one = TRUE;
2844
Bram Moolenaard23a8232018-02-10 18:45:26 +01002845 VIM_CLEAR(term->tl_title);
2846 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002847#ifdef WIN3264
2848 if (term->tl_out_fd != NULL)
2849 {
2850 fclose(term->tl_out_fd);
2851 term->tl_out_fd = NULL;
2852 }
2853#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002854
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002855 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002856 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002857 /* Cannot open or close windows now. Can happen when
2858 * 'lazyredraw' is set. */
2859 term->tl_channel_recently_closed = TRUE;
2860 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002861 }
2862
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002863 if (term_after_channel_closed(term))
2864 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002865 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002866 }
2867
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 if (did_one)
2869 {
2870 redraw_statuslines();
2871
2872 /* Need to break out of vgetc(). */
2873 ins_char_typebuf(K_IGNORE);
2874 typebuf_was_filled = TRUE;
2875
2876 term = curbuf->b_term;
2877 if (term != NULL)
2878 {
2879 if (term->tl_job == ch->ch_job)
2880 maketitle();
2881 update_cursor(term, term->tl_cursor_visible);
2882 }
2883 }
2884}
2885
2886/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002887 * To be called after resetting updating_screen: handle any terminal where the
2888 * channel was closed.
2889 */
2890 void
2891term_check_channel_closed_recently()
2892{
2893 term_T *term;
2894 term_T *next_term;
2895
2896 for (term = first_term; term != NULL; term = next_term)
2897 {
2898 next_term = term->tl_next;
2899 if (term->tl_channel_recently_closed)
2900 {
2901 term->tl_channel_recently_closed = FALSE;
2902 if (term_after_channel_closed(term))
2903 // start over, the list may have changed
2904 next_term = first_term;
2905 }
2906 }
2907}
2908
2909/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002910 * Fill one screen line from a line of the terminal.
2911 * Advances "pos" to past the last column.
2912 */
2913 static void
2914term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2915{
2916 int off = screen_get_current_line_off();
2917
2918 for (pos->col = 0; pos->col < max_col; )
2919 {
2920 VTermScreenCell cell;
2921 int c;
2922
2923 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2924 vim_memset(&cell, 0, sizeof(cell));
2925
2926 c = cell.chars[0];
2927 if (c == NUL)
2928 {
2929 ScreenLines[off] = ' ';
2930 if (enc_utf8)
2931 ScreenLinesUC[off] = NUL;
2932 }
2933 else
2934 {
2935 if (enc_utf8)
2936 {
2937 int i;
2938
2939 /* composing chars */
2940 for (i = 0; i < Screen_mco
2941 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2942 {
2943 ScreenLinesC[i][off] = cell.chars[i + 1];
2944 if (cell.chars[i + 1] == 0)
2945 break;
2946 }
2947 if (c >= 0x80 || (Screen_mco > 0
2948 && ScreenLinesC[0][off] != 0))
2949 {
2950 ScreenLines[off] = ' ';
2951 ScreenLinesUC[off] = c;
2952 }
2953 else
2954 {
2955 ScreenLines[off] = c;
2956 ScreenLinesUC[off] = NUL;
2957 }
2958 }
2959#ifdef WIN3264
2960 else if (has_mbyte && c >= 0x80)
2961 {
2962 char_u mb[MB_MAXBYTES+1];
2963 WCHAR wc = c;
2964
2965 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2966 (char*)mb, 2, 0, 0) > 1)
2967 {
2968 ScreenLines[off] = mb[0];
2969 ScreenLines[off + 1] = mb[1];
2970 cell.width = mb_ptr2cells(mb);
2971 }
2972 else
2973 ScreenLines[off] = c;
2974 }
2975#endif
2976 else
2977 ScreenLines[off] = c;
2978 }
2979 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2980
2981 ++pos->col;
2982 ++off;
2983 if (cell.width == 2)
2984 {
2985 if (enc_utf8)
2986 ScreenLinesUC[off] = NUL;
2987
2988 /* don't set the second byte to NUL for a DBCS encoding, it
2989 * has been set above */
2990 if (enc_utf8 || !has_mbyte)
2991 ScreenLines[off] = NUL;
2992
2993 ++pos->col;
2994 ++off;
2995 }
2996 }
2997}
2998
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002999#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003000 static void
3001update_system_term(term_T *term)
3002{
3003 VTermPos pos;
3004 VTermScreen *screen;
3005
3006 if (term->tl_vterm == NULL)
3007 return;
3008 screen = vterm_obtain_screen(term->tl_vterm);
3009
3010 /* Scroll up to make more room for terminal lines if needed. */
3011 while (term->tl_toprow > 0
3012 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3013 {
3014 int save_p_more = p_more;
3015
3016 p_more = FALSE;
3017 msg_row = Rows - 1;
3018 msg_puts((char_u *)"\n");
3019 p_more = save_p_more;
3020 --term->tl_toprow;
3021 }
3022
3023 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3024 && pos.row < Rows; ++pos.row)
3025 {
3026 if (pos.row < term->tl_rows)
3027 {
3028 int max_col = MIN(Columns, term->tl_cols);
3029
3030 term_line2screenline(screen, &pos, max_col);
3031 }
3032 else
3033 pos.col = 0;
3034
3035 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3036 }
3037
3038 term->tl_dirty_row_start = MAX_ROW;
3039 term->tl_dirty_row_end = 0;
3040 update_cursor(term, TRUE);
3041}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003042#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003043
3044/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003045 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3046 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047 * Terminal-Normal mode.
3048 */
3049 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003050term_do_update_window(win_T *wp)
3051{
3052 term_T *term = wp->w_buffer->b_term;
3053
3054 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3055}
3056
3057/*
3058 * Called to update a window that contains an active terminal.
3059 */
3060 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061term_update_window(win_T *wp)
3062{
3063 term_T *term = wp->w_buffer->b_term;
3064 VTerm *vterm;
3065 VTermScreen *screen;
3066 VTermState *state;
3067 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003068 int rows, cols;
3069 int newrows, newcols;
3070 int minsize;
3071 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 vterm = term->tl_vterm;
3074 screen = vterm_obtain_screen(vterm);
3075 state = vterm_obtain_state(vterm);
3076
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003077 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3078 * SOME_VALID only redraw what was marked dirty. */
3079 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003080 {
3081 term->tl_dirty_row_start = 0;
3082 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003083
3084 if (term->tl_postponed_scroll > 0
3085 && term->tl_postponed_scroll < term->tl_rows / 3)
3086 /* Scrolling is usually faster than redrawing, when there are only
3087 * a few lines to scroll. */
3088 term_scroll_up(term, 0, term->tl_postponed_scroll);
3089 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003090 }
3091
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092 /*
3093 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003094 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003095 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003096 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003097
Bram Moolenaar498c2562018-04-15 23:45:15 +02003098 newrows = 99999;
3099 newcols = 99999;
3100 FOR_ALL_WINDOWS(twp)
3101 {
3102 /* When more than one window shows the same terminal, use the
3103 * smallest size. */
3104 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003106 newrows = MIN(newrows, twp->w_height);
3107 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003109 }
3110 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3111 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3112
3113 if (term->tl_rows != newrows || term->tl_cols != newcols)
3114 {
3115
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116
3117 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003118 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003120 newrows);
3121 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003122 }
3123
3124 /* The cursor may have been moved when resizing. */
3125 vterm_state_get_cursorpos(state, &pos);
3126 position_cursor(wp, &pos);
3127
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003128 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3129 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131 if (pos.row < term->tl_rows)
3132 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003133 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134
Bram Moolenaar13568252018-03-16 20:46:58 +01003135 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003136 }
3137 else
3138 pos.col = 0;
3139
Bram Moolenaarf118d482018-03-13 13:14:00 +01003140 screen_line(wp->w_winrow + pos.row
3141#ifdef FEAT_MENU
3142 + winbar_height(wp)
3143#endif
3144 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003146 term->tl_dirty_row_start = MAX_ROW;
3147 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003148}
3149
3150/*
3151 * Return TRUE if "wp" is a terminal window where the job has finished.
3152 */
3153 int
3154term_is_finished(buf_T *buf)
3155{
3156 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3157}
3158
3159/*
3160 * Return TRUE if "wp" is a terminal window where the job has finished or we
3161 * are in Terminal-Normal mode, thus we show the buffer contents.
3162 */
3163 int
3164term_show_buffer(buf_T *buf)
3165{
3166 term_T *term = buf->b_term;
3167
3168 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3169}
3170
3171/*
3172 * The current buffer is going to be changed. If there is terminal
3173 * highlighting remove it now.
3174 */
3175 void
3176term_change_in_curbuf(void)
3177{
3178 term_T *term = curbuf->b_term;
3179
3180 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3181 {
3182 free_scrollback(term);
3183 redraw_buf_later(term->tl_buffer, NOT_VALID);
3184
3185 /* The buffer is now like a normal buffer, it cannot be easily
3186 * abandoned when changed. */
3187 set_string_option_direct((char_u *)"buftype", -1,
3188 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3189 }
3190}
3191
3192/*
3193 * Get the screen attribute for a position in the buffer.
3194 * Use a negative "col" to get the filler background color.
3195 */
3196 int
3197term_get_attr(buf_T *buf, linenr_T lnum, int col)
3198{
3199 term_T *term = buf->b_term;
3200 sb_line_T *line;
3201 cellattr_T *cellattr;
3202
3203 if (lnum > term->tl_scrollback.ga_len)
3204 cellattr = &term->tl_default_color;
3205 else
3206 {
3207 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3208 if (col < 0 || col >= line->sb_cols)
3209 cellattr = &line->sb_fill_attr;
3210 else
3211 cellattr = line->sb_cells + col;
3212 }
3213 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3214}
3215
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216/*
3217 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003218 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003219 */
3220 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003221cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003222{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003223 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003224}
3225
3226/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003227 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003228 */
3229 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003230init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003231{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003232 VTermColor *fg, *bg;
3233 int fgval, bgval;
3234 int id;
3235
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3237 term->tl_default_color.width = 1;
3238 fg = &term->tl_default_color.fg;
3239 bg = &term->tl_default_color.bg;
3240
3241 /* Vterm uses a default black background. Set it to white when
3242 * 'background' is "light". */
3243 if (*p_bg == 'l')
3244 {
3245 fgval = 0;
3246 bgval = 255;
3247 }
3248 else
3249 {
3250 fgval = 255;
3251 bgval = 0;
3252 }
3253 fg->red = fg->green = fg->blue = fgval;
3254 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003255 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256
3257 /* The "Terminal" highlight group overrules the defaults. */
3258 id = syn_name2id((char_u *)"Terminal");
3259
Bram Moolenaar46359e12017-11-29 22:33:38 +01003260 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003261#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3262 if (0
3263# ifdef FEAT_GUI
3264 || gui.in_use
3265# endif
3266# ifdef FEAT_TERMGUICOLORS
3267 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003268# ifdef FEAT_VTP
3269 /* Finally get INVALCOLOR on this execution path */
3270 || (!p_tgc && t_colors >= 256)
3271# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003272# endif
3273 )
3274 {
3275 guicolor_T fg_rgb = INVALCOLOR;
3276 guicolor_T bg_rgb = INVALCOLOR;
3277
3278 if (id != 0)
3279 syn_id2colors(id, &fg_rgb, &bg_rgb);
3280
3281# ifdef FEAT_GUI
3282 if (gui.in_use)
3283 {
3284 if (fg_rgb == INVALCOLOR)
3285 fg_rgb = gui.norm_pixel;
3286 if (bg_rgb == INVALCOLOR)
3287 bg_rgb = gui.back_pixel;
3288 }
3289# ifdef FEAT_TERMGUICOLORS
3290 else
3291# endif
3292# endif
3293# ifdef FEAT_TERMGUICOLORS
3294 {
3295 if (fg_rgb == INVALCOLOR)
3296 fg_rgb = cterm_normal_fg_gui_color;
3297 if (bg_rgb == INVALCOLOR)
3298 bg_rgb = cterm_normal_bg_gui_color;
3299 }
3300# endif
3301 if (fg_rgb != INVALCOLOR)
3302 {
3303 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3304
3305 fg->red = (unsigned)(rgb >> 16);
3306 fg->green = (unsigned)(rgb >> 8) & 255;
3307 fg->blue = (unsigned)rgb & 255;
3308 }
3309 if (bg_rgb != INVALCOLOR)
3310 {
3311 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3312
3313 bg->red = (unsigned)(rgb >> 16);
3314 bg->green = (unsigned)(rgb >> 8) & 255;
3315 bg->blue = (unsigned)rgb & 255;
3316 }
3317 }
3318 else
3319#endif
3320 if (id != 0 && t_colors >= 16)
3321 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003322 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003323 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003324 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003325 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003326 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003327 else
3328 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003329#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003330 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003331#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003332
3333 /* In an MS-Windows console we know the normal colors. */
3334 if (cterm_normal_fg_color > 0)
3335 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003336 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003337# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003338 tmp = fg->red;
3339 fg->red = fg->blue;
3340 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003341# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003342 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003343# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003344 else
3345 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003346# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003347
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003348 if (cterm_normal_bg_color > 0)
3349 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003350 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003351# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352 tmp = bg->red;
3353 bg->red = bg->blue;
3354 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003355# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003357# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003358 else
3359 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003360# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003361 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003362}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003363
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003364#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3365/*
3366 * Set the 16 ANSI colors from array of RGB values
3367 */
3368 static void
3369set_vterm_palette(VTerm *vterm, long_u *rgb)
3370{
3371 int index = 0;
3372 VTermState *state = vterm_obtain_state(vterm);
3373 for (; index < 16; index++)
3374 {
3375 VTermColor color;
3376 color.red = (unsigned)(rgb[index] >> 16);
3377 color.green = (unsigned)(rgb[index] >> 8) & 255;
3378 color.blue = (unsigned)rgb[index] & 255;
3379 vterm_state_set_palette_color(state, index, &color);
3380 }
3381}
3382
3383/*
3384 * Set the ANSI color palette from a list of colors
3385 */
3386 static int
3387set_ansi_colors_list(VTerm *vterm, list_T *list)
3388{
3389 int n = 0;
3390 long_u rgb[16];
3391 listitem_T *li = list->lv_first;
3392
3393 for (; li != NULL && n < 16; li = li->li_next, n++)
3394 {
3395 char_u *color_name;
3396 guicolor_T guicolor;
3397
3398 color_name = get_tv_string_chk(&li->li_tv);
3399 if (color_name == NULL)
3400 return FAIL;
3401
3402 guicolor = GUI_GET_COLOR(color_name);
3403 if (guicolor == INVALCOLOR)
3404 return FAIL;
3405
3406 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3407 }
3408
3409 if (n != 16 || li != NULL)
3410 return FAIL;
3411
3412 set_vterm_palette(vterm, rgb);
3413
3414 return OK;
3415}
3416
3417/*
3418 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3419 */
3420 static void
3421init_vterm_ansi_colors(VTerm *vterm)
3422{
3423 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3424
3425 if (var != NULL
3426 && (var->di_tv.v_type != VAR_LIST
3427 || var->di_tv.vval.v_list == NULL
3428 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3429 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3430}
3431#endif
3432
Bram Moolenaar52acb112018-03-18 19:20:22 +01003433/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003434 * Handles a "drop" command from the job in the terminal.
3435 * "item" is the file name, "item->li_next" may have options.
3436 */
3437 static void
3438handle_drop_command(listitem_T *item)
3439{
3440 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003441 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003442 int bufnr;
3443 win_T *wp;
3444 tabpage_T *tp;
3445 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003446 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003447
3448 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3449 FOR_ALL_TAB_WINDOWS(tp, wp)
3450 {
3451 if (wp->w_buffer->b_fnum == bufnr)
3452 {
3453 /* buffer is in a window already, go there */
3454 goto_tabpage_win(tp, wp);
3455 return;
3456 }
3457 }
3458
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003459 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003460
3461 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3462 && opt_item->li_tv.vval.v_dict != NULL)
3463 {
3464 dict_T *dict = opt_item->li_tv.vval.v_dict;
3465 char_u *p;
3466
3467 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3468 if (p == NULL)
3469 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3470 if (p != NULL)
3471 {
3472 if (check_ff_value(p) == FAIL)
3473 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3474 else
3475 ea.force_ff = *p;
3476 }
3477 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3478 if (p == NULL)
3479 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3480 if (p != NULL)
3481 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003482 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003483 if (ea.cmd != NULL)
3484 {
3485 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3486 ea.force_enc = 11;
3487 tofree = ea.cmd;
3488 }
3489 }
3490
3491 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3492 if (p != NULL)
3493 get_bad_opt(p, &ea);
3494
3495 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3496 ea.force_bin = FORCE_BIN;
3497 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3498 ea.force_bin = FORCE_BIN;
3499 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3500 ea.force_bin = FORCE_NOBIN;
3501 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3502 ea.force_bin = FORCE_NOBIN;
3503 }
3504
3505 /* open in new window, like ":split fname" */
3506 if (ea.cmd == NULL)
3507 ea.cmd = (char_u *)"split";
3508 ea.arg = fname;
3509 ea.cmdidx = CMD_split;
3510 ex_splitview(&ea);
3511
3512 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003513}
3514
3515/*
3516 * Handles a function call from the job running in a terminal.
3517 * "item" is the function name, "item->li_next" has the arguments.
3518 */
3519 static void
3520handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3521{
3522 char_u *func;
3523 typval_T argvars[2];
3524 typval_T rettv;
3525 int doesrange;
3526
3527 if (item->li_next == NULL)
3528 {
3529 ch_log(channel, "Missing function arguments for call");
3530 return;
3531 }
3532 func = get_tv_string(&item->li_tv);
3533
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003534 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003535 {
3536 ch_log(channel, "Invalid function name: %s", func);
3537 return;
3538 }
3539
3540 argvars[0].v_type = VAR_NUMBER;
3541 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3542 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003543 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003544 2, argvars, /* argv_func */ NULL,
3545 /* firstline */ 1, /* lastline */ 1,
3546 &doesrange, /* evaluate */ TRUE,
3547 /* partial */ NULL, /* selfdict */ NULL) == OK)
3548 {
3549 clear_tv(&rettv);
3550 ch_log(channel, "Function %s called", func);
3551 }
3552 else
3553 ch_log(channel, "Calling function %s failed", func);
3554}
3555
3556/*
3557 * Called by libvterm when it cannot recognize an OSC sequence.
3558 * We recognize a terminal API command.
3559 */
3560 static int
3561parse_osc(const char *command, size_t cmdlen, void *user)
3562{
3563 term_T *term = (term_T *)user;
3564 js_read_T reader;
3565 typval_T tv;
3566 channel_T *channel = term->tl_job == NULL ? NULL
3567 : term->tl_job->jv_channel;
3568
3569 /* We recognize only OSC 5 1 ; {command} */
3570 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3571 return 0; /* not handled */
3572
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003573 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003574 if (reader.js_buf == NULL)
3575 return 1;
3576 reader.js_fill = NULL;
3577 reader.js_used = 0;
3578 if (json_decode(&reader, &tv, 0) == OK
3579 && tv.v_type == VAR_LIST
3580 && tv.vval.v_list != NULL)
3581 {
3582 listitem_T *item = tv.vval.v_list->lv_first;
3583
3584 if (item == NULL)
3585 ch_log(channel, "Missing command");
3586 else
3587 {
3588 char_u *cmd = get_tv_string(&item->li_tv);
3589
Bram Moolenaara997b452018-04-17 23:24:06 +02003590 /* Make sure an invoked command doesn't delete the buffer (and the
3591 * terminal) under our fingers. */
3592 ++term->tl_buffer->b_locked;
3593
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003594 item = item->li_next;
3595 if (item == NULL)
3596 ch_log(channel, "Missing argument for %s", cmd);
3597 else if (STRCMP(cmd, "drop") == 0)
3598 handle_drop_command(item);
3599 else if (STRCMP(cmd, "call") == 0)
3600 handle_call_command(term, channel, item);
3601 else
3602 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003603 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003604 }
3605 }
3606 else
3607 ch_log(channel, "Invalid JSON received");
3608
3609 vim_free(reader.js_buf);
3610 clear_tv(&tv);
3611 return 1;
3612}
3613
3614static VTermParserCallbacks parser_fallbacks = {
3615 NULL, /* text */
3616 NULL, /* control */
3617 NULL, /* escape */
3618 NULL, /* csi */
3619 parse_osc, /* osc */
3620 NULL, /* dcs */
3621 NULL /* resize */
3622};
3623
3624/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003625 * Use Vim's allocation functions for vterm so profiling works.
3626 */
3627 static void *
3628vterm_malloc(size_t size, void *data UNUSED)
3629{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003630 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003631}
3632
3633 static void
3634vterm_memfree(void *ptr, void *data UNUSED)
3635{
3636 vim_free(ptr);
3637}
3638
3639static VTermAllocatorFunctions vterm_allocator = {
3640 &vterm_malloc,
3641 &vterm_memfree
3642};
3643
3644/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003645 * Create a new vterm and initialize it.
3646 */
3647 static void
3648create_vterm(term_T *term, int rows, int cols)
3649{
3650 VTerm *vterm;
3651 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003652 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003653 VTermValue value;
3654
Bram Moolenaar756ef112018-04-10 12:04:27 +02003655 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003656 term->tl_vterm = vterm;
3657 screen = vterm_obtain_screen(vterm);
3658 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3659 /* TODO: depends on 'encoding'. */
3660 vterm_set_utf8(vterm, 1);
3661
3662 init_default_colors(term);
3663
3664 vterm_state_set_default_colors(
3665 vterm_obtain_state(vterm),
3666 &term->tl_default_color.fg,
3667 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003668
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003669 if (t_colors >= 16)
3670 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003672 /* Required to initialize most things. */
3673 vterm_screen_reset(screen, 1 /* hard */);
3674
3675 /* Allow using alternate screen. */
3676 vterm_screen_enable_altscreen(screen, 1);
3677
3678 /* For unix do not use a blinking cursor. In an xterm this causes the
3679 * cursor to blink if it's blinking in the xterm.
3680 * For Windows we respect the system wide setting. */
3681#ifdef WIN3264
3682 if (GetCaretBlinkTime() == INFINITE)
3683 value.boolean = 0;
3684 else
3685 value.boolean = 1;
3686#else
3687 value.boolean = 0;
3688#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003689 state = vterm_obtain_state(vterm);
3690 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3691 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003692}
3693
3694/*
3695 * Return the text to show for the buffer name and status.
3696 */
3697 char_u *
3698term_get_status_text(term_T *term)
3699{
3700 if (term->tl_status_text == NULL)
3701 {
3702 char_u *txt;
3703 size_t len;
3704
3705 if (term->tl_normal_mode)
3706 {
3707 if (term_job_running(term))
3708 txt = (char_u *)_("Terminal");
3709 else
3710 txt = (char_u *)_("Terminal-finished");
3711 }
3712 else if (term->tl_title != NULL)
3713 txt = term->tl_title;
3714 else if (term_none_open(term))
3715 txt = (char_u *)_("active");
3716 else if (term_job_running(term))
3717 txt = (char_u *)_("running");
3718 else
3719 txt = (char_u *)_("finished");
3720 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3721 term->tl_status_text = alloc((int)len);
3722 if (term->tl_status_text != NULL)
3723 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3724 term->tl_buffer->b_fname, txt);
3725 }
3726 return term->tl_status_text;
3727}
3728
3729/*
3730 * Mark references in jobs of terminals.
3731 */
3732 int
3733set_ref_in_term(int copyID)
3734{
3735 int abort = FALSE;
3736 term_T *term;
3737 typval_T tv;
3738
3739 for (term = first_term; term != NULL; term = term->tl_next)
3740 if (term->tl_job != NULL)
3741 {
3742 tv.v_type = VAR_JOB;
3743 tv.vval.v_job = term->tl_job;
3744 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3745 }
3746 return abort;
3747}
3748
3749/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003750 * Cache "Terminal" highlight group colors.
3751 */
3752 void
3753set_terminal_default_colors(int cterm_fg, int cterm_bg)
3754{
3755 term_default_cterm_fg = cterm_fg - 1;
3756 term_default_cterm_bg = cterm_bg - 1;
3757}
3758
3759/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003760 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003761 * Returns NULL when the buffer is not for a terminal window and logs a message
3762 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003763 */
3764 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003765term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003766{
3767 buf_T *buf;
3768
3769 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3770 ++emsg_off;
3771 buf = get_buf_tv(&argvars[0], FALSE);
3772 --emsg_off;
3773 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003774 {
3775 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003776 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003777 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003778 return buf;
3779}
3780
Bram Moolenaard96ff162018-02-18 22:13:29 +01003781 static int
3782same_color(VTermColor *a, VTermColor *b)
3783{
3784 return a->red == b->red
3785 && a->green == b->green
3786 && a->blue == b->blue
3787 && a->ansi_index == b->ansi_index;
3788}
3789
3790 static void
3791dump_term_color(FILE *fd, VTermColor *color)
3792{
3793 fprintf(fd, "%02x%02x%02x%d",
3794 (int)color->red, (int)color->green, (int)color->blue,
3795 (int)color->ansi_index);
3796}
3797
3798/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003799 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003800 *
3801 * Each screen cell in full is:
3802 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3803 * {characters} is a space for an empty cell
3804 * For a double-width character "+" is changed to "*" and the next cell is
3805 * skipped.
3806 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3807 * when "&" use the same as the previous cell.
3808 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3809 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3810 * {color-idx} is a number from 0 to 255
3811 *
3812 * Screen cell with same width, attributes and color as the previous one:
3813 * |{characters}
3814 *
3815 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3816 *
3817 * Repeating the previous screen cell:
3818 * @{count}
3819 */
3820 void
3821f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3822{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003823 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003824 term_T *term;
3825 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003826 int max_height = 0;
3827 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003828 stat_T st;
3829 FILE *fd;
3830 VTermPos pos;
3831 VTermScreen *screen;
3832 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003833 VTermState *state;
3834 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003835
3836 if (check_restricted() || check_secure())
3837 return;
3838 if (buf == NULL)
3839 return;
3840 term = buf->b_term;
3841
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003842 if (argvars[2].v_type != VAR_UNKNOWN)
3843 {
3844 dict_T *d;
3845
3846 if (argvars[2].v_type != VAR_DICT)
3847 {
3848 EMSG(_(e_dictreq));
3849 return;
3850 }
3851 d = argvars[2].vval.v_dict;
3852 if (d != NULL)
3853 {
3854 max_height = get_dict_number(d, (char_u *)"rows");
3855 max_width = get_dict_number(d, (char_u *)"columns");
3856 }
3857 }
3858
Bram Moolenaard96ff162018-02-18 22:13:29 +01003859 fname = get_tv_string_chk(&argvars[1]);
3860 if (fname == NULL)
3861 return;
3862 if (mch_stat((char *)fname, &st) >= 0)
3863 {
3864 EMSG2(_("E953: File exists: %s"), fname);
3865 return;
3866 }
3867
Bram Moolenaard96ff162018-02-18 22:13:29 +01003868 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3869 {
3870 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3871 return;
3872 }
3873
3874 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3875
3876 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003877 state = vterm_obtain_state(term->tl_vterm);
3878 vterm_state_get_cursorpos(state, &cursor_pos);
3879
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003880 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3881 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003882 {
3883 int repeat = 0;
3884
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003885 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3886 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003887 {
3888 VTermScreenCell cell;
3889 int same_attr;
3890 int same_chars = TRUE;
3891 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003892 int is_cursor_pos = (pos.col == cursor_pos.col
3893 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003894
3895 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3896 vim_memset(&cell, 0, sizeof(cell));
3897
3898 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3899 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003900 int c = cell.chars[i];
3901 int pc = prev_cell.chars[i];
3902
3903 /* For the first character NUL is the same as space. */
3904 if (i == 0)
3905 {
3906 c = (c == NUL) ? ' ' : c;
3907 pc = (pc == NUL) ? ' ' : pc;
3908 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003909 if (cell.chars[i] != prev_cell.chars[i])
3910 same_chars = FALSE;
3911 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3912 break;
3913 }
3914 same_attr = vtermAttr2hl(cell.attrs)
3915 == vtermAttr2hl(prev_cell.attrs)
3916 && same_color(&cell.fg, &prev_cell.fg)
3917 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003918 if (same_chars && cell.width == prev_cell.width && same_attr
3919 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003920 {
3921 ++repeat;
3922 }
3923 else
3924 {
3925 if (repeat > 0)
3926 {
3927 fprintf(fd, "@%d", repeat);
3928 repeat = 0;
3929 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003930 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003931
3932 if (cell.chars[0] == NUL)
3933 fputs(" ", fd);
3934 else
3935 {
3936 char_u charbuf[10];
3937 int len;
3938
3939 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3940 && cell.chars[i] != NUL; ++i)
3941 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003942 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003943 fwrite(charbuf, len, 1, fd);
3944 }
3945 }
3946
3947 /* When only the characters differ we don't write anything, the
3948 * following "|", "@" or NL will indicate using the same
3949 * attributes. */
3950 if (cell.width != prev_cell.width || !same_attr)
3951 {
3952 if (cell.width == 2)
3953 {
3954 fputs("*", fd);
3955 ++pos.col;
3956 }
3957 else
3958 fputs("+", fd);
3959
3960 if (same_attr)
3961 {
3962 fputs("&", fd);
3963 }
3964 else
3965 {
3966 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3967 if (same_color(&cell.fg, &prev_cell.fg))
3968 fputs("&", fd);
3969 else
3970 {
3971 fputs("#", fd);
3972 dump_term_color(fd, &cell.fg);
3973 }
3974 if (same_color(&cell.bg, &prev_cell.bg))
3975 fputs("&", fd);
3976 else
3977 {
3978 fputs("#", fd);
3979 dump_term_color(fd, &cell.bg);
3980 }
3981 }
3982 }
3983
3984 prev_cell = cell;
3985 }
3986 }
3987 if (repeat > 0)
3988 fprintf(fd, "@%d", repeat);
3989 fputs("\n", fd);
3990 }
3991
3992 fclose(fd);
3993}
3994
3995/*
3996 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3997 */
3998 static void
3999dump_is_corrupt(garray_T *gap)
4000{
4001 ga_concat(gap, (char_u *)"CORRUPT");
4002}
4003
4004 static void
4005append_cell(garray_T *gap, cellattr_T *cell)
4006{
4007 if (ga_grow(gap, 1) == OK)
4008 {
4009 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4010 ++gap->ga_len;
4011 }
4012}
4013
4014/*
4015 * Read the dump file from "fd" and append lines to the current buffer.
4016 * Return the cell width of the longest line.
4017 */
4018 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004019read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004020{
4021 int c;
4022 garray_T ga_text;
4023 garray_T ga_cell;
4024 char_u *prev_char = NULL;
4025 int attr = 0;
4026 cellattr_T cell;
4027 term_T *term = curbuf->b_term;
4028 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004029 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004030
4031 ga_init2(&ga_text, 1, 90);
4032 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4033 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004034 cursor_pos->row = -1;
4035 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004036
4037 c = fgetc(fd);
4038 for (;;)
4039 {
4040 if (c == EOF)
4041 break;
4042 if (c == '\n')
4043 {
4044 /* End of a line: append it to the buffer. */
4045 if (ga_text.ga_data == NULL)
4046 dump_is_corrupt(&ga_text);
4047 if (ga_grow(&term->tl_scrollback, 1) == OK)
4048 {
4049 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4050 + term->tl_scrollback.ga_len;
4051
4052 if (max_cells < ga_cell.ga_len)
4053 max_cells = ga_cell.ga_len;
4054 line->sb_cols = ga_cell.ga_len;
4055 line->sb_cells = ga_cell.ga_data;
4056 line->sb_fill_attr = term->tl_default_color;
4057 ++term->tl_scrollback.ga_len;
4058 ga_init(&ga_cell);
4059
4060 ga_append(&ga_text, NUL);
4061 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4062 ga_text.ga_len, FALSE);
4063 }
4064 else
4065 ga_clear(&ga_cell);
4066 ga_text.ga_len = 0;
4067
4068 c = fgetc(fd);
4069 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004070 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004071 {
4072 int prev_len = ga_text.ga_len;
4073
Bram Moolenaar9271d052018-02-25 21:39:46 +01004074 if (c == '>')
4075 {
4076 if (cursor_pos->row != -1)
4077 dump_is_corrupt(&ga_text); /* duplicate cursor */
4078 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4079 cursor_pos->col = ga_cell.ga_len;
4080 }
4081
Bram Moolenaard96ff162018-02-18 22:13:29 +01004082 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4083 c = fgetc(fd);
4084 if (c != EOF)
4085 ga_append(&ga_text, c);
4086 for (;;)
4087 {
4088 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004089 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004090 || c == EOF || c == '\n')
4091 break;
4092 ga_append(&ga_text, c);
4093 }
4094
4095 /* save the character for repeating it */
4096 vim_free(prev_char);
4097 if (ga_text.ga_data != NULL)
4098 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4099 ga_text.ga_len - prev_len);
4100
Bram Moolenaar9271d052018-02-25 21:39:46 +01004101 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004102 {
4103 /* use all attributes from previous cell */
4104 }
4105 else if (c == '+' || c == '*')
4106 {
4107 int is_bg;
4108
4109 cell.width = c == '+' ? 1 : 2;
4110
4111 c = fgetc(fd);
4112 if (c == '&')
4113 {
4114 /* use same attr as previous cell */
4115 c = fgetc(fd);
4116 }
4117 else if (isdigit(c))
4118 {
4119 /* get the decimal attribute */
4120 attr = 0;
4121 while (isdigit(c))
4122 {
4123 attr = attr * 10 + (c - '0');
4124 c = fgetc(fd);
4125 }
4126 hl2vtermAttr(attr, &cell);
4127 }
4128 else
4129 dump_is_corrupt(&ga_text);
4130
4131 /* is_bg == 0: fg, is_bg == 1: bg */
4132 for (is_bg = 0; is_bg <= 1; ++is_bg)
4133 {
4134 if (c == '&')
4135 {
4136 /* use same color as previous cell */
4137 c = fgetc(fd);
4138 }
4139 else if (c == '#')
4140 {
4141 int red, green, blue, index = 0;
4142
4143 c = fgetc(fd);
4144 red = hex2nr(c);
4145 c = fgetc(fd);
4146 red = (red << 4) + hex2nr(c);
4147 c = fgetc(fd);
4148 green = hex2nr(c);
4149 c = fgetc(fd);
4150 green = (green << 4) + hex2nr(c);
4151 c = fgetc(fd);
4152 blue = hex2nr(c);
4153 c = fgetc(fd);
4154 blue = (blue << 4) + hex2nr(c);
4155 c = fgetc(fd);
4156 if (!isdigit(c))
4157 dump_is_corrupt(&ga_text);
4158 while (isdigit(c))
4159 {
4160 index = index * 10 + (c - '0');
4161 c = fgetc(fd);
4162 }
4163
4164 if (is_bg)
4165 {
4166 cell.bg.red = red;
4167 cell.bg.green = green;
4168 cell.bg.blue = blue;
4169 cell.bg.ansi_index = index;
4170 }
4171 else
4172 {
4173 cell.fg.red = red;
4174 cell.fg.green = green;
4175 cell.fg.blue = blue;
4176 cell.fg.ansi_index = index;
4177 }
4178 }
4179 else
4180 dump_is_corrupt(&ga_text);
4181 }
4182 }
4183 else
4184 dump_is_corrupt(&ga_text);
4185
4186 append_cell(&ga_cell, &cell);
4187 }
4188 else if (c == '@')
4189 {
4190 if (prev_char == NULL)
4191 dump_is_corrupt(&ga_text);
4192 else
4193 {
4194 int count = 0;
4195
4196 /* repeat previous character, get the count */
4197 for (;;)
4198 {
4199 c = fgetc(fd);
4200 if (!isdigit(c))
4201 break;
4202 count = count * 10 + (c - '0');
4203 }
4204
4205 while (count-- > 0)
4206 {
4207 ga_concat(&ga_text, prev_char);
4208 append_cell(&ga_cell, &cell);
4209 }
4210 }
4211 }
4212 else
4213 {
4214 dump_is_corrupt(&ga_text);
4215 c = fgetc(fd);
4216 }
4217 }
4218
4219 if (ga_text.ga_len > 0)
4220 {
4221 /* trailing characters after last NL */
4222 dump_is_corrupt(&ga_text);
4223 ga_append(&ga_text, NUL);
4224 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4225 ga_text.ga_len, FALSE);
4226 }
4227
4228 ga_clear(&ga_text);
4229 vim_free(prev_char);
4230
4231 return max_cells;
4232}
4233
4234/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004235 * Return an allocated string with at least "text_width" "=" characters and
4236 * "fname" inserted in the middle.
4237 */
4238 static char_u *
4239get_separator(int text_width, char_u *fname)
4240{
4241 int width = MAX(text_width, curwin->w_width);
4242 char_u *textline;
4243 int fname_size;
4244 char_u *p = fname;
4245 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004246 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004247
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004248 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004249 if (textline == NULL)
4250 return NULL;
4251
4252 fname_size = vim_strsize(fname);
4253 if (fname_size < width - 8)
4254 {
4255 /* enough room, don't use the full window width */
4256 width = MAX(text_width, fname_size + 8);
4257 }
4258 else if (fname_size > width - 8)
4259 {
4260 /* full name doesn't fit, use only the tail */
4261 p = gettail(fname);
4262 fname_size = vim_strsize(p);
4263 }
4264 /* skip characters until the name fits */
4265 while (fname_size > width - 8)
4266 {
4267 p += (*mb_ptr2len)(p);
4268 fname_size = vim_strsize(p);
4269 }
4270
4271 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4272 textline[i] = '=';
4273 textline[i++] = ' ';
4274
4275 STRCPY(textline + i, p);
4276 off = STRLEN(textline);
4277 textline[off] = ' ';
4278 for (i = 1; i < (width - fname_size) / 2; ++i)
4279 textline[off + i] = '=';
4280 textline[off + i] = NUL;
4281
4282 return textline;
4283}
4284
4285/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004286 * Common for "term_dumpdiff()" and "term_dumpload()".
4287 */
4288 static void
4289term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4290{
4291 jobopt_T opt;
4292 buf_T *buf;
4293 char_u buf1[NUMBUFLEN];
4294 char_u buf2[NUMBUFLEN];
4295 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004296 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004297 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004298 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004299 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004300 char_u *textline = NULL;
4301
4302 /* First open the files. If this fails bail out. */
4303 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4304 if (do_diff)
4305 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4306 if (fname1 == NULL || (do_diff && fname2 == NULL))
4307 {
4308 EMSG(_(e_invarg));
4309 return;
4310 }
4311 fd1 = mch_fopen((char *)fname1, READBIN);
4312 if (fd1 == NULL)
4313 {
4314 EMSG2(_(e_notread), fname1);
4315 return;
4316 }
4317 if (do_diff)
4318 {
4319 fd2 = mch_fopen((char *)fname2, READBIN);
4320 if (fd2 == NULL)
4321 {
4322 fclose(fd1);
4323 EMSG2(_(e_notread), fname2);
4324 return;
4325 }
4326 }
4327
4328 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004329 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4330 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4331 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4332 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4333 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004334
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004335 if (opt.jo_term_name == NULL)
4336 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004337 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004338
Bram Moolenaarb571c632018-03-21 22:27:59 +01004339 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004340 if (fname_tofree != NULL)
4341 {
4342 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4343 opt.jo_term_name = fname_tofree;
4344 }
4345 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004346
Bram Moolenaar13568252018-03-16 20:46:58 +01004347 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004348 if (buf != NULL && buf->b_term != NULL)
4349 {
4350 int i;
4351 linenr_T bot_lnum;
4352 linenr_T lnum;
4353 term_T *term = buf->b_term;
4354 int width;
4355 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004356 VTermPos cursor_pos1;
4357 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004358
Bram Moolenaar52acb112018-03-18 19:20:22 +01004359 init_default_colors(term);
4360
Bram Moolenaard96ff162018-02-18 22:13:29 +01004361 rettv->vval.v_number = buf->b_fnum;
4362
4363 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004364 width = read_dump_file(fd1, &cursor_pos1);
4365
4366 /* position the cursor */
4367 if (cursor_pos1.row >= 0)
4368 {
4369 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4370 coladvance(cursor_pos1.col);
4371 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004372
4373 /* Delete the empty line that was in the empty buffer. */
4374 ml_delete(1, FALSE);
4375
4376 /* For term_dumpload() we are done here. */
4377 if (!do_diff)
4378 goto theend;
4379
4380 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4381
Bram Moolenaar4a696342018-04-05 18:45:26 +02004382 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004383 if (textline == NULL)
4384 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004385 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4386 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4387 vim_free(textline);
4388
4389 textline = get_separator(width, fname2);
4390 if (textline == NULL)
4391 goto theend;
4392 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4393 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004394 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004395
4396 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004397 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004398 if (width2 > width)
4399 {
4400 vim_free(textline);
4401 textline = alloc(width2 + 1);
4402 if (textline == NULL)
4403 goto theend;
4404 width = width2;
4405 textline[width] = NUL;
4406 }
4407 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4408
4409 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4410 {
4411 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4412 {
4413 /* bottom part has fewer rows, fill with "-" */
4414 for (i = 0; i < width; ++i)
4415 textline[i] = '-';
4416 }
4417 else
4418 {
4419 char_u *line1;
4420 char_u *line2;
4421 char_u *p1;
4422 char_u *p2;
4423 int col;
4424 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4425 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4426 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4427 ->sb_cells;
4428
4429 /* Make a copy, getting the second line will invalidate it. */
4430 line1 = vim_strsave(ml_get(lnum));
4431 if (line1 == NULL)
4432 break;
4433 p1 = line1;
4434
4435 line2 = ml_get(lnum + bot_lnum);
4436 p2 = line2;
4437 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4438 {
4439 int len1 = utfc_ptr2len(p1);
4440 int len2 = utfc_ptr2len(p2);
4441
4442 textline[col] = ' ';
4443 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004444 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004445 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004446 else if (lnum == cursor_pos1.row + 1
4447 && col == cursor_pos1.col
4448 && (cursor_pos1.row != cursor_pos2.row
4449 || cursor_pos1.col != cursor_pos2.col))
4450 /* cursor in first but not in second */
4451 textline[col] = '>';
4452 else if (lnum == cursor_pos2.row + 1
4453 && col == cursor_pos2.col
4454 && (cursor_pos1.row != cursor_pos2.row
4455 || cursor_pos1.col != cursor_pos2.col))
4456 /* cursor in second but not in first */
4457 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004458 else if (cellattr1 != NULL && cellattr2 != NULL)
4459 {
4460 if ((cellattr1 + col)->width
4461 != (cellattr2 + col)->width)
4462 textline[col] = 'w';
4463 else if (!same_color(&(cellattr1 + col)->fg,
4464 &(cellattr2 + col)->fg))
4465 textline[col] = 'f';
4466 else if (!same_color(&(cellattr1 + col)->bg,
4467 &(cellattr2 + col)->bg))
4468 textline[col] = 'b';
4469 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4470 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4471 textline[col] = 'a';
4472 }
4473 p1 += len1;
4474 p2 += len2;
4475 /* TODO: handle different width */
4476 }
4477 vim_free(line1);
4478
4479 while (col < width)
4480 {
4481 if (*p1 == NUL && *p2 == NUL)
4482 textline[col] = '?';
4483 else if (*p1 == NUL)
4484 {
4485 textline[col] = '+';
4486 p2 += utfc_ptr2len(p2);
4487 }
4488 else
4489 {
4490 textline[col] = '-';
4491 p1 += utfc_ptr2len(p1);
4492 }
4493 ++col;
4494 }
4495 }
4496 if (add_empty_scrollback(term, &term->tl_default_color,
4497 term->tl_top_diff_rows) == OK)
4498 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4499 ++bot_lnum;
4500 }
4501
4502 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4503 {
4504 /* bottom part has more rows, fill with "+" */
4505 for (i = 0; i < width; ++i)
4506 textline[i] = '+';
4507 if (add_empty_scrollback(term, &term->tl_default_color,
4508 term->tl_top_diff_rows) == OK)
4509 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4510 ++lnum;
4511 ++bot_lnum;
4512 }
4513
4514 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004515
4516 /* looks better without wrapping */
4517 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004518 }
4519
4520theend:
4521 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004522 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004523 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004524 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004525 fclose(fd2);
4526}
4527
4528/*
4529 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4530 * bottom files.
4531 * Return FAIL when this is not possible.
4532 */
4533 int
4534term_swap_diff()
4535{
4536 term_T *term = curbuf->b_term;
4537 linenr_T line_count;
4538 linenr_T top_rows;
4539 linenr_T bot_rows;
4540 linenr_T bot_start;
4541 linenr_T lnum;
4542 char_u *p;
4543 sb_line_T *sb_line;
4544
4545 if (term == NULL
4546 || !term_is_finished(curbuf)
4547 || term->tl_top_diff_rows == 0
4548 || term->tl_scrollback.ga_len == 0)
4549 return FAIL;
4550
4551 line_count = curbuf->b_ml.ml_line_count;
4552 top_rows = term->tl_top_diff_rows;
4553 bot_rows = term->tl_bot_diff_rows;
4554 bot_start = line_count - bot_rows;
4555 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4556
4557 /* move lines from top to above the bottom part */
4558 for (lnum = 1; lnum <= top_rows; ++lnum)
4559 {
4560 p = vim_strsave(ml_get(1));
4561 if (p == NULL)
4562 return OK;
4563 ml_append(bot_start, p, 0, FALSE);
4564 ml_delete(1, FALSE);
4565 vim_free(p);
4566 }
4567
4568 /* move lines from bottom to the top */
4569 for (lnum = 1; lnum <= bot_rows; ++lnum)
4570 {
4571 p = vim_strsave(ml_get(bot_start + lnum));
4572 if (p == NULL)
4573 return OK;
4574 ml_delete(bot_start + lnum, FALSE);
4575 ml_append(lnum - 1, p, 0, FALSE);
4576 vim_free(p);
4577 }
4578
4579 if (top_rows == bot_rows)
4580 {
4581 /* rows counts are equal, can swap cell properties */
4582 for (lnum = 0; lnum < top_rows; ++lnum)
4583 {
4584 sb_line_T temp;
4585
4586 temp = *(sb_line + lnum);
4587 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4588 *(sb_line + bot_start + lnum) = temp;
4589 }
4590 }
4591 else
4592 {
4593 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4594 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4595
4596 /* need to copy cell properties into temp memory */
4597 if (temp != NULL)
4598 {
4599 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4600 mch_memmove(term->tl_scrollback.ga_data,
4601 temp + bot_start,
4602 sizeof(sb_line_T) * bot_rows);
4603 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4604 temp + top_rows,
4605 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4606 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4607 + line_count - top_rows,
4608 temp,
4609 sizeof(sb_line_T) * top_rows);
4610 vim_free(temp);
4611 }
4612 }
4613
4614 term->tl_top_diff_rows = bot_rows;
4615 term->tl_bot_diff_rows = top_rows;
4616
4617 update_screen(NOT_VALID);
4618 return OK;
4619}
4620
4621/*
4622 * "term_dumpdiff(filename, filename, options)" function
4623 */
4624 void
4625f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4626{
4627 term_load_dump(argvars, rettv, TRUE);
4628}
4629
4630/*
4631 * "term_dumpload(filename, options)" function
4632 */
4633 void
4634f_term_dumpload(typval_T *argvars, typval_T *rettv)
4635{
4636 term_load_dump(argvars, rettv, FALSE);
4637}
4638
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004639/*
4640 * "term_getaltscreen(buf)" function
4641 */
4642 void
4643f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4644{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004645 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004646
4647 if (buf == NULL)
4648 return;
4649 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4650}
4651
4652/*
4653 * "term_getattr(attr, name)" function
4654 */
4655 void
4656f_term_getattr(typval_T *argvars, typval_T *rettv)
4657{
4658 int attr;
4659 size_t i;
4660 char_u *name;
4661
4662 static struct {
4663 char *name;
4664 int attr;
4665 } attrs[] = {
4666 {"bold", HL_BOLD},
4667 {"italic", HL_ITALIC},
4668 {"underline", HL_UNDERLINE},
4669 {"strike", HL_STRIKETHROUGH},
4670 {"reverse", HL_INVERSE},
4671 };
4672
4673 attr = get_tv_number(&argvars[0]);
4674 name = get_tv_string_chk(&argvars[1]);
4675 if (name == NULL)
4676 return;
4677
4678 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4679 if (STRCMP(name, attrs[i].name) == 0)
4680 {
4681 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4682 break;
4683 }
4684}
4685
4686/*
4687 * "term_getcursor(buf)" function
4688 */
4689 void
4690f_term_getcursor(typval_T *argvars, typval_T *rettv)
4691{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004692 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004693 term_T *term;
4694 list_T *l;
4695 dict_T *d;
4696
4697 if (rettv_list_alloc(rettv) == FAIL)
4698 return;
4699 if (buf == NULL)
4700 return;
4701 term = buf->b_term;
4702
4703 l = rettv->vval.v_list;
4704 list_append_number(l, term->tl_cursor_pos.row + 1);
4705 list_append_number(l, term->tl_cursor_pos.col + 1);
4706
4707 d = dict_alloc();
4708 if (d != NULL)
4709 {
4710 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4711 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4712 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4713 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4714 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4715 ? (char_u *)"" : term->tl_cursor_color);
4716 list_append_dict(l, d);
4717 }
4718}
4719
4720/*
4721 * "term_getjob(buf)" function
4722 */
4723 void
4724f_term_getjob(typval_T *argvars, typval_T *rettv)
4725{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004726 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004727
4728 rettv->v_type = VAR_JOB;
4729 rettv->vval.v_job = NULL;
4730 if (buf == NULL)
4731 return;
4732
4733 rettv->vval.v_job = buf->b_term->tl_job;
4734 if (rettv->vval.v_job != NULL)
4735 ++rettv->vval.v_job->jv_refcount;
4736}
4737
4738 static int
4739get_row_number(typval_T *tv, term_T *term)
4740{
4741 if (tv->v_type == VAR_STRING
4742 && tv->vval.v_string != NULL
4743 && STRCMP(tv->vval.v_string, ".") == 0)
4744 return term->tl_cursor_pos.row;
4745 return (int)get_tv_number(tv) - 1;
4746}
4747
4748/*
4749 * "term_getline(buf, row)" function
4750 */
4751 void
4752f_term_getline(typval_T *argvars, typval_T *rettv)
4753{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004754 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004755 term_T *term;
4756 int row;
4757
4758 rettv->v_type = VAR_STRING;
4759 if (buf == NULL)
4760 return;
4761 term = buf->b_term;
4762 row = get_row_number(&argvars[1], term);
4763
4764 if (term->tl_vterm == NULL)
4765 {
4766 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4767
4768 /* vterm is finished, get the text from the buffer */
4769 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4770 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4771 }
4772 else
4773 {
4774 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4775 VTermRect rect;
4776 int len;
4777 char_u *p;
4778
4779 if (row < 0 || row >= term->tl_rows)
4780 return;
4781 len = term->tl_cols * MB_MAXBYTES + 1;
4782 p = alloc(len);
4783 if (p == NULL)
4784 return;
4785 rettv->vval.v_string = p;
4786
4787 rect.start_col = 0;
4788 rect.end_col = term->tl_cols;
4789 rect.start_row = row;
4790 rect.end_row = row + 1;
4791 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4792 }
4793}
4794
4795/*
4796 * "term_getscrolled(buf)" function
4797 */
4798 void
4799f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4800{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004801 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004802
4803 if (buf == NULL)
4804 return;
4805 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4806}
4807
4808/*
4809 * "term_getsize(buf)" function
4810 */
4811 void
4812f_term_getsize(typval_T *argvars, typval_T *rettv)
4813{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004814 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004815 list_T *l;
4816
4817 if (rettv_list_alloc(rettv) == FAIL)
4818 return;
4819 if (buf == NULL)
4820 return;
4821
4822 l = rettv->vval.v_list;
4823 list_append_number(l, buf->b_term->tl_rows);
4824 list_append_number(l, buf->b_term->tl_cols);
4825}
4826
4827/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004828 * "term_setsize(buf, rows, cols)" function
4829 */
4830 void
4831f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4832{
4833 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4834 term_T *term;
4835 varnumber_T rows, cols;
4836
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004837 if (buf == NULL)
4838 {
4839 EMSG(_("E955: Not a terminal buffer"));
4840 return;
4841 }
4842 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004843 return;
4844 term = buf->b_term;
4845 rows = get_tv_number(&argvars[1]);
4846 rows = rows <= 0 ? term->tl_rows : rows;
4847 cols = get_tv_number(&argvars[2]);
4848 cols = cols <= 0 ? term->tl_cols : cols;
4849 vterm_set_size(term->tl_vterm, rows, cols);
4850 /* handle_resize() will resize the windows */
4851
4852 /* Get and remember the size we ended up with. Update the pty. */
4853 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4854 term_report_winsize(term, term->tl_rows, term->tl_cols);
4855}
4856
4857/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004858 * "term_getstatus(buf)" function
4859 */
4860 void
4861f_term_getstatus(typval_T *argvars, typval_T *rettv)
4862{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004863 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004864 term_T *term;
4865 char_u val[100];
4866
4867 rettv->v_type = VAR_STRING;
4868 if (buf == NULL)
4869 return;
4870 term = buf->b_term;
4871
4872 if (term_job_running(term))
4873 STRCPY(val, "running");
4874 else
4875 STRCPY(val, "finished");
4876 if (term->tl_normal_mode)
4877 STRCAT(val, ",normal");
4878 rettv->vval.v_string = vim_strsave(val);
4879}
4880
4881/*
4882 * "term_gettitle(buf)" function
4883 */
4884 void
4885f_term_gettitle(typval_T *argvars, typval_T *rettv)
4886{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004887 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004888
4889 rettv->v_type = VAR_STRING;
4890 if (buf == NULL)
4891 return;
4892
4893 if (buf->b_term->tl_title != NULL)
4894 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4895}
4896
4897/*
4898 * "term_gettty(buf)" function
4899 */
4900 void
4901f_term_gettty(typval_T *argvars, typval_T *rettv)
4902{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004903 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004904 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004905 int num = 0;
4906
4907 rettv->v_type = VAR_STRING;
4908 if (buf == NULL)
4909 return;
4910 if (argvars[1].v_type != VAR_UNKNOWN)
4911 num = get_tv_number(&argvars[1]);
4912
4913 switch (num)
4914 {
4915 case 0:
4916 if (buf->b_term->tl_job != NULL)
4917 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004918 break;
4919 case 1:
4920 if (buf->b_term->tl_job != NULL)
4921 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004922 break;
4923 default:
4924 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4925 return;
4926 }
4927 if (p != NULL)
4928 rettv->vval.v_string = vim_strsave(p);
4929}
4930
4931/*
4932 * "term_list()" function
4933 */
4934 void
4935f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4936{
4937 term_T *tp;
4938 list_T *l;
4939
4940 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4941 return;
4942
4943 l = rettv->vval.v_list;
4944 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4945 if (tp != NULL && tp->tl_buffer != NULL)
4946 if (list_append_number(l,
4947 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4948 return;
4949}
4950
4951/*
4952 * "term_scrape(buf, row)" function
4953 */
4954 void
4955f_term_scrape(typval_T *argvars, typval_T *rettv)
4956{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004957 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004958 VTermScreen *screen = NULL;
4959 VTermPos pos;
4960 list_T *l;
4961 term_T *term;
4962 char_u *p;
4963 sb_line_T *line;
4964
4965 if (rettv_list_alloc(rettv) == FAIL)
4966 return;
4967 if (buf == NULL)
4968 return;
4969 term = buf->b_term;
4970
4971 l = rettv->vval.v_list;
4972 pos.row = get_row_number(&argvars[1], term);
4973
4974 if (term->tl_vterm != NULL)
4975 {
4976 screen = vterm_obtain_screen(term->tl_vterm);
4977 p = NULL;
4978 line = NULL;
4979 }
4980 else
4981 {
4982 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4983
4984 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4985 return;
4986 p = ml_get_buf(buf, lnum + 1, FALSE);
4987 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4988 }
4989
4990 for (pos.col = 0; pos.col < term->tl_cols; )
4991 {
4992 dict_T *dcell;
4993 int width;
4994 VTermScreenCellAttrs attrs;
4995 VTermColor fg, bg;
4996 char_u rgb[8];
4997 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4998 int off = 0;
4999 int i;
5000
5001 if (screen == NULL)
5002 {
5003 cellattr_T *cellattr;
5004 int len;
5005
5006 /* vterm has finished, get the cell from scrollback */
5007 if (pos.col >= line->sb_cols)
5008 break;
5009 cellattr = line->sb_cells + pos.col;
5010 width = cellattr->width;
5011 attrs = cellattr->attrs;
5012 fg = cellattr->fg;
5013 bg = cellattr->bg;
5014 len = MB_PTR2LEN(p);
5015 mch_memmove(mbs, p, len);
5016 mbs[len] = NUL;
5017 p += len;
5018 }
5019 else
5020 {
5021 VTermScreenCell cell;
5022 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5023 break;
5024 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5025 {
5026 if (cell.chars[i] == 0)
5027 break;
5028 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5029 }
5030 mbs[off] = NUL;
5031 width = cell.width;
5032 attrs = cell.attrs;
5033 fg = cell.fg;
5034 bg = cell.bg;
5035 }
5036 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005037 if (dcell == NULL)
5038 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005039 list_append_dict(l, dcell);
5040
5041 dict_add_nr_str(dcell, "chars", 0, mbs);
5042
5043 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5044 fg.red, fg.green, fg.blue);
5045 dict_add_nr_str(dcell, "fg", 0, rgb);
5046 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5047 bg.red, bg.green, bg.blue);
5048 dict_add_nr_str(dcell, "bg", 0, rgb);
5049
5050 dict_add_nr_str(dcell, "attr",
5051 cell2attr(attrs, fg, bg), NULL);
5052 dict_add_nr_str(dcell, "width", width, NULL);
5053
5054 ++pos.col;
5055 if (width == 2)
5056 ++pos.col;
5057 }
5058}
5059
5060/*
5061 * "term_sendkeys(buf, keys)" function
5062 */
5063 void
5064f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5065{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005066 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005067 char_u *msg;
5068 term_T *term;
5069
5070 rettv->v_type = VAR_UNKNOWN;
5071 if (buf == NULL)
5072 return;
5073
5074 msg = get_tv_string_chk(&argvars[1]);
5075 if (msg == NULL)
5076 return;
5077 term = buf->b_term;
5078 if (term->tl_vterm == NULL)
5079 return;
5080
5081 while (*msg != NUL)
5082 {
5083 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005084 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005085 }
5086}
5087
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005088#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5089/*
5090 * "term_getansicolors(buf)" function
5091 */
5092 void
5093f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5094{
5095 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5096 term_T *term;
5097 VTermState *state;
5098 VTermColor color;
5099 char_u hexbuf[10];
5100 int index;
5101 list_T *list;
5102
5103 if (rettv_list_alloc(rettv) == FAIL)
5104 return;
5105
5106 if (buf == NULL)
5107 return;
5108 term = buf->b_term;
5109 if (term->tl_vterm == NULL)
5110 return;
5111
5112 list = rettv->vval.v_list;
5113 state = vterm_obtain_state(term->tl_vterm);
5114 for (index = 0; index < 16; index++)
5115 {
5116 vterm_state_get_palette_color(state, index, &color);
5117 sprintf((char *)hexbuf, "#%02x%02x%02x",
5118 color.red, color.green, color.blue);
5119 if (list_append_string(list, hexbuf, 7) == FAIL)
5120 return;
5121 }
5122}
5123
5124/*
5125 * "term_setansicolors(buf, list)" function
5126 */
5127 void
5128f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5129{
5130 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5131 term_T *term;
5132
5133 if (buf == NULL)
5134 return;
5135 term = buf->b_term;
5136 if (term->tl_vterm == NULL)
5137 return;
5138
5139 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5140 {
5141 EMSG(_(e_listreq));
5142 return;
5143 }
5144
5145 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5146 EMSG(_(e_invarg));
5147}
5148#endif
5149
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005150/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005151 * "term_setrestore(buf, command)" function
5152 */
5153 void
5154f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5155{
5156#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005157 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005158 term_T *term;
5159 char_u *cmd;
5160
5161 if (buf == NULL)
5162 return;
5163 term = buf->b_term;
5164 vim_free(term->tl_command);
5165 cmd = get_tv_string_chk(&argvars[1]);
5166 if (cmd != NULL)
5167 term->tl_command = vim_strsave(cmd);
5168 else
5169 term->tl_command = NULL;
5170#endif
5171}
5172
5173/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005174 * "term_setkill(buf, how)" function
5175 */
5176 void
5177f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5178{
5179 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5180 term_T *term;
5181 char_u *how;
5182
5183 if (buf == NULL)
5184 return;
5185 term = buf->b_term;
5186 vim_free(term->tl_kill);
5187 how = get_tv_string_chk(&argvars[1]);
5188 if (how != NULL)
5189 term->tl_kill = vim_strsave(how);
5190 else
5191 term->tl_kill = NULL;
5192}
5193
5194/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005195 * "term_start(command, options)" function
5196 */
5197 void
5198f_term_start(typval_T *argvars, typval_T *rettv)
5199{
5200 jobopt_T opt;
5201 buf_T *buf;
5202
5203 init_job_options(&opt);
5204 if (argvars[1].v_type != VAR_UNKNOWN
5205 && get_job_options(&argvars[1], &opt,
5206 JO_TIMEOUT_ALL + JO_STOPONEXIT
5207 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5208 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5209 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5210 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005211 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005212 + JO2_NORESTORE + JO2_TERM_KILL
5213 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005214 return;
5215
Bram Moolenaar13568252018-03-16 20:46:58 +01005216 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005217
5218 if (buf != NULL && buf->b_term != NULL)
5219 rettv->vval.v_number = buf->b_fnum;
5220}
5221
5222/*
5223 * "term_wait" function
5224 */
5225 void
5226f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5227{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005228 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005229
5230 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005231 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005232 if (buf->b_term->tl_job == NULL)
5233 {
5234 ch_log(NULL, "term_wait(): no job to wait for");
5235 return;
5236 }
5237 if (buf->b_term->tl_job->jv_channel == NULL)
5238 /* channel is closed, nothing to do */
5239 return;
5240
5241 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005242 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005243 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5244 {
5245 /* The job is dead, keep reading channel I/O until the channel is
5246 * closed. buf->b_term may become NULL if the terminal was closed while
5247 * waiting. */
5248 ch_log(NULL, "term_wait(): waiting for channel to close");
5249 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5250 {
5251 mch_check_messages();
5252 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005253 if (!buf_valid(buf))
5254 /* If the terminal is closed when the channel is closed the
5255 * buffer disappears. */
5256 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005257 ui_delay(10L, FALSE);
5258 }
5259 mch_check_messages();
5260 parse_queued_messages();
5261 }
5262 else
5263 {
5264 long wait = 10L;
5265
5266 mch_check_messages();
5267 parse_queued_messages();
5268
5269 /* Wait for some time for any channel I/O. */
5270 if (argvars[1].v_type != VAR_UNKNOWN)
5271 wait = get_tv_number(&argvars[1]);
5272 ui_delay(wait, TRUE);
5273 mch_check_messages();
5274
5275 /* Flushing messages on channels is hopefully sufficient.
5276 * TODO: is there a better way? */
5277 parse_queued_messages();
5278 }
5279}
5280
5281/*
5282 * Called when a channel has sent all the lines to a terminal.
5283 * Send a CTRL-D to mark the end of the text.
5284 */
5285 void
5286term_send_eof(channel_T *ch)
5287{
5288 term_T *term;
5289
5290 for (term = first_term; term != NULL; term = term->tl_next)
5291 if (term->tl_job == ch->ch_job)
5292 {
5293 if (term->tl_eof_chars != NULL)
5294 {
5295 channel_send(ch, PART_IN, term->tl_eof_chars,
5296 (int)STRLEN(term->tl_eof_chars), NULL);
5297 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5298 }
5299# ifdef WIN3264
5300 else
5301 /* Default: CTRL-D */
5302 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5303# endif
5304 }
5305}
5306
5307# if defined(WIN3264) || defined(PROTO)
5308
5309/**************************************
5310 * 2. MS-Windows implementation.
5311 */
5312
5313# ifndef PROTO
5314
5315#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5316#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005317#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005318
5319void* (*winpty_config_new)(UINT64, void*);
5320void* (*winpty_open)(void*, void*);
5321void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5322BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5323void (*winpty_config_set_mouse_mode)(void*, int);
5324void (*winpty_config_set_initial_size)(void*, int, int);
5325LPCWSTR (*winpty_conin_name)(void*);
5326LPCWSTR (*winpty_conout_name)(void*);
5327LPCWSTR (*winpty_conerr_name)(void*);
5328void (*winpty_free)(void*);
5329void (*winpty_config_free)(void*);
5330void (*winpty_spawn_config_free)(void*);
5331void (*winpty_error_free)(void*);
5332LPCWSTR (*winpty_error_msg)(void*);
5333BOOL (*winpty_set_size)(void*, int, int, void*);
5334HANDLE (*winpty_agent_process)(void*);
5335
5336#define WINPTY_DLL "winpty.dll"
5337
5338static HINSTANCE hWinPtyDLL = NULL;
5339# endif
5340
5341 static int
5342dyn_winpty_init(int verbose)
5343{
5344 int i;
5345 static struct
5346 {
5347 char *name;
5348 FARPROC *ptr;
5349 } winpty_entry[] =
5350 {
5351 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5352 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5353 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5354 {"winpty_config_set_mouse_mode",
5355 (FARPROC*)&winpty_config_set_mouse_mode},
5356 {"winpty_config_set_initial_size",
5357 (FARPROC*)&winpty_config_set_initial_size},
5358 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5359 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5360 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5361 {"winpty_free", (FARPROC*)&winpty_free},
5362 {"winpty_open", (FARPROC*)&winpty_open},
5363 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5364 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5365 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5366 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5367 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5368 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5369 {NULL, NULL}
5370 };
5371
5372 /* No need to initialize twice. */
5373 if (hWinPtyDLL)
5374 return OK;
5375 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5376 * winpty.dll. */
5377 if (*p_winptydll != NUL)
5378 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5379 if (!hWinPtyDLL)
5380 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5381 if (!hWinPtyDLL)
5382 {
5383 if (verbose)
5384 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5385 : (char_u *)WINPTY_DLL);
5386 return FAIL;
5387 }
5388 for (i = 0; winpty_entry[i].name != NULL
5389 && winpty_entry[i].ptr != NULL; ++i)
5390 {
5391 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5392 winpty_entry[i].name)) == NULL)
5393 {
5394 if (verbose)
5395 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5396 return FAIL;
5397 }
5398 }
5399
5400 return OK;
5401}
5402
5403/*
5404 * Create a new terminal of "rows" by "cols" cells.
5405 * Store a reference in "term".
5406 * Return OK or FAIL.
5407 */
5408 static int
5409term_and_job_init(
5410 term_T *term,
5411 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005412 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005413 jobopt_T *opt,
5414 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005415{
5416 WCHAR *cmd_wchar = NULL;
5417 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005418 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005419 channel_T *channel = NULL;
5420 job_T *job = NULL;
5421 DWORD error;
5422 HANDLE jo = NULL;
5423 HANDLE child_process_handle;
5424 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005425 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005426 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005427 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005428 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429
5430 if (dyn_winpty_init(TRUE) == FAIL)
5431 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005432 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5433 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005434
5435 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005436 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005437 cmd = argvar->vval.v_string;
5438 }
5439 else if (argvar->v_type == VAR_LIST)
5440 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005441 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005442 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005443 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005444 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005445 if (cmd == NULL || *cmd == NUL)
5446 {
5447 EMSG(_(e_invarg));
5448 goto failed;
5449 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005450
5451 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005452 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005453 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005454 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005455 if (opt->jo_cwd != NULL)
5456 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005457
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005458 win32_build_env(opt->jo_env, &ga_env, TRUE);
5459 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005461 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5462 if (term->tl_winpty_config == NULL)
5463 goto failed;
5464
5465 winpty_config_set_mouse_mode(term->tl_winpty_config,
5466 WINPTY_MOUSE_MODE_FORCE);
5467 winpty_config_set_initial_size(term->tl_winpty_config,
5468 term->tl_cols, term->tl_rows);
5469 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5470 if (term->tl_winpty == NULL)
5471 goto failed;
5472
5473 spawn_config = winpty_spawn_config_new(
5474 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5475 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5476 NULL,
5477 cmd_wchar,
5478 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005479 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005480 &winpty_err);
5481 if (spawn_config == NULL)
5482 goto failed;
5483
5484 channel = add_channel();
5485 if (channel == NULL)
5486 goto failed;
5487
5488 job = job_alloc();
5489 if (job == NULL)
5490 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005491 if (argvar->v_type == VAR_STRING)
5492 {
5493 int argc;
5494
5495 build_argv_from_string(cmd, &job->jv_argv, &argc);
5496 }
5497 else
5498 {
5499 int argc;
5500
5501 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5502 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005503
5504 if (opt->jo_set & JO_IN_BUF)
5505 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5506
5507 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5508 &child_thread_handle, &error, &winpty_err))
5509 goto failed;
5510
5511 channel_set_pipes(channel,
5512 (sock_T)CreateFileW(
5513 winpty_conin_name(term->tl_winpty),
5514 GENERIC_WRITE, 0, NULL,
5515 OPEN_EXISTING, 0, NULL),
5516 (sock_T)CreateFileW(
5517 winpty_conout_name(term->tl_winpty),
5518 GENERIC_READ, 0, NULL,
5519 OPEN_EXISTING, 0, NULL),
5520 (sock_T)CreateFileW(
5521 winpty_conerr_name(term->tl_winpty),
5522 GENERIC_READ, 0, NULL,
5523 OPEN_EXISTING, 0, NULL));
5524
5525 /* Write lines with CR instead of NL. */
5526 channel->ch_write_text_mode = TRUE;
5527
5528 jo = CreateJobObject(NULL, NULL);
5529 if (jo == NULL)
5530 goto failed;
5531
5532 if (!AssignProcessToJobObject(jo, child_process_handle))
5533 {
5534 /* Failed, switch the way to terminate process with TerminateProcess. */
5535 CloseHandle(jo);
5536 jo = NULL;
5537 }
5538
5539 winpty_spawn_config_free(spawn_config);
5540 vim_free(cmd_wchar);
5541 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005542 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005543
5544 create_vterm(term, term->tl_rows, term->tl_cols);
5545
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005546#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5547 if (opt->jo_set2 & JO2_ANSI_COLORS)
5548 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5549 else
5550 init_vterm_ansi_colors(term->tl_vterm);
5551#endif
5552
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005553 channel_set_job(channel, job, opt);
5554 job_set_options(job, opt);
5555
5556 job->jv_channel = channel;
5557 job->jv_proc_info.hProcess = child_process_handle;
5558 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5559 job->jv_job_object = jo;
5560 job->jv_status = JOB_STARTED;
5561 job->jv_tty_in = utf16_to_enc(
5562 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5563 job->jv_tty_out = utf16_to_enc(
5564 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5565 ++job->jv_refcount;
5566 term->tl_job = job;
5567
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005568 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5569 * open the file here and handle it in. opt->jo_io was changed in
5570 * setup_job_options(), use the original flags here. */
5571 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5572 {
5573 char_u *fname = opt->jo_io_name[PART_OUT];
5574
5575 ch_log(channel, "Opening output file %s", fname);
5576 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5577 if (term->tl_out_fd == NULL)
5578 EMSG2(_(e_notopen), fname);
5579 }
5580
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005581 return OK;
5582
5583failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005584 ga_clear(&ga_cmd);
5585 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005586 vim_free(cmd_wchar);
5587 vim_free(cwd_wchar);
5588 if (spawn_config != NULL)
5589 winpty_spawn_config_free(spawn_config);
5590 if (channel != NULL)
5591 channel_clear(channel);
5592 if (job != NULL)
5593 {
5594 job->jv_channel = NULL;
5595 job_cleanup(job);
5596 }
5597 term->tl_job = NULL;
5598 if (jo != NULL)
5599 CloseHandle(jo);
5600 if (term->tl_winpty != NULL)
5601 winpty_free(term->tl_winpty);
5602 term->tl_winpty = NULL;
5603 if (term->tl_winpty_config != NULL)
5604 winpty_config_free(term->tl_winpty_config);
5605 term->tl_winpty_config = NULL;
5606 if (winpty_err != NULL)
5607 {
5608 char_u *msg = utf16_to_enc(
5609 (short_u *)winpty_error_msg(winpty_err), NULL);
5610
5611 EMSG(msg);
5612 winpty_error_free(winpty_err);
5613 }
5614 return FAIL;
5615}
5616
5617 static int
5618create_pty_only(term_T *term, jobopt_T *options)
5619{
5620 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5621 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5622 char in_name[80], out_name[80];
5623 channel_T *channel = NULL;
5624
5625 create_vterm(term, term->tl_rows, term->tl_cols);
5626
5627 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5628 GetCurrentProcessId(),
5629 curbuf->b_fnum);
5630 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5631 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5632 PIPE_UNLIMITED_INSTANCES,
5633 0, 0, NMPWAIT_NOWAIT, NULL);
5634 if (hPipeIn == INVALID_HANDLE_VALUE)
5635 goto failed;
5636
5637 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5638 GetCurrentProcessId(),
5639 curbuf->b_fnum);
5640 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5641 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5642 PIPE_UNLIMITED_INSTANCES,
5643 0, 0, 0, NULL);
5644 if (hPipeOut == INVALID_HANDLE_VALUE)
5645 goto failed;
5646
5647 ConnectNamedPipe(hPipeIn, NULL);
5648 ConnectNamedPipe(hPipeOut, NULL);
5649
5650 term->tl_job = job_alloc();
5651 if (term->tl_job == NULL)
5652 goto failed;
5653 ++term->tl_job->jv_refcount;
5654
5655 /* behave like the job is already finished */
5656 term->tl_job->jv_status = JOB_FINISHED;
5657
5658 channel = add_channel();
5659 if (channel == NULL)
5660 goto failed;
5661 term->tl_job->jv_channel = channel;
5662 channel->ch_keep_open = TRUE;
5663 channel->ch_named_pipe = TRUE;
5664
5665 channel_set_pipes(channel,
5666 (sock_T)hPipeIn,
5667 (sock_T)hPipeOut,
5668 (sock_T)hPipeOut);
5669 channel_set_job(channel, term->tl_job, options);
5670 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5671 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5672
5673 return OK;
5674
5675failed:
5676 if (hPipeIn != NULL)
5677 CloseHandle(hPipeIn);
5678 if (hPipeOut != NULL)
5679 CloseHandle(hPipeOut);
5680 return FAIL;
5681}
5682
5683/*
5684 * Free the terminal emulator part of "term".
5685 */
5686 static void
5687term_free_vterm(term_T *term)
5688{
5689 if (term->tl_winpty != NULL)
5690 winpty_free(term->tl_winpty);
5691 term->tl_winpty = NULL;
5692 if (term->tl_winpty_config != NULL)
5693 winpty_config_free(term->tl_winpty_config);
5694 term->tl_winpty_config = NULL;
5695 if (term->tl_vterm != NULL)
5696 vterm_free(term->tl_vterm);
5697 term->tl_vterm = NULL;
5698}
5699
5700/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005701 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005702 */
5703 static void
5704term_report_winsize(term_T *term, int rows, int cols)
5705{
5706 if (term->tl_winpty)
5707 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5708}
5709
5710 int
5711terminal_enabled(void)
5712{
5713 return dyn_winpty_init(FALSE) == OK;
5714}
5715
5716# else
5717
5718/**************************************
5719 * 3. Unix-like implementation.
5720 */
5721
5722/*
5723 * Create a new terminal of "rows" by "cols" cells.
5724 * Start job for "cmd".
5725 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005726 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005727 * Return OK or FAIL.
5728 */
5729 static int
5730term_and_job_init(
5731 term_T *term,
5732 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005733 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005734 jobopt_T *opt,
5735 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005736{
5737 create_vterm(term, term->tl_rows, term->tl_cols);
5738
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005739#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5740 if (opt->jo_set2 & JO2_ANSI_COLORS)
5741 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5742 else
5743 init_vterm_ansi_colors(term->tl_vterm);
5744#endif
5745
Bram Moolenaar13568252018-03-16 20:46:58 +01005746 /* This may change a string in "argvar". */
5747 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005748 if (term->tl_job != NULL)
5749 ++term->tl_job->jv_refcount;
5750
5751 return term->tl_job != NULL
5752 && term->tl_job->jv_channel != NULL
5753 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5754}
5755
5756 static int
5757create_pty_only(term_T *term, jobopt_T *opt)
5758{
5759 create_vterm(term, term->tl_rows, term->tl_cols);
5760
5761 term->tl_job = job_alloc();
5762 if (term->tl_job == NULL)
5763 return FAIL;
5764 ++term->tl_job->jv_refcount;
5765
5766 /* behave like the job is already finished */
5767 term->tl_job->jv_status = JOB_FINISHED;
5768
5769 return mch_create_pty_channel(term->tl_job, opt);
5770}
5771
5772/*
5773 * Free the terminal emulator part of "term".
5774 */
5775 static void
5776term_free_vterm(term_T *term)
5777{
5778 if (term->tl_vterm != NULL)
5779 vterm_free(term->tl_vterm);
5780 term->tl_vterm = NULL;
5781}
5782
5783/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005784 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005785 */
5786 static void
5787term_report_winsize(term_T *term, int rows, int cols)
5788{
5789 /* Use an ioctl() to report the new window size to the job. */
5790 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5791 {
5792 int fd = -1;
5793 int part;
5794
5795 for (part = PART_OUT; part < PART_COUNT; ++part)
5796 {
5797 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5798 if (isatty(fd))
5799 break;
5800 }
5801 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5802 mch_signal_job(term->tl_job, (char_u *)"winch");
5803 }
5804}
5805
5806# endif
5807
5808#endif /* FEAT_TERMINAL */