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