blob: 32680620550fe5d85c31321f9284fd89dd46c1a2 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
39 *
40 * TODO:
Bram Moolenaar13568252018-03-16 20:46:58 +010041 * - Add a way to set the 16 ANSI colors, to be used for 'termguicolors' and in
42 * the GUI.
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +020043 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
44 * redirection.
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010045 * - implement term_setsize()
46 * - Copy text in the vterm to the Vim buffer once in a while, so that
47 * completion works.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +010048 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar46359e12017-11-29 22:33:38 +010049 * a job that uses 16 colors while Vim is using > 256.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020050 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
51 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020052 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020053 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
54 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020055 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010056 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020057 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020058 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010059 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 * - add test for giving error for invalid 'termsize' value.
61 * - support minimal size when 'termsize' is "rows*cols".
62 * - support minimal size when 'termsize' is empty?
63 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020064 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020065 * - For the GUI fill termios with default values, perhaps like pangoterm:
66 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
68 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020069 * - add an optional limit for the scrollback size. When reaching it remove
70 * 10% at the start.
71 */
72
73#include "vim.h"
74
75#if defined(FEAT_TERMINAL) || defined(PROTO)
76
77#ifndef MIN
78# define MIN(x,y) ((x) < (y) ? (x) : (y))
79#endif
80#ifndef MAX
81# define MAX(x,y) ((x) > (y) ? (x) : (y))
82#endif
83
84#include "libvterm/include/vterm.h"
85
86/* This is VTermScreenCell without the characters, thus much smaller. */
87typedef struct {
88 VTermScreenCellAttrs attrs;
89 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010090 VTermColor fg;
91 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020092} cellattr_T;
93
94typedef struct sb_line_S {
95 int sb_cols; /* can differ per line */
96 cellattr_T *sb_cells; /* allocated */
97 cellattr_T sb_fill_attr; /* for short line */
98} sb_line_T;
99
100/* typedef term_T in structs.h */
101struct terminal_S {
102 term_T *tl_next;
103
104 VTerm *tl_vterm;
105 job_T *tl_job;
106 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100107#if defined(FEAT_GUI)
108 int tl_system; /* when non-zero used for :!cmd output */
109 int tl_toprow; /* row with first line of system terminal */
110#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200111
112 /* Set when setting the size of a vterm, reset after redrawing. */
113 int tl_vterm_size_changed;
114
115 /* used when tl_job is NULL and only a pty was created */
116 int tl_tty_fd;
117 char_u *tl_tty_in;
118 char_u *tl_tty_out;
119
120 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
121 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100122 int tl_finish;
123#define TL_FINISH_UNSET NUL
124#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
125#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
126#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200127 char_u *tl_opencmd;
128 char_u *tl_eof_chars;
129
130#ifdef WIN3264
131 void *tl_winpty_config;
132 void *tl_winpty;
133#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100134#if defined(FEAT_SESSION)
135 char_u *tl_command;
136#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100137 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200138
139 /* last known vterm size */
140 int tl_rows;
141 int tl_cols;
142 /* vterm size does not follow window size */
143 int tl_rows_fixed;
144 int tl_cols_fixed;
145
146 char_u *tl_title; /* NULL or allocated */
147 char_u *tl_status_text; /* NULL or allocated */
148
149 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200150 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 int tl_dirty_row_end; /* row below last one to update */
152
153 garray_T tl_scrollback;
154 int tl_scrollback_scrolled;
155 cellattr_T tl_default_color;
156
Bram Moolenaard96ff162018-02-18 22:13:29 +0100157 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
158 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
159
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200160 VTermPos tl_cursor_pos;
161 int tl_cursor_visible;
162 int tl_cursor_blink;
163 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
164 char_u *tl_cursor_color; /* NULL or allocated */
165
166 int tl_using_altscreen;
167};
168
169#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
170#define TMODE_LOOP 2 /* CTRL-W N used */
171
172/*
173 * List of all active terminals.
174 */
175static term_T *first_term = NULL;
176
177/* Terminal active in terminal_loop(). */
178static term_T *in_terminal_loop = NULL;
179
180#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
181#define KEY_BUF_LEN 200
182
183/*
184 * Functions with separate implementation for MS-Windows and Unix-like systems.
185 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100186static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187static int create_pty_only(term_T *term, jobopt_T *opt);
188static void term_report_winsize(term_T *term, int rows, int cols);
189static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100190#ifdef FEAT_GUI
191static void update_system_term(term_T *term);
192#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100194/* The character that we know (or assume) that the terminal expects for the
195 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200196static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100198/* "Terminal" highlight group colors. */
199static int term_default_cterm_fg = -1;
200static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200201
Bram Moolenaard317b382018-02-08 22:33:31 +0100202/* Store the last set and the desired cursor properties, so that we only update
203 * them when needed. Doing it unnecessary may result in flicker. */
204static char_u *last_set_cursor_color = (char_u *)"";
205static char_u *desired_cursor_color = (char_u *)"";
206static int last_set_cursor_shape = -1;
207static int desired_cursor_shape = -1;
208static int last_set_cursor_blink = -1;
209static int desired_cursor_blink = -1;
210
211
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200212/**************************************
213 * 1. Generic code for all systems.
214 */
215
216/*
217 * Determine the terminal size from 'termsize' and the current window.
218 * Assumes term->tl_rows and term->tl_cols are zero.
219 */
220 static void
221set_term_and_win_size(term_T *term)
222{
Bram Moolenaar13568252018-03-16 20:46:58 +0100223#ifdef FEAT_GUI
224 if (term->tl_system)
225 {
226 /* Use the whole screen for the system command. However, it will start
227 * at the command line and scroll up as needed, using tl_toprow. */
228 term->tl_rows = Rows;
229 term->tl_cols = Columns;
230 }
231 else
232#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200233 if (*curwin->w_p_tms != NUL)
234 {
235 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
236
237 term->tl_rows = atoi((char *)curwin->w_p_tms);
238 term->tl_cols = atoi((char *)p);
239 }
240 if (term->tl_rows == 0)
241 term->tl_rows = curwin->w_height;
242 else
243 {
244 win_setheight_win(term->tl_rows, curwin);
245 term->tl_rows_fixed = TRUE;
246 }
247 if (term->tl_cols == 0)
248 term->tl_cols = curwin->w_width;
249 else
250 {
251 win_setwidth_win(term->tl_cols, curwin);
252 term->tl_cols_fixed = TRUE;
253 }
254}
255
256/*
257 * Initialize job options for a terminal job.
258 * Caller may overrule some of them.
259 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100260 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200261init_job_options(jobopt_T *opt)
262{
263 clear_job_options(opt);
264
265 opt->jo_mode = MODE_RAW;
266 opt->jo_out_mode = MODE_RAW;
267 opt->jo_err_mode = MODE_RAW;
268 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
269}
270
271/*
272 * Set job options mandatory for a terminal job.
273 */
274 static void
275setup_job_options(jobopt_T *opt, int rows, int cols)
276{
277 if (!(opt->jo_set & JO_OUT_IO))
278 {
279 /* Connect stdout to the terminal. */
280 opt->jo_io[PART_OUT] = JIO_BUFFER;
281 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
282 opt->jo_modifiable[PART_OUT] = 0;
283 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
284 }
285
286 if (!(opt->jo_set & JO_ERR_IO))
287 {
288 /* Connect stderr to the terminal. */
289 opt->jo_io[PART_ERR] = JIO_BUFFER;
290 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
291 opt->jo_modifiable[PART_ERR] = 0;
292 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
293 }
294
295 opt->jo_pty = TRUE;
296 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
297 opt->jo_term_rows = rows;
298 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
299 opt->jo_term_cols = cols;
300}
301
302/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100303 * Close a terminal buffer (and its window). Used when creating the terminal
304 * fails.
305 */
306 static void
307term_close_buffer(buf_T *buf, buf_T *old_curbuf)
308{
309 free_terminal(buf);
310 if (old_curbuf != NULL)
311 {
312 --curbuf->b_nwindows;
313 curbuf = old_curbuf;
314 curwin->w_buffer = curbuf;
315 ++curbuf->b_nwindows;
316 }
317
318 /* Wiping out the buffer will also close the window and call
319 * free_terminal(). */
320 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
321}
322
323/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200324 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100325 * Use either "argvar" or "argv", the other must be NULL.
326 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
327 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200328 * Returns NULL when failed.
329 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100330 buf_T *
331term_start(
332 typval_T *argvar,
333 char **argv,
334 jobopt_T *opt,
335 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200336{
337 exarg_T split_ea;
338 win_T *old_curwin = curwin;
339 term_T *term;
340 buf_T *old_curbuf = NULL;
341 int res;
342 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100343 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344
345 if (check_restricted() || check_secure())
346 return NULL;
347
348 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
349 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
350 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
351 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
352 {
353 EMSG(_(e_invarg));
354 return NULL;
355 }
356
357 term = (term_T *)alloc_clear(sizeof(term_T));
358 if (term == NULL)
359 return NULL;
360 term->tl_dirty_row_end = MAX_ROW;
361 term->tl_cursor_visible = TRUE;
362 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
363 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100364#ifdef FEAT_GUI
365 term->tl_system = (flags & TERM_START_SYSTEM);
366#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
368
369 vim_memset(&split_ea, 0, sizeof(split_ea));
370 if (opt->jo_curwin)
371 {
372 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100373 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200374 {
375 no_write_message();
376 vim_free(term);
377 return NULL;
378 }
379 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100380 ECMD_HIDE
381 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
382 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200383 {
384 vim_free(term);
385 return NULL;
386 }
387 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100388 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200389 {
390 buf_T *buf;
391
392 /* Create a new buffer without a window. Make it the current buffer for
393 * a moment to be able to do the initialisations. */
394 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
395 BLN_NEW | BLN_LISTED);
396 if (buf == NULL || ml_open(buf) == FAIL)
397 {
398 vim_free(term);
399 return NULL;
400 }
401 old_curbuf = curbuf;
402 --curbuf->b_nwindows;
403 curbuf = buf;
404 curwin->w_buffer = buf;
405 ++curbuf->b_nwindows;
406 }
407 else
408 {
409 /* Open a new window or tab. */
410 split_ea.cmdidx = CMD_new;
411 split_ea.cmd = (char_u *)"new";
412 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100413 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414 {
415 split_ea.line2 = opt->jo_term_rows;
416 split_ea.addr_count = 1;
417 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100418 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200419 {
420 split_ea.line2 = opt->jo_term_cols;
421 split_ea.addr_count = 1;
422 }
423
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100424 if (vertical)
425 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200426 ex_splitview(&split_ea);
427 if (curwin == old_curwin)
428 {
429 /* split failed */
430 vim_free(term);
431 return NULL;
432 }
433 }
434 term->tl_buffer = curbuf;
435 curbuf->b_term = term;
436
437 if (!opt->jo_hidden)
438 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100439 /* Only one size was taken care of with :new, do the other one. With
440 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100441 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100443 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200444 win_setwidth(opt->jo_term_cols);
445 }
446
447 /* Link the new terminal in the list of active terminals. */
448 term->tl_next = first_term;
449 first_term = term;
450
451 if (opt->jo_term_name != NULL)
452 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100453 else if (argv != NULL)
454 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200455 else
456 {
457 int i;
458 size_t len;
459 char_u *cmd, *p;
460
461 if (argvar->v_type == VAR_STRING)
462 {
463 cmd = argvar->vval.v_string;
464 if (cmd == NULL)
465 cmd = (char_u *)"";
466 else if (STRCMP(cmd, "NONE") == 0)
467 cmd = (char_u *)"pty";
468 }
469 else if (argvar->v_type != VAR_LIST
470 || argvar->vval.v_list == NULL
471 || argvar->vval.v_list->lv_len < 1
472 || (cmd = get_tv_string_chk(
473 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
474 cmd = (char_u*)"";
475
476 len = STRLEN(cmd) + 10;
477 p = alloc((int)len);
478
479 for (i = 0; p != NULL; ++i)
480 {
481 /* Prepend a ! to the command name to avoid the buffer name equals
482 * the executable, otherwise ":w!" would overwrite it. */
483 if (i == 0)
484 vim_snprintf((char *)p, len, "!%s", cmd);
485 else
486 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
487 if (buflist_findname(p) == NULL)
488 {
489 vim_free(curbuf->b_ffname);
490 curbuf->b_ffname = p;
491 break;
492 }
493 }
494 }
495 curbuf->b_fname = curbuf->b_ffname;
496
497 if (opt->jo_term_opencmd != NULL)
498 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
499
500 if (opt->jo_eof_chars != NULL)
501 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
502
503 set_string_option_direct((char_u *)"buftype", -1,
504 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
505
506 /* Mark the buffer as not modifiable. It can only be made modifiable after
507 * the job finished. */
508 curbuf->b_p_ma = FALSE;
509
510 set_term_and_win_size(term);
511 setup_job_options(opt, term->tl_rows, term->tl_cols);
512
Bram Moolenaar13568252018-03-16 20:46:58 +0100513 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100514 return curbuf;
515
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100516#if defined(FEAT_SESSION)
517 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100518 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100519 {
520 term->tl_command = vim_strsave((char_u *)"NONE");
521 }
522 else if (argvar->v_type == VAR_STRING)
523 {
524 char_u *cmd = argvar->vval.v_string;
525
526 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
527 term->tl_command = vim_strsave(cmd);
528 }
529 else if (argvar->v_type == VAR_LIST
530 && argvar->vval.v_list != NULL
531 && argvar->vval.v_list->lv_len > 0)
532 {
533 garray_T ga;
534 listitem_T *item;
535
536 ga_init2(&ga, 1, 100);
537 for (item = argvar->vval.v_list->lv_first;
538 item != NULL; item = item->li_next)
539 {
540 char_u *s = get_tv_string_chk(&item->li_tv);
541 char_u *p;
542
543 if (s == NULL)
544 break;
545 p = vim_strsave_fnameescape(s, FALSE);
546 if (p == NULL)
547 break;
548 ga_concat(&ga, p);
549 vim_free(p);
550 ga_append(&ga, ' ');
551 }
552 if (item == NULL)
553 {
554 ga_append(&ga, NUL);
555 term->tl_command = ga.ga_data;
556 }
557 else
558 ga_clear(&ga);
559 }
560#endif
561
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100562 if (opt->jo_term_kill != NULL)
563 {
564 char_u *p = skiptowhite(opt->jo_term_kill);
565
566 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
567 }
568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200569 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100570 if (argv == NULL
571 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572 && argvar->vval.v_string != NULL
573 && STRCMP(argvar->vval.v_string, "NONE") == 0)
574 res = create_pty_only(term, opt);
575 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100576 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577
578 newbuf = curbuf;
579 if (res == OK)
580 {
581 /* Get and remember the size we ended up with. Update the pty. */
582 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
583 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100584#ifdef FEAT_GUI
585 if (term->tl_system)
586 {
587 /* display first line below typed command */
588 term->tl_toprow = msg_row + 1;
589 term->tl_dirty_row_end = 0;
590 }
591#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200592
593 /* Make sure we don't get stuck on sending keys to the job, it leads to
594 * a deadlock if the job is waiting for Vim to read. */
595 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
596
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100598 {
599 ++curbuf->b_locked;
600 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
601 --curbuf->b_locked;
602 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100603 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200604 {
605 --curbuf->b_nwindows;
606 curbuf = old_curbuf;
607 curwin->w_buffer = curbuf;
608 ++curbuf->b_nwindows;
609 }
610 }
611 else
612 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100613 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200614 return NULL;
615 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100616
Bram Moolenaar13568252018-03-16 20:46:58 +0100617 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200618 return newbuf;
619}
620
621/*
622 * ":terminal": open a terminal window and execute a job in it.
623 */
624 void
625ex_terminal(exarg_T *eap)
626{
627 typval_T argvar[2];
628 jobopt_T opt;
629 char_u *cmd;
630 char_u *tofree = NULL;
631
632 init_job_options(&opt);
633
634 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100635 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200636 {
637 char_u *p, *ep;
638
639 cmd += 2;
640 p = skiptowhite(cmd);
641 ep = vim_strchr(cmd, '=');
642 if (ep != NULL && ep < p)
643 p = ep;
644
645 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
646 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100647 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
648 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200649 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
650 opt.jo_term_finish = 'o';
651 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
652 opt.jo_curwin = 1;
653 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
654 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100655 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
656 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100657 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
658 && ep != NULL)
659 {
660 opt.jo_set2 |= JO2_TERM_KILL;
661 opt.jo_term_kill = ep + 1;
662 p = skiptowhite(cmd);
663 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200664 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
665 && ep != NULL && isdigit(ep[1]))
666 {
667 opt.jo_set2 |= JO2_TERM_ROWS;
668 opt.jo_term_rows = atoi((char *)ep + 1);
669 p = skiptowhite(cmd);
670 }
671 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
672 && ep != NULL && isdigit(ep[1]))
673 {
674 opt.jo_set2 |= JO2_TERM_COLS;
675 opt.jo_term_cols = atoi((char *)ep + 1);
676 p = skiptowhite(cmd);
677 }
678 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
679 && ep != NULL)
680 {
681 char_u *buf = NULL;
682 char_u *keys;
683
684 p = skiptowhite(cmd);
685 *p = NUL;
686 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
687 opt.jo_set2 |= JO2_EOF_CHARS;
688 opt.jo_eof_chars = vim_strsave(keys);
689 vim_free(buf);
690 *p = ' ';
691 }
692 else
693 {
694 if (*p)
695 *p = NUL;
696 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100697 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200698 }
699 cmd = skipwhite(p);
700 }
701 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100702 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200703 /* Make a copy of 'shell', an autocommand may change the option. */
704 tofree = cmd = vim_strsave(p_sh);
705
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100706 /* default to close when the shell exits */
707 if (opt.jo_term_finish == NUL)
708 opt.jo_term_finish = 'c';
709 }
710
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 if (eap->addr_count > 0)
712 {
713 /* Write lines from current buffer to the job. */
714 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
715 opt.jo_io[PART_IN] = JIO_BUFFER;
716 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
717 opt.jo_in_top = eap->line1;
718 opt.jo_in_bot = eap->line2;
719 }
720
721 argvar[0].v_type = VAR_STRING;
722 argvar[0].vval.v_string = cmd;
723 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100724 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200725 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100726
727theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200728 vim_free(opt.jo_eof_chars);
729}
730
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100731#if defined(FEAT_SESSION) || defined(PROTO)
732/*
733 * Write a :terminal command to the session file to restore the terminal in
734 * window "wp".
735 * Return FAIL if writing fails.
736 */
737 int
738term_write_session(FILE *fd, win_T *wp)
739{
740 term_T *term = wp->w_buffer->b_term;
741
742 /* Create the terminal and run the command. This is not without
743 * risk, but let's assume the user only creates a session when this
744 * will be OK. */
745 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
746 term->tl_cols, term->tl_rows) < 0)
747 return FAIL;
748 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
749 return FAIL;
750
751 return put_eol(fd);
752}
753
754/*
755 * Return TRUE if "buf" has a terminal that should be restored.
756 */
757 int
758term_should_restore(buf_T *buf)
759{
760 term_T *term = buf->b_term;
761
762 return term != NULL && (term->tl_command == NULL
763 || STRCMP(term->tl_command, "NONE") != 0);
764}
765#endif
766
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200767/*
768 * Free the scrollback buffer for "term".
769 */
770 static void
771free_scrollback(term_T *term)
772{
773 int i;
774
775 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
776 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
777 ga_clear(&term->tl_scrollback);
778}
779
780/*
781 * Free a terminal and everything it refers to.
782 * Kills the job if there is one.
783 * Called when wiping out a buffer.
784 */
785 void
786free_terminal(buf_T *buf)
787{
788 term_T *term = buf->b_term;
789 term_T *tp;
790
791 if (term == NULL)
792 return;
793 if (first_term == term)
794 first_term = term->tl_next;
795 else
796 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
797 if (tp->tl_next == term)
798 {
799 tp->tl_next = term->tl_next;
800 break;
801 }
802
803 if (term->tl_job != NULL)
804 {
805 if (term->tl_job->jv_status != JOB_ENDED
806 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100807 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200808 job_stop(term->tl_job, NULL, "kill");
809 job_unref(term->tl_job);
810 }
811
812 free_scrollback(term);
813
814 term_free_vterm(term);
815 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100816#ifdef FEAT_SESSION
817 vim_free(term->tl_command);
818#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100819 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200820 vim_free(term->tl_status_text);
821 vim_free(term->tl_opencmd);
822 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100823 if (desired_cursor_color == term->tl_cursor_color)
824 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200825 vim_free(term->tl_cursor_color);
826 vim_free(term);
827 buf->b_term = NULL;
828 if (in_terminal_loop == term)
829 in_terminal_loop = NULL;
830}
831
832/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100833 * Get the part that is connected to the tty. Normally this is PART_IN, but
834 * when writing buffer lines to the job it can be another. This makes it
835 * possible to do "1,5term vim -".
836 */
837 static ch_part_T
838get_tty_part(term_T *term)
839{
840#ifdef UNIX
841 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
842 int i;
843
844 for (i = 0; i < 3; ++i)
845 {
846 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
847
848 if (isatty(fd))
849 return parts[i];
850 }
851#endif
852 return PART_IN;
853}
854
855/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200856 * Write job output "msg[len]" to the vterm.
857 */
858 static void
859term_write_job_output(term_T *term, char_u *msg, size_t len)
860{
861 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100862 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200863
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100864 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200865
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100866 /* flush vterm buffer when vterm responded to control sequence */
867 if (prevlen != vterm_output_get_buffer_current(vterm))
868 {
869 char buf[KEY_BUF_LEN];
870 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
871
872 if (curlen > 0)
873 channel_send(term->tl_job->jv_channel, get_tty_part(term),
874 (char_u *)buf, (int)curlen, NULL);
875 }
876
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200877 /* this invokes the damage callbacks */
878 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
879}
880
881 static void
882update_cursor(term_T *term, int redraw)
883{
884 if (term->tl_normal_mode)
885 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100886#ifdef FEAT_GUI
887 if (term->tl_system)
888 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
889 term->tl_cursor_pos.col);
890 else
891#endif
892 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200893 if (redraw)
894 {
895 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
896 cursor_on();
897 out_flush();
898#ifdef FEAT_GUI
899 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100900 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100902 gui_mch_flush();
903 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200904#endif
905 }
906}
907
908/*
909 * Invoked when "msg" output from a job was received. Write it to the terminal
910 * of "buffer".
911 */
912 void
913write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
914{
915 size_t len = STRLEN(msg);
916 term_T *term = buffer->b_term;
917
918 if (term->tl_vterm == NULL)
919 {
920 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
921 return;
922 }
923 ch_log(channel, "writing %d bytes to terminal", (int)len);
924 term_write_job_output(term, msg, len);
925
Bram Moolenaar13568252018-03-16 20:46:58 +0100926#ifdef FEAT_GUI
927 if (term->tl_system)
928 {
929 /* show system output, scrolling up the screen as needed */
930 update_system_term(term);
931 update_cursor(term, TRUE);
932 }
933 else
934#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200935 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
936 * contents, thus no screen update is needed. */
937 if (!term->tl_normal_mode)
938 {
939 /* TODO: only update once in a while. */
940 ch_log(term->tl_job->jv_channel, "updating screen");
941 if (buffer == curbuf)
942 {
943 update_screen(0);
944 update_cursor(term, TRUE);
945 }
946 else
947 redraw_after_callback(TRUE);
948 }
949}
950
951/*
952 * Send a mouse position and click to the vterm
953 */
954 static int
955term_send_mouse(VTerm *vterm, int button, int pressed)
956{
957 VTermModifier mod = VTERM_MOD_NONE;
958
959 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200960 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100961 if (button != 0)
962 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200963 return TRUE;
964}
965
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100966static int enter_mouse_col = -1;
967static int enter_mouse_row = -1;
968
969/*
970 * Handle a mouse click, drag or release.
971 * Return TRUE when a mouse event is sent to the terminal.
972 */
973 static int
974term_mouse_click(VTerm *vterm, int key)
975{
976#if defined(FEAT_CLIPBOARD)
977 /* For modeless selection mouse drag and release events are ignored, unless
978 * they are preceded with a mouse down event */
979 static int ignore_drag_release = TRUE;
980 VTermMouseState mouse_state;
981
982 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
983 if (mouse_state.flags == 0)
984 {
985 /* Terminal is not using the mouse, use modeless selection. */
986 switch (key)
987 {
988 case K_LEFTDRAG:
989 case K_LEFTRELEASE:
990 case K_RIGHTDRAG:
991 case K_RIGHTRELEASE:
992 /* Ignore drag and release events when the button-down wasn't
993 * seen before. */
994 if (ignore_drag_release)
995 {
996 int save_mouse_col, save_mouse_row;
997
998 if (enter_mouse_col < 0)
999 break;
1000
1001 /* mouse click in the window gave us focus, handle that
1002 * click now */
1003 save_mouse_col = mouse_col;
1004 save_mouse_row = mouse_row;
1005 mouse_col = enter_mouse_col;
1006 mouse_row = enter_mouse_row;
1007 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1008 mouse_col = save_mouse_col;
1009 mouse_row = save_mouse_row;
1010 }
1011 /* FALLTHROUGH */
1012 case K_LEFTMOUSE:
1013 case K_RIGHTMOUSE:
1014 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1015 ignore_drag_release = TRUE;
1016 else
1017 ignore_drag_release = FALSE;
1018 /* Should we call mouse_has() here? */
1019 if (clip_star.available)
1020 {
1021 int button, is_click, is_drag;
1022
1023 button = get_mouse_button(KEY2TERMCAP1(key),
1024 &is_click, &is_drag);
1025 if (mouse_model_popup() && button == MOUSE_LEFT
1026 && (mod_mask & MOD_MASK_SHIFT))
1027 {
1028 /* Translate shift-left to right button. */
1029 button = MOUSE_RIGHT;
1030 mod_mask &= ~MOD_MASK_SHIFT;
1031 }
1032 clip_modeless(button, is_click, is_drag);
1033 }
1034 break;
1035
1036 case K_MIDDLEMOUSE:
1037 if (clip_star.available)
1038 insert_reg('*', TRUE);
1039 break;
1040 }
1041 enter_mouse_col = -1;
1042 return FALSE;
1043 }
1044#endif
1045 enter_mouse_col = -1;
1046
1047 switch (key)
1048 {
1049 case K_LEFTMOUSE:
1050 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1051 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1052 case K_LEFTRELEASE:
1053 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1054 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1055 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1056 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1057 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1058 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1059 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1060 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1061 }
1062 return TRUE;
1063}
1064
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001065/*
1066 * Convert typed key "c" into bytes to send to the job.
1067 * Return the number of bytes in "buf".
1068 */
1069 static int
1070term_convert_key(term_T *term, int c, char *buf)
1071{
1072 VTerm *vterm = term->tl_vterm;
1073 VTermKey key = VTERM_KEY_NONE;
1074 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001075 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001076
1077 switch (c)
1078 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001079 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1080
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001081 /* don't use VTERM_KEY_BACKSPACE, it always
1082 * becomes 0x7f DEL */
1083 case K_BS: c = term_backspace_char; break;
1084
1085 case ESC: key = VTERM_KEY_ESCAPE; break;
1086 case K_DEL: key = VTERM_KEY_DEL; break;
1087 case K_DOWN: key = VTERM_KEY_DOWN; break;
1088 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1089 key = VTERM_KEY_DOWN; break;
1090 case K_END: key = VTERM_KEY_END; break;
1091 case K_S_END: mod = VTERM_MOD_SHIFT;
1092 key = VTERM_KEY_END; break;
1093 case K_C_END: mod = VTERM_MOD_CTRL;
1094 key = VTERM_KEY_END; break;
1095 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1096 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1097 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1098 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1099 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1100 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1101 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1102 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1103 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1104 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1105 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1106 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1107 case K_HOME: key = VTERM_KEY_HOME; break;
1108 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1109 key = VTERM_KEY_HOME; break;
1110 case K_C_HOME: mod = VTERM_MOD_CTRL;
1111 key = VTERM_KEY_HOME; break;
1112 case K_INS: key = VTERM_KEY_INS; break;
1113 case K_K0: key = VTERM_KEY_KP_0; break;
1114 case K_K1: key = VTERM_KEY_KP_1; break;
1115 case K_K2: key = VTERM_KEY_KP_2; break;
1116 case K_K3: key = VTERM_KEY_KP_3; break;
1117 case K_K4: key = VTERM_KEY_KP_4; break;
1118 case K_K5: key = VTERM_KEY_KP_5; break;
1119 case K_K6: key = VTERM_KEY_KP_6; break;
1120 case K_K7: key = VTERM_KEY_KP_7; break;
1121 case K_K8: key = VTERM_KEY_KP_8; break;
1122 case K_K9: key = VTERM_KEY_KP_9; break;
1123 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1124 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1125 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1126 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1127 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1128 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1129 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1130 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1131 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1132 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1133 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1134 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1135 case K_LEFT: key = VTERM_KEY_LEFT; break;
1136 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1137 key = VTERM_KEY_LEFT; break;
1138 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1139 key = VTERM_KEY_LEFT; break;
1140 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1141 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1142 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1143 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1144 key = VTERM_KEY_RIGHT; break;
1145 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1146 key = VTERM_KEY_RIGHT; break;
1147 case K_UP: key = VTERM_KEY_UP; break;
1148 case K_S_UP: mod = VTERM_MOD_SHIFT;
1149 key = VTERM_KEY_UP; break;
1150 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001151 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1152 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001153
Bram Moolenaara42ad572017-11-16 13:08:04 +01001154 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1155 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001156 case K_MOUSELEFT: /* TODO */ return 0;
1157 case K_MOUSERIGHT: /* TODO */ return 0;
1158
1159 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001160 case K_LEFTMOUSE_NM:
1161 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001162 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001163 case K_LEFTRELEASE_NM:
1164 case K_MOUSEMOVE:
1165 case K_MIDDLEMOUSE:
1166 case K_MIDDLEDRAG:
1167 case K_MIDDLERELEASE:
1168 case K_RIGHTMOUSE:
1169 case K_RIGHTDRAG:
1170 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1171 return 0;
1172 other = TRUE;
1173 break;
1174
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 case K_X1MOUSE: /* TODO */ return 0;
1176 case K_X1DRAG: /* TODO */ return 0;
1177 case K_X1RELEASE: /* TODO */ return 0;
1178 case K_X2MOUSE: /* TODO */ return 0;
1179 case K_X2DRAG: /* TODO */ return 0;
1180 case K_X2RELEASE: /* TODO */ return 0;
1181
1182 case K_IGNORE: return 0;
1183 case K_NOP: return 0;
1184 case K_UNDO: return 0;
1185 case K_HELP: return 0;
1186 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1187 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1188 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1189 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1190 case K_SELECT: return 0;
1191#ifdef FEAT_GUI
1192 case K_VER_SCROLLBAR: return 0;
1193 case K_HOR_SCROLLBAR: return 0;
1194#endif
1195#ifdef FEAT_GUI_TABLINE
1196 case K_TABLINE: return 0;
1197 case K_TABMENU: return 0;
1198#endif
1199#ifdef FEAT_NETBEANS_INTG
1200 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1201#endif
1202#ifdef FEAT_DND
1203 case K_DROP: return 0;
1204#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001205 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001206 case K_PS: vterm_keyboard_start_paste(vterm);
1207 other = TRUE;
1208 break;
1209 case K_PE: vterm_keyboard_end_paste(vterm);
1210 other = TRUE;
1211 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001212 }
1213
1214 /*
1215 * Convert special keys to vterm keys:
1216 * - Write keys to vterm: vterm_keyboard_key()
1217 * - Write output to channel.
1218 * TODO: use mod_mask
1219 */
1220 if (key != VTERM_KEY_NONE)
1221 /* Special key, let vterm convert it. */
1222 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001223 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001224 /* Normal character, let vterm convert it. */
1225 vterm_keyboard_unichar(vterm, c, mod);
1226
1227 /* Read back the converted escape sequence. */
1228 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1229}
1230
1231/*
1232 * Return TRUE if the job for "term" is still running.
1233 */
1234 int
1235term_job_running(term_T *term)
1236{
1237 /* Also consider the job finished when the channel is closed, to avoid a
1238 * race condition when updating the title. */
1239 return term != NULL
1240 && term->tl_job != NULL
1241 && channel_is_open(term->tl_job->jv_channel)
1242 && (term->tl_job->jv_status == JOB_STARTED
1243 || term->tl_job->jv_channel->ch_keep_open);
1244}
1245
1246/*
1247 * Return TRUE if "term" has an active channel and used ":term NONE".
1248 */
1249 int
1250term_none_open(term_T *term)
1251{
1252 /* Also consider the job finished when the channel is closed, to avoid a
1253 * race condition when updating the title. */
1254 return term != NULL
1255 && term->tl_job != NULL
1256 && channel_is_open(term->tl_job->jv_channel)
1257 && term->tl_job->jv_channel->ch_keep_open;
1258}
1259
1260/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001261 * Used when exiting: kill the job in "buf" if so desired.
1262 * Return OK when the job finished.
1263 * Return FAIL when the job is still running.
1264 */
1265 int
1266term_try_stop_job(buf_T *buf)
1267{
1268 int count;
1269 char *how = (char *)buf->b_term->tl_kill;
1270
1271#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1272 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1273 {
1274 char_u buff[DIALOG_MSG_SIZE];
1275 int ret;
1276
1277 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1278 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1279 if (ret == VIM_YES)
1280 how = "kill";
1281 else if (ret == VIM_CANCEL)
1282 return FAIL;
1283 }
1284#endif
1285 if (how == NULL || *how == NUL)
1286 return FAIL;
1287
1288 job_stop(buf->b_term->tl_job, NULL, how);
1289
1290 /* wait for up to a second for the job to die */
1291 for (count = 0; count < 100; ++count)
1292 {
1293 /* buffer, terminal and job may be cleaned up while waiting */
1294 if (!buf_valid(buf)
1295 || buf->b_term == NULL
1296 || buf->b_term->tl_job == NULL)
1297 return OK;
1298
1299 /* call job_status() to update jv_status */
1300 job_status(buf->b_term->tl_job);
1301 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1302 return OK;
1303 ui_delay(10L, FALSE);
1304 mch_check_messages();
1305 parse_queued_messages();
1306 }
1307 return FAIL;
1308}
1309
1310/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001311 * Add the last line of the scrollback buffer to the buffer in the window.
1312 */
1313 static void
1314add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1315{
1316 buf_T *buf = term->tl_buffer;
1317 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1318 linenr_T lnum = buf->b_ml.ml_line_count;
1319
1320#ifdef WIN3264
1321 if (!enc_utf8 && enc_codepage > 0)
1322 {
1323 WCHAR *ret = NULL;
1324 int length = 0;
1325
1326 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1327 &ret, &length);
1328 if (ret != NULL)
1329 {
1330 WideCharToMultiByte_alloc(enc_codepage, 0,
1331 ret, length, (char **)&text, &len, 0, 0);
1332 vim_free(ret);
1333 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1334 vim_free(text);
1335 }
1336 }
1337 else
1338#endif
1339 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1340 if (empty)
1341 {
1342 /* Delete the empty line that was in the empty buffer. */
1343 curbuf = buf;
1344 ml_delete(1, FALSE);
1345 curbuf = curwin->w_buffer;
1346 }
1347}
1348
1349 static void
1350cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1351{
1352 attr->width = cell->width;
1353 attr->attrs = cell->attrs;
1354 attr->fg = cell->fg;
1355 attr->bg = cell->bg;
1356}
1357
1358 static int
1359equal_celattr(cellattr_T *a, cellattr_T *b)
1360{
1361 /* Comparing the colors should be sufficient. */
1362 return a->fg.red == b->fg.red
1363 && a->fg.green == b->fg.green
1364 && a->fg.blue == b->fg.blue
1365 && a->bg.red == b->bg.red
1366 && a->bg.green == b->bg.green
1367 && a->bg.blue == b->bg.blue;
1368}
1369
Bram Moolenaard96ff162018-02-18 22:13:29 +01001370/*
1371 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1372 * line at this position. Otherwise at the end.
1373 */
1374 static int
1375add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1376{
1377 if (ga_grow(&term->tl_scrollback, 1) == OK)
1378 {
1379 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1380 + term->tl_scrollback.ga_len;
1381
1382 if (lnum > 0)
1383 {
1384 int i;
1385
1386 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1387 {
1388 *line = *(line - 1);
1389 --line;
1390 }
1391 }
1392 line->sb_cols = 0;
1393 line->sb_cells = NULL;
1394 line->sb_fill_attr = *fill_attr;
1395 ++term->tl_scrollback.ga_len;
1396 return OK;
1397 }
1398 return FALSE;
1399}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001400
1401/*
1402 * Add the current lines of the terminal to scrollback and to the buffer.
1403 * Called after the job has ended and when switching to Terminal-Normal mode.
1404 */
1405 static void
1406move_terminal_to_buffer(term_T *term)
1407{
1408 win_T *wp;
1409 int len;
1410 int lines_skipped = 0;
1411 VTermPos pos;
1412 VTermScreenCell cell;
1413 cellattr_T fill_attr, new_fill_attr;
1414 cellattr_T *p;
1415 VTermScreen *screen;
1416
1417 if (term->tl_vterm == NULL)
1418 return;
1419 screen = vterm_obtain_screen(term->tl_vterm);
1420 fill_attr = new_fill_attr = term->tl_default_color;
1421
1422 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1423 {
1424 len = 0;
1425 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1426 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1427 && cell.chars[0] != NUL)
1428 {
1429 len = pos.col + 1;
1430 new_fill_attr = term->tl_default_color;
1431 }
1432 else
1433 /* Assume the last attr is the filler attr. */
1434 cell2cellattr(&cell, &new_fill_attr);
1435
1436 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1437 ++lines_skipped;
1438 else
1439 {
1440 while (lines_skipped > 0)
1441 {
1442 /* Line was skipped, add an empty line. */
1443 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001444 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001445 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001446 }
1447
1448 if (len == 0)
1449 p = NULL;
1450 else
1451 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1452 if ((p != NULL || len == 0)
1453 && ga_grow(&term->tl_scrollback, 1) == OK)
1454 {
1455 garray_T ga;
1456 int width;
1457 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1458 + term->tl_scrollback.ga_len;
1459
1460 ga_init2(&ga, 1, 100);
1461 for (pos.col = 0; pos.col < len; pos.col += width)
1462 {
1463 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1464 {
1465 width = 1;
1466 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1467 if (ga_grow(&ga, 1) == OK)
1468 ga.ga_len += utf_char2bytes(' ',
1469 (char_u *)ga.ga_data + ga.ga_len);
1470 }
1471 else
1472 {
1473 width = cell.width;
1474
1475 cell2cellattr(&cell, &p[pos.col]);
1476
1477 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1478 {
1479 int i;
1480 int c;
1481
1482 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1483 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1484 (char_u *)ga.ga_data + ga.ga_len);
1485 }
1486 }
1487 }
1488 line->sb_cols = len;
1489 line->sb_cells = p;
1490 line->sb_fill_attr = new_fill_attr;
1491 fill_attr = new_fill_attr;
1492 ++term->tl_scrollback.ga_len;
1493
1494 if (ga_grow(&ga, 1) == FAIL)
1495 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1496 else
1497 {
1498 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1499 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1500 }
1501 ga_clear(&ga);
1502 }
1503 else
1504 vim_free(p);
1505 }
1506 }
1507
1508 /* Obtain the current background color. */
1509 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1510 &term->tl_default_color.fg, &term->tl_default_color.bg);
1511
1512 FOR_ALL_WINDOWS(wp)
1513 {
1514 if (wp->w_buffer == term->tl_buffer)
1515 {
1516 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1517 wp->w_cursor.col = 0;
1518 wp->w_valid = 0;
1519 if (wp->w_cursor.lnum >= wp->w_height)
1520 {
1521 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1522
1523 if (wp->w_topline < min_topline)
1524 wp->w_topline = min_topline;
1525 }
1526 redraw_win_later(wp, NOT_VALID);
1527 }
1528 }
1529}
1530
1531 static void
1532set_terminal_mode(term_T *term, int normal_mode)
1533{
1534 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001535 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001536 if (term->tl_buffer == curbuf)
1537 maketitle();
1538}
1539
1540/*
1541 * Called after the job if finished and Terminal mode is not active:
1542 * Move the vterm contents into the scrollback buffer and free the vterm.
1543 */
1544 static void
1545cleanup_vterm(term_T *term)
1546{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001547 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001548 move_terminal_to_buffer(term);
1549 term_free_vterm(term);
1550 set_terminal_mode(term, FALSE);
1551}
1552
1553/*
1554 * Switch from Terminal-Job mode to Terminal-Normal mode.
1555 * Suspends updating the terminal window.
1556 */
1557 static void
1558term_enter_normal_mode(void)
1559{
1560 term_T *term = curbuf->b_term;
1561
1562 /* Append the current terminal contents to the buffer. */
1563 move_terminal_to_buffer(term);
1564
1565 set_terminal_mode(term, TRUE);
1566
1567 /* Move the window cursor to the position of the cursor in the
1568 * terminal. */
1569 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1570 + term->tl_cursor_pos.row + 1;
1571 check_cursor();
1572 coladvance(term->tl_cursor_pos.col);
1573
1574 /* Display the same lines as in the terminal. */
1575 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1576}
1577
1578/*
1579 * Returns TRUE if the current window contains a terminal and we are in
1580 * Terminal-Normal mode.
1581 */
1582 int
1583term_in_normal_mode(void)
1584{
1585 term_T *term = curbuf->b_term;
1586
1587 return term != NULL && term->tl_normal_mode;
1588}
1589
1590/*
1591 * Switch from Terminal-Normal mode to Terminal-Job mode.
1592 * Restores updating the terminal window.
1593 */
1594 void
1595term_enter_job_mode()
1596{
1597 term_T *term = curbuf->b_term;
1598 sb_line_T *line;
1599 garray_T *gap;
1600
1601 /* Remove the terminal contents from the scrollback and the buffer. */
1602 gap = &term->tl_scrollback;
1603 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1604 && gap->ga_len > 0)
1605 {
1606 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1607 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1608 vim_free(line->sb_cells);
1609 --gap->ga_len;
1610 }
1611 check_cursor();
1612
1613 set_terminal_mode(term, FALSE);
1614
1615 if (term->tl_channel_closed)
1616 cleanup_vterm(term);
1617 redraw_buf_and_status_later(curbuf, NOT_VALID);
1618}
1619
1620/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001621 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001622 * Note: while waiting a terminal may be closed and freed if the channel is
1623 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 */
1625 static int
1626term_vgetc()
1627{
1628 int c;
1629 int save_State = State;
1630
1631 State = TERMINAL;
1632 got_int = FALSE;
1633#ifdef WIN3264
1634 ctrl_break_was_pressed = FALSE;
1635#endif
1636 c = vgetc();
1637 got_int = FALSE;
1638 State = save_State;
1639 return c;
1640}
1641
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001642static int mouse_was_outside = FALSE;
1643
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001645 * Send keys to terminal.
1646 * Return FAIL when the key needs to be handled in Normal mode.
1647 * Return OK when the key was dropped or sent to the terminal.
1648 */
1649 int
1650send_keys_to_term(term_T *term, int c, int typed)
1651{
1652 char msg[KEY_BUF_LEN];
1653 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654 int dragging_outside = FALSE;
1655
1656 /* Catch keys that need to be handled as in Normal mode. */
1657 switch (c)
1658 {
1659 case NUL:
1660 case K_ZERO:
1661 if (typed)
1662 stuffcharReadbuff(c);
1663 return FAIL;
1664
1665 case K_IGNORE:
1666 return FAIL;
1667
1668 case K_LEFTDRAG:
1669 case K_MIDDLEDRAG:
1670 case K_RIGHTDRAG:
1671 case K_X1DRAG:
1672 case K_X2DRAG:
1673 dragging_outside = mouse_was_outside;
1674 /* FALLTHROUGH */
1675 case K_LEFTMOUSE:
1676 case K_LEFTMOUSE_NM:
1677 case K_LEFTRELEASE:
1678 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001679 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001680 case K_MIDDLEMOUSE:
1681 case K_MIDDLERELEASE:
1682 case K_RIGHTMOUSE:
1683 case K_RIGHTRELEASE:
1684 case K_X1MOUSE:
1685 case K_X1RELEASE:
1686 case K_X2MOUSE:
1687 case K_X2RELEASE:
1688
1689 case K_MOUSEUP:
1690 case K_MOUSEDOWN:
1691 case K_MOUSELEFT:
1692 case K_MOUSERIGHT:
1693 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001694 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001695 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001696 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 || dragging_outside)
1698 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001699 /* click or scroll outside the current window or on status line
1700 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001701 if (typed)
1702 {
1703 stuffcharReadbuff(c);
1704 mouse_was_outside = TRUE;
1705 }
1706 return FAIL;
1707 }
1708 }
1709 if (typed)
1710 mouse_was_outside = FALSE;
1711
1712 /* Convert the typed key to a sequence of bytes for the job. */
1713 len = term_convert_key(term, c, msg);
1714 if (len > 0)
1715 /* TODO: if FAIL is returned, stop? */
1716 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1717 (char_u *)msg, (int)len, NULL);
1718
1719 return OK;
1720}
1721
1722 static void
1723position_cursor(win_T *wp, VTermPos *pos)
1724{
1725 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1726 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1727 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1728}
1729
1730/*
1731 * Handle CTRL-W "": send register contents to the job.
1732 */
1733 static void
1734term_paste_register(int prev_c UNUSED)
1735{
1736 int c;
1737 list_T *l;
1738 listitem_T *item;
1739 long reglen = 0;
1740 int type;
1741
1742#ifdef FEAT_CMDL_INFO
1743 if (add_to_showcmd(prev_c))
1744 if (add_to_showcmd('"'))
1745 out_flush();
1746#endif
1747 c = term_vgetc();
1748#ifdef FEAT_CMDL_INFO
1749 clear_showcmd();
1750#endif
1751 if (!term_use_loop())
1752 /* job finished while waiting for a character */
1753 return;
1754
1755 /* CTRL-W "= prompt for expression to evaluate. */
1756 if (c == '=' && get_expr_register() != '=')
1757 return;
1758 if (!term_use_loop())
1759 /* job finished while waiting for a character */
1760 return;
1761
1762 l = (list_T *)get_reg_contents(c, GREG_LIST);
1763 if (l != NULL)
1764 {
1765 type = get_reg_type(c, &reglen);
1766 for (item = l->lv_first; item != NULL; item = item->li_next)
1767 {
1768 char_u *s = get_tv_string(&item->li_tv);
1769#ifdef WIN3264
1770 char_u *tmp = s;
1771
1772 if (!enc_utf8 && enc_codepage > 0)
1773 {
1774 WCHAR *ret = NULL;
1775 int length = 0;
1776
1777 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1778 (int)STRLEN(s), &ret, &length);
1779 if (ret != NULL)
1780 {
1781 WideCharToMultiByte_alloc(CP_UTF8, 0,
1782 ret, length, (char **)&s, &length, 0, 0);
1783 vim_free(ret);
1784 }
1785 }
1786#endif
1787 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1788 s, (int)STRLEN(s), NULL);
1789#ifdef WIN3264
1790 if (tmp != s)
1791 vim_free(s);
1792#endif
1793
1794 if (item->li_next != NULL || type == MLINE)
1795 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1796 (char_u *)"\r", 1, NULL);
1797 }
1798 list_free(l);
1799 }
1800}
1801
1802#if defined(FEAT_GUI) || defined(PROTO)
1803/*
1804 * Return TRUE when the cursor of the terminal should be displayed.
1805 */
1806 int
1807terminal_is_active()
1808{
1809 return in_terminal_loop != NULL;
1810}
1811
1812 cursorentry_T *
1813term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1814{
1815 term_T *term = in_terminal_loop;
1816 static cursorentry_T entry;
1817
1818 vim_memset(&entry, 0, sizeof(entry));
1819 entry.shape = entry.mshape =
1820 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1821 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1822 SHAPE_BLOCK;
1823 entry.percentage = 20;
1824 if (term->tl_cursor_blink)
1825 {
1826 entry.blinkwait = 700;
1827 entry.blinkon = 400;
1828 entry.blinkoff = 250;
1829 }
1830 *fg = gui.back_pixel;
1831 if (term->tl_cursor_color == NULL)
1832 *bg = gui.norm_pixel;
1833 else
1834 *bg = color_name2handle(term->tl_cursor_color);
1835 entry.name = "n";
1836 entry.used_for = SHAPE_CURSOR;
1837
1838 return &entry;
1839}
1840#endif
1841
Bram Moolenaard317b382018-02-08 22:33:31 +01001842 static void
1843may_output_cursor_props(void)
1844{
1845 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1846 || last_set_cursor_shape != desired_cursor_shape
1847 || last_set_cursor_blink != desired_cursor_blink)
1848 {
1849 last_set_cursor_color = desired_cursor_color;
1850 last_set_cursor_shape = desired_cursor_shape;
1851 last_set_cursor_blink = desired_cursor_blink;
1852 term_cursor_color(desired_cursor_color);
1853 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1854 /* this will restore the initial cursor style, if possible */
1855 ui_cursor_shape_forced(TRUE);
1856 else
1857 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1858 }
1859}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860
Bram Moolenaard317b382018-02-08 22:33:31 +01001861/*
1862 * Set the cursor color and shape, if not last set to these.
1863 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001864 static void
1865may_set_cursor_props(term_T *term)
1866{
1867#ifdef FEAT_GUI
1868 /* For the GUI the cursor properties are obtained with
1869 * term_get_cursor_shape(). */
1870 if (gui.in_use)
1871 return;
1872#endif
1873 if (in_terminal_loop == term)
1874 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001876 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001877 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001878 desired_cursor_color = (char_u *)"";
1879 desired_cursor_shape = term->tl_cursor_shape;
1880 desired_cursor_blink = term->tl_cursor_blink;
1881 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001882 }
1883}
1884
Bram Moolenaard317b382018-02-08 22:33:31 +01001885/*
1886 * Reset the desired cursor properties and restore them when needed.
1887 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001888 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001889prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001890{
1891#ifdef FEAT_GUI
1892 if (gui.in_use)
1893 return;
1894#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001895 desired_cursor_color = (char_u *)"";
1896 desired_cursor_shape = -1;
1897 desired_cursor_blink = -1;
1898 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899}
1900
1901/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001902 * Called when entering a window with the mouse. If this is a terminal window
1903 * we may want to change state.
1904 */
1905 void
1906term_win_entered()
1907{
1908 term_T *term = curbuf->b_term;
1909
1910 if (term != NULL)
1911 {
1912 if (term_use_loop())
1913 {
1914 reset_VIsual_and_resel();
1915 if (State & INSERT)
1916 stop_insert_mode = TRUE;
1917 }
1918 mouse_was_outside = FALSE;
1919 enter_mouse_col = mouse_col;
1920 enter_mouse_row = mouse_row;
1921 }
1922}
1923
1924/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001925 * Returns TRUE if the current window contains a terminal and we are sending
1926 * keys to the job.
1927 */
1928 int
1929term_use_loop(void)
1930{
1931 term_T *term = curbuf->b_term;
1932
1933 return term != NULL
1934 && !term->tl_normal_mode
1935 && term->tl_vterm != NULL
1936 && term_job_running(term);
1937}
1938
1939/*
1940 * Wait for input and send it to the job.
1941 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1942 * when there is no more typahead.
1943 * Return when the start of a CTRL-W command is typed or anything else that
1944 * should be handled as a Normal mode command.
1945 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1946 * the terminal was closed.
1947 */
1948 int
1949terminal_loop(int blocking)
1950{
1951 int c;
1952 int termkey = 0;
1953 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001954#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001955 int tty_fd = curbuf->b_term->tl_job->jv_channel
1956 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001957#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001958 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959
1960 /* Remember the terminal we are sending keys to. However, the terminal
1961 * might be closed while waiting for a character, e.g. typing "exit" in a
1962 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1963 * stored reference. */
1964 in_terminal_loop = curbuf->b_term;
1965
1966 if (*curwin->w_p_tk != NUL)
1967 termkey = string_to_key(curwin->w_p_tk, TRUE);
1968 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1969 may_set_cursor_props(curbuf->b_term);
1970
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001971 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001972 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001973#ifdef FEAT_GUI
1974 if (!curbuf->b_term->tl_system)
1975#endif
1976 /* TODO: skip screen update when handling a sequence of keys. */
1977 /* Repeat redrawing in case a message is received while redrawing.
1978 */
1979 while (must_redraw != 0)
1980 if (update_screen(0) == FAIL)
1981 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001982 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001983 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984
1985 c = term_vgetc();
1986 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001987 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001988 /* Job finished while waiting for a character. Push back the
1989 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001990 if (c != K_IGNORE)
1991 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001993 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 if (c == K_IGNORE)
1995 continue;
1996
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001997#ifdef UNIX
1998 /*
1999 * The shell or another program may change the tty settings. Getting
2000 * them for every typed character is a bit of overhead, but it's needed
2001 * for the first character typed, e.g. when Vim starts in a shell.
2002 */
2003 if (isatty(tty_fd))
2004 {
2005 ttyinfo_T info;
2006
2007 /* Get the current backspace character of the pty. */
2008 if (get_tty_info(tty_fd, &info) == OK)
2009 term_backspace_char = info.backspace;
2010 }
2011#endif
2012
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002013#ifdef WIN3264
2014 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2015 * Use CTRL-BREAK to kill the job. */
2016 if (ctrl_break_was_pressed)
2017 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2018#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002019 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2020 * Not in a system terminal. */
2021 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2022#ifdef FEAT_GUI
2023 && !curbuf->b_term->tl_system
2024#endif
2025 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 {
2027 int prev_c = c;
2028
2029#ifdef FEAT_CMDL_INFO
2030 if (add_to_showcmd(c))
2031 out_flush();
2032#endif
2033 c = term_vgetc();
2034#ifdef FEAT_CMDL_INFO
2035 clear_showcmd();
2036#endif
2037 if (!term_use_loop())
2038 /* job finished while waiting for a character */
2039 break;
2040
2041 if (prev_c == Ctrl_BSL)
2042 {
2043 if (c == Ctrl_N)
2044 {
2045 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2046 term_enter_normal_mode();
2047 ret = FAIL;
2048 goto theend;
2049 }
2050 /* Send both keys to the terminal. */
2051 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2052 }
2053 else if (c == Ctrl_C)
2054 {
2055 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2056 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2057 }
2058 else if (termkey == 0 && c == '.')
2059 {
2060 /* "CTRL-W .": send CTRL-W to the job */
2061 c = Ctrl_W;
2062 }
2063 else if (c == 'N')
2064 {
2065 /* CTRL-W N : go to Terminal-Normal mode. */
2066 term_enter_normal_mode();
2067 ret = FAIL;
2068 goto theend;
2069 }
2070 else if (c == '"')
2071 {
2072 term_paste_register(prev_c);
2073 continue;
2074 }
2075 else if (termkey == 0 || c != termkey)
2076 {
2077 stuffcharReadbuff(Ctrl_W);
2078 stuffcharReadbuff(c);
2079 ret = OK;
2080 goto theend;
2081 }
2082 }
2083# ifdef WIN3264
2084 if (!enc_utf8 && has_mbyte && c >= 0x80)
2085 {
2086 WCHAR wc;
2087 char_u mb[3];
2088
2089 mb[0] = (unsigned)c >> 8;
2090 mb[1] = c;
2091 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2092 c = wc;
2093 }
2094# endif
2095 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2096 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002097 if (c == K_MOUSEMOVE)
2098 /* We are sure to come back here, don't reset the cursor color
2099 * and shape to avoid flickering. */
2100 restore_cursor = FALSE;
2101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 ret = OK;
2103 goto theend;
2104 }
2105 }
2106 ret = FAIL;
2107
2108theend:
2109 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002110 if (restore_cursor)
2111 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112 return ret;
2113}
2114
2115/*
2116 * Called when a job has finished.
2117 * This updates the title and status, but does not close the vterm, because
2118 * there might still be pending output in the channel.
2119 */
2120 void
2121term_job_ended(job_T *job)
2122{
2123 term_T *term;
2124 int did_one = FALSE;
2125
2126 for (term = first_term; term != NULL; term = term->tl_next)
2127 if (term->tl_job == job)
2128 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002129 VIM_CLEAR(term->tl_title);
2130 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 redraw_buf_and_status_later(term->tl_buffer, VALID);
2132 did_one = TRUE;
2133 }
2134 if (did_one)
2135 redraw_statuslines();
2136 if (curbuf->b_term != NULL)
2137 {
2138 if (curbuf->b_term->tl_job == job)
2139 maketitle();
2140 update_cursor(curbuf->b_term, TRUE);
2141 }
2142}
2143
2144 static void
2145may_toggle_cursor(term_T *term)
2146{
2147 if (in_terminal_loop == term)
2148 {
2149 if (term->tl_cursor_visible)
2150 cursor_on();
2151 else
2152 cursor_off();
2153 }
2154}
2155
2156/*
2157 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002158 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 */
2160 static int
2161color2index(VTermColor *color, int fg, int *boldp)
2162{
2163 int red = color->red;
2164 int blue = color->blue;
2165 int green = color->green;
2166
Bram Moolenaar46359e12017-11-29 22:33:38 +01002167 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002169 /* First 16 colors and default: use the ANSI index, because these
2170 * colors can be redefined. */
2171 if (t_colors >= 16)
2172 return color->ansi_index;
2173 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002175 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002176 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002177 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2178 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2179 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
2180 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
2181 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2182 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2183 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2184 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2185 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2186 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2187 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2188 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2189 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2190 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2191 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002192 }
2193 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002194
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002195 if (t_colors >= 256)
2196 {
2197 if (red == blue && red == green)
2198 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002199 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002201 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2202 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2203 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 int i;
2205
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002206 if (red < 5)
2207 return 17; /* 00/00/00 */
2208 if (red > 245) /* ff/ff/ff */
2209 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210 for (i = 0; i < 23; ++i)
2211 if (red < cutoff[i])
2212 return i + 233;
2213 return 256;
2214 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002215 {
2216 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2217 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002218
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002219 /* 216-color cube */
2220 for (ri = 0; ri < 5; ++ri)
2221 if (red < cutoff[ri])
2222 break;
2223 for (gi = 0; gi < 5; ++gi)
2224 if (green < cutoff[gi])
2225 break;
2226 for (bi = 0; bi < 5; ++bi)
2227 if (blue < cutoff[bi])
2228 break;
2229 return 17 + ri * 36 + gi * 6 + bi;
2230 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002231 }
2232 return 0;
2233}
2234
2235/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002236 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237 */
2238 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002239vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002240{
2241 int attr = 0;
2242
2243 if (cellattrs.bold)
2244 attr |= HL_BOLD;
2245 if (cellattrs.underline)
2246 attr |= HL_UNDERLINE;
2247 if (cellattrs.italic)
2248 attr |= HL_ITALIC;
2249 if (cellattrs.strike)
2250 attr |= HL_STRIKETHROUGH;
2251 if (cellattrs.reverse)
2252 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002253 return attr;
2254}
2255
2256/*
2257 * Store Vterm attributes in "cell" from highlight flags.
2258 */
2259 static void
2260hl2vtermAttr(int attr, cellattr_T *cell)
2261{
2262 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2263 if (attr & HL_BOLD)
2264 cell->attrs.bold = 1;
2265 if (attr & HL_UNDERLINE)
2266 cell->attrs.underline = 1;
2267 if (attr & HL_ITALIC)
2268 cell->attrs.italic = 1;
2269 if (attr & HL_STRIKETHROUGH)
2270 cell->attrs.strike = 1;
2271 if (attr & HL_INVERSE)
2272 cell->attrs.reverse = 1;
2273}
2274
2275/*
2276 * Convert the attributes of a vterm cell into an attribute index.
2277 */
2278 static int
2279cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2280{
2281 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002282
2283#ifdef FEAT_GUI
2284 if (gui.in_use)
2285 {
2286 guicolor_T fg, bg;
2287
2288 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2289 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2290 return get_gui_attr_idx(attr, fg, bg);
2291 }
2292 else
2293#endif
2294#ifdef FEAT_TERMGUICOLORS
2295 if (p_tgc)
2296 {
2297 guicolor_T fg, bg;
2298
2299 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2300 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2301
2302 return get_tgc_attr_idx(attr, fg, bg);
2303 }
2304 else
2305#endif
2306 {
2307 int bold = MAYBE;
2308 int fg = color2index(&cellfg, TRUE, &bold);
2309 int bg = color2index(&cellbg, FALSE, &bold);
2310
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002311 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002312 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002313 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002314 if (fg == 0 && term_default_cterm_fg >= 0)
2315 fg = term_default_cterm_fg + 1;
2316 if (bg == 0 && term_default_cterm_bg >= 0)
2317 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002318 }
2319
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 /* with 8 colors set the bold attribute to get a bright foreground */
2321 if (bold == TRUE)
2322 attr |= HL_BOLD;
2323 return get_cterm_attr_idx(attr, fg, bg);
2324 }
2325 return 0;
2326}
2327
2328 static int
2329handle_damage(VTermRect rect, void *user)
2330{
2331 term_T *term = (term_T *)user;
2332
2333 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2334 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2335 redraw_buf_later(term->tl_buffer, NOT_VALID);
2336 return 1;
2337}
2338
2339 static int
2340handle_moverect(VTermRect dest, VTermRect src, void *user)
2341{
2342 term_T *term = (term_T *)user;
2343
2344 /* Scrolling up is done much more efficiently by deleting lines instead of
2345 * redrawing the text. */
2346 if (dest.start_col == src.start_col
2347 && dest.end_col == src.end_col
2348 && dest.start_row < src.start_row)
2349 {
2350 win_T *wp;
2351 VTermColor fg, bg;
2352 VTermScreenCellAttrs attr;
2353 int clear_attr;
2354
2355 /* Set the color to clear lines with. */
2356 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2357 &fg, &bg);
2358 vim_memset(&attr, 0, sizeof(attr));
2359 clear_attr = cell2attr(attr, fg, bg);
2360
2361 FOR_ALL_WINDOWS(wp)
2362 {
2363 if (wp->w_buffer == term->tl_buffer)
2364 win_del_lines(wp, dest.start_row,
2365 src.start_row - dest.start_row, FALSE, FALSE,
2366 clear_attr);
2367 }
2368 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002369
2370 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2371 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 redraw_buf_later(term->tl_buffer, NOT_VALID);
2374 return 1;
2375}
2376
2377 static int
2378handle_movecursor(
2379 VTermPos pos,
2380 VTermPos oldpos UNUSED,
2381 int visible,
2382 void *user)
2383{
2384 term_T *term = (term_T *)user;
2385 win_T *wp;
2386
2387 term->tl_cursor_pos = pos;
2388 term->tl_cursor_visible = visible;
2389
2390 FOR_ALL_WINDOWS(wp)
2391 {
2392 if (wp->w_buffer == term->tl_buffer)
2393 position_cursor(wp, &pos);
2394 }
2395 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2396 {
2397 may_toggle_cursor(term);
2398 update_cursor(term, term->tl_cursor_visible);
2399 }
2400
2401 return 1;
2402}
2403
2404 static int
2405handle_settermprop(
2406 VTermProp prop,
2407 VTermValue *value,
2408 void *user)
2409{
2410 term_T *term = (term_T *)user;
2411
2412 switch (prop)
2413 {
2414 case VTERM_PROP_TITLE:
2415 vim_free(term->tl_title);
2416 /* a blank title isn't useful, make it empty, so that "running" is
2417 * displayed */
2418 if (*skipwhite((char_u *)value->string) == NUL)
2419 term->tl_title = NULL;
2420#ifdef WIN3264
2421 else if (!enc_utf8 && enc_codepage > 0)
2422 {
2423 WCHAR *ret = NULL;
2424 int length = 0;
2425
2426 MultiByteToWideChar_alloc(CP_UTF8, 0,
2427 (char*)value->string, (int)STRLEN(value->string),
2428 &ret, &length);
2429 if (ret != NULL)
2430 {
2431 WideCharToMultiByte_alloc(enc_codepage, 0,
2432 ret, length, (char**)&term->tl_title,
2433 &length, 0, 0);
2434 vim_free(ret);
2435 }
2436 }
2437#endif
2438 else
2439 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002440 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441 if (term == curbuf->b_term)
2442 maketitle();
2443 break;
2444
2445 case VTERM_PROP_CURSORVISIBLE:
2446 term->tl_cursor_visible = value->boolean;
2447 may_toggle_cursor(term);
2448 out_flush();
2449 break;
2450
2451 case VTERM_PROP_CURSORBLINK:
2452 term->tl_cursor_blink = value->boolean;
2453 may_set_cursor_props(term);
2454 break;
2455
2456 case VTERM_PROP_CURSORSHAPE:
2457 term->tl_cursor_shape = value->number;
2458 may_set_cursor_props(term);
2459 break;
2460
2461 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002462 if (desired_cursor_color == term->tl_cursor_color)
2463 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 vim_free(term->tl_cursor_color);
2465 if (*value->string == NUL)
2466 term->tl_cursor_color = NULL;
2467 else
2468 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2469 may_set_cursor_props(term);
2470 break;
2471
2472 case VTERM_PROP_ALTSCREEN:
2473 /* TODO: do anything else? */
2474 term->tl_using_altscreen = value->boolean;
2475 break;
2476
2477 default:
2478 break;
2479 }
2480 /* Always return 1, otherwise vterm doesn't store the value internally. */
2481 return 1;
2482}
2483
2484/*
2485 * The job running in the terminal resized the terminal.
2486 */
2487 static int
2488handle_resize(int rows, int cols, void *user)
2489{
2490 term_T *term = (term_T *)user;
2491 win_T *wp;
2492
2493 term->tl_rows = rows;
2494 term->tl_cols = cols;
2495 if (term->tl_vterm_size_changed)
2496 /* Size was set by vterm_set_size(), don't set the window size. */
2497 term->tl_vterm_size_changed = FALSE;
2498 else
2499 {
2500 FOR_ALL_WINDOWS(wp)
2501 {
2502 if (wp->w_buffer == term->tl_buffer)
2503 {
2504 win_setheight_win(rows, wp);
2505 win_setwidth_win(cols, wp);
2506 }
2507 }
2508 redraw_buf_later(term->tl_buffer, NOT_VALID);
2509 }
2510 return 1;
2511}
2512
2513/*
2514 * Handle a line that is pushed off the top of the screen.
2515 */
2516 static int
2517handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2518{
2519 term_T *term = (term_T *)user;
2520
2521 /* TODO: Limit the number of lines that are stored. */
2522 if (ga_grow(&term->tl_scrollback, 1) == OK)
2523 {
2524 cellattr_T *p = NULL;
2525 int len = 0;
2526 int i;
2527 int c;
2528 int col;
2529 sb_line_T *line;
2530 garray_T ga;
2531 cellattr_T fill_attr = term->tl_default_color;
2532
2533 /* do not store empty cells at the end */
2534 for (i = 0; i < cols; ++i)
2535 if (cells[i].chars[0] != 0)
2536 len = i + 1;
2537 else
2538 cell2cellattr(&cells[i], &fill_attr);
2539
2540 ga_init2(&ga, 1, 100);
2541 if (len > 0)
2542 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2543 if (p != NULL)
2544 {
2545 for (col = 0; col < len; col += cells[col].width)
2546 {
2547 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2548 {
2549 ga.ga_len = 0;
2550 break;
2551 }
2552 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2553 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2554 (char_u *)ga.ga_data + ga.ga_len);
2555 cell2cellattr(&cells[col], &p[col]);
2556 }
2557 }
2558 if (ga_grow(&ga, 1) == FAIL)
2559 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2560 else
2561 {
2562 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2563 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2564 }
2565 ga_clear(&ga);
2566
2567 line = (sb_line_T *)term->tl_scrollback.ga_data
2568 + term->tl_scrollback.ga_len;
2569 line->sb_cols = len;
2570 line->sb_cells = p;
2571 line->sb_fill_attr = fill_attr;
2572 ++term->tl_scrollback.ga_len;
2573 ++term->tl_scrollback_scrolled;
2574 }
2575 return 0; /* ignored */
2576}
2577
2578static VTermScreenCallbacks screen_callbacks = {
2579 handle_damage, /* damage */
2580 handle_moverect, /* moverect */
2581 handle_movecursor, /* movecursor */
2582 handle_settermprop, /* settermprop */
2583 NULL, /* bell */
2584 handle_resize, /* resize */
2585 handle_pushline, /* sb_pushline */
2586 NULL /* sb_popline */
2587};
2588
2589/*
2590 * Called when a channel has been closed.
2591 * If this was a channel for a terminal window then finish it up.
2592 */
2593 void
2594term_channel_closed(channel_T *ch)
2595{
2596 term_T *term;
2597 int did_one = FALSE;
2598
2599 for (term = first_term; term != NULL; term = term->tl_next)
2600 if (term->tl_job == ch->ch_job)
2601 {
2602 term->tl_channel_closed = TRUE;
2603 did_one = TRUE;
2604
Bram Moolenaard23a8232018-02-10 18:45:26 +01002605 VIM_CLEAR(term->tl_title);
2606 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607
2608 /* Unless in Terminal-Normal mode: clear the vterm. */
2609 if (!term->tl_normal_mode)
2610 {
2611 int fnum = term->tl_buffer->b_fnum;
2612
2613 cleanup_vterm(term);
2614
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002615 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002616 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002617 aco_save_T aco;
2618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 /* ++close or term_finish == "close" */
2620 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002621 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002622 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002623 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 break;
2625 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002626 if (term->tl_finish == TL_FINISH_OPEN
2627 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 {
2629 char buf[50];
2630
2631 /* TODO: use term_opencmd */
2632 ch_log(NULL, "terminal job finished, opening window");
2633 vim_snprintf(buf, sizeof(buf),
2634 term->tl_opencmd == NULL
2635 ? "botright sbuf %d"
2636 : (char *)term->tl_opencmd, fnum);
2637 do_cmdline_cmd((char_u *)buf);
2638 }
2639 else
2640 ch_log(NULL, "terminal job finished");
2641 }
2642
2643 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2644 }
2645 if (did_one)
2646 {
2647 redraw_statuslines();
2648
2649 /* Need to break out of vgetc(). */
2650 ins_char_typebuf(K_IGNORE);
2651 typebuf_was_filled = TRUE;
2652
2653 term = curbuf->b_term;
2654 if (term != NULL)
2655 {
2656 if (term->tl_job == ch->ch_job)
2657 maketitle();
2658 update_cursor(term, term->tl_cursor_visible);
2659 }
2660 }
2661}
2662
2663/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002664 * Fill one screen line from a line of the terminal.
2665 * Advances "pos" to past the last column.
2666 */
2667 static void
2668term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2669{
2670 int off = screen_get_current_line_off();
2671
2672 for (pos->col = 0; pos->col < max_col; )
2673 {
2674 VTermScreenCell cell;
2675 int c;
2676
2677 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2678 vim_memset(&cell, 0, sizeof(cell));
2679
2680 c = cell.chars[0];
2681 if (c == NUL)
2682 {
2683 ScreenLines[off] = ' ';
2684 if (enc_utf8)
2685 ScreenLinesUC[off] = NUL;
2686 }
2687 else
2688 {
2689 if (enc_utf8)
2690 {
2691 int i;
2692
2693 /* composing chars */
2694 for (i = 0; i < Screen_mco
2695 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2696 {
2697 ScreenLinesC[i][off] = cell.chars[i + 1];
2698 if (cell.chars[i + 1] == 0)
2699 break;
2700 }
2701 if (c >= 0x80 || (Screen_mco > 0
2702 && ScreenLinesC[0][off] != 0))
2703 {
2704 ScreenLines[off] = ' ';
2705 ScreenLinesUC[off] = c;
2706 }
2707 else
2708 {
2709 ScreenLines[off] = c;
2710 ScreenLinesUC[off] = NUL;
2711 }
2712 }
2713#ifdef WIN3264
2714 else if (has_mbyte && c >= 0x80)
2715 {
2716 char_u mb[MB_MAXBYTES+1];
2717 WCHAR wc = c;
2718
2719 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2720 (char*)mb, 2, 0, 0) > 1)
2721 {
2722 ScreenLines[off] = mb[0];
2723 ScreenLines[off + 1] = mb[1];
2724 cell.width = mb_ptr2cells(mb);
2725 }
2726 else
2727 ScreenLines[off] = c;
2728 }
2729#endif
2730 else
2731 ScreenLines[off] = c;
2732 }
2733 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2734
2735 ++pos->col;
2736 ++off;
2737 if (cell.width == 2)
2738 {
2739 if (enc_utf8)
2740 ScreenLinesUC[off] = NUL;
2741
2742 /* don't set the second byte to NUL for a DBCS encoding, it
2743 * has been set above */
2744 if (enc_utf8 || !has_mbyte)
2745 ScreenLines[off] = NUL;
2746
2747 ++pos->col;
2748 ++off;
2749 }
2750 }
2751}
2752
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002753#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002754 static void
2755update_system_term(term_T *term)
2756{
2757 VTermPos pos;
2758 VTermScreen *screen;
2759
2760 if (term->tl_vterm == NULL)
2761 return;
2762 screen = vterm_obtain_screen(term->tl_vterm);
2763
2764 /* Scroll up to make more room for terminal lines if needed. */
2765 while (term->tl_toprow > 0
2766 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2767 {
2768 int save_p_more = p_more;
2769
2770 p_more = FALSE;
2771 msg_row = Rows - 1;
2772 msg_puts((char_u *)"\n");
2773 p_more = save_p_more;
2774 --term->tl_toprow;
2775 }
2776
2777 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2778 && pos.row < Rows; ++pos.row)
2779 {
2780 if (pos.row < term->tl_rows)
2781 {
2782 int max_col = MIN(Columns, term->tl_cols);
2783
2784 term_line2screenline(screen, &pos, max_col);
2785 }
2786 else
2787 pos.col = 0;
2788
2789 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2790 }
2791
2792 term->tl_dirty_row_start = MAX_ROW;
2793 term->tl_dirty_row_end = 0;
2794 update_cursor(term, TRUE);
2795}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002796#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002797
2798/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 * Called to update a window that contains an active terminal.
2800 * Returns FAIL when there is no terminal running in this window or in
2801 * Terminal-Normal mode.
2802 */
2803 int
2804term_update_window(win_T *wp)
2805{
2806 term_T *term = wp->w_buffer->b_term;
2807 VTerm *vterm;
2808 VTermScreen *screen;
2809 VTermState *state;
2810 VTermPos pos;
2811
2812 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2813 return FAIL;
2814
2815 vterm = term->tl_vterm;
2816 screen = vterm_obtain_screen(vterm);
2817 state = vterm_obtain_state(vterm);
2818
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002819 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002820 {
2821 term->tl_dirty_row_start = 0;
2822 term->tl_dirty_row_end = MAX_ROW;
2823 }
2824
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002825 /*
2826 * If the window was resized a redraw will be triggered and we get here.
2827 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2828 */
2829 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2830 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2831 {
2832 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2833 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2834 win_T *twp;
2835
2836 FOR_ALL_WINDOWS(twp)
2837 {
2838 /* When more than one window shows the same terminal, use the
2839 * smallest size. */
2840 if (twp->w_buffer == term->tl_buffer)
2841 {
2842 if (!term->tl_rows_fixed && rows > twp->w_height)
2843 rows = twp->w_height;
2844 if (!term->tl_cols_fixed && cols > twp->w_width)
2845 cols = twp->w_width;
2846 }
2847 }
2848
2849 term->tl_vterm_size_changed = TRUE;
2850 vterm_set_size(vterm, rows, cols);
2851 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2852 rows);
2853 term_report_winsize(term, rows, cols);
2854 }
2855
2856 /* The cursor may have been moved when resizing. */
2857 vterm_state_get_cursorpos(state, &pos);
2858 position_cursor(wp, &pos);
2859
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002860 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2861 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002863 if (pos.row < term->tl_rows)
2864 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002865 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002866
Bram Moolenaar13568252018-03-16 20:46:58 +01002867 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 }
2869 else
2870 pos.col = 0;
2871
Bram Moolenaarf118d482018-03-13 13:14:00 +01002872 screen_line(wp->w_winrow + pos.row
2873#ifdef FEAT_MENU
2874 + winbar_height(wp)
2875#endif
2876 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002878 term->tl_dirty_row_start = MAX_ROW;
2879 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880
2881 return OK;
2882}
2883
2884/*
2885 * Return TRUE if "wp" is a terminal window where the job has finished.
2886 */
2887 int
2888term_is_finished(buf_T *buf)
2889{
2890 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2891}
2892
2893/*
2894 * Return TRUE if "wp" is a terminal window where the job has finished or we
2895 * are in Terminal-Normal mode, thus we show the buffer contents.
2896 */
2897 int
2898term_show_buffer(buf_T *buf)
2899{
2900 term_T *term = buf->b_term;
2901
2902 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2903}
2904
2905/*
2906 * The current buffer is going to be changed. If there is terminal
2907 * highlighting remove it now.
2908 */
2909 void
2910term_change_in_curbuf(void)
2911{
2912 term_T *term = curbuf->b_term;
2913
2914 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2915 {
2916 free_scrollback(term);
2917 redraw_buf_later(term->tl_buffer, NOT_VALID);
2918
2919 /* The buffer is now like a normal buffer, it cannot be easily
2920 * abandoned when changed. */
2921 set_string_option_direct((char_u *)"buftype", -1,
2922 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2923 }
2924}
2925
2926/*
2927 * Get the screen attribute for a position in the buffer.
2928 * Use a negative "col" to get the filler background color.
2929 */
2930 int
2931term_get_attr(buf_T *buf, linenr_T lnum, int col)
2932{
2933 term_T *term = buf->b_term;
2934 sb_line_T *line;
2935 cellattr_T *cellattr;
2936
2937 if (lnum > term->tl_scrollback.ga_len)
2938 cellattr = &term->tl_default_color;
2939 else
2940 {
2941 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2942 if (col < 0 || col >= line->sb_cols)
2943 cellattr = &line->sb_fill_attr;
2944 else
2945 cellattr = line->sb_cells + col;
2946 }
2947 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2948}
2949
2950static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002951 { 0, 0, 0, 1}, /* black */
2952 {224, 0, 0, 2}, /* dark red */
2953 { 0, 224, 0, 3}, /* dark green */
2954 {224, 224, 0, 4}, /* dark yellow / brown */
2955 { 0, 0, 224, 5}, /* dark blue */
2956 {224, 0, 224, 6}, /* dark magenta */
2957 { 0, 224, 224, 7}, /* dark cyan */
2958 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959
Bram Moolenaar46359e12017-11-29 22:33:38 +01002960 {128, 128, 128, 9}, /* dark grey */
2961 {255, 64, 64, 10}, /* light red */
2962 { 64, 255, 64, 11}, /* light green */
2963 {255, 255, 64, 12}, /* yellow */
2964 { 64, 64, 255, 13}, /* light blue */
2965 {255, 64, 255, 14}, /* light magenta */
2966 { 64, 255, 255, 15}, /* light cyan */
2967 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968};
2969
2970static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002971 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002972};
2973
2974static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002975 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2976 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977};
2978
2979/*
2980 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002981 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 */
2983 static void
2984cterm_color2rgb(int nr, VTermColor *rgb)
2985{
2986 int idx;
2987
2988 if (nr < 16)
2989 {
2990 *rgb = ansi_table[nr];
2991 }
2992 else if (nr < 232)
2993 {
2994 /* 216 color cube */
2995 idx = nr - 16;
2996 rgb->blue = cube_value[idx % 6];
2997 rgb->green = cube_value[idx / 6 % 6];
2998 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002999 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 }
3001 else if (nr < 256)
3002 {
3003 /* 24 grey scale ramp */
3004 idx = nr - 232;
3005 rgb->blue = grey_ramp[idx];
3006 rgb->green = grey_ramp[idx];
3007 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003008 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009 }
3010}
3011
3012/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003013 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 */
3015 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003016init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 VTermColor *fg, *bg;
3019 int fgval, bgval;
3020 int id;
3021
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003022 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3023 term->tl_default_color.width = 1;
3024 fg = &term->tl_default_color.fg;
3025 bg = &term->tl_default_color.bg;
3026
3027 /* Vterm uses a default black background. Set it to white when
3028 * 'background' is "light". */
3029 if (*p_bg == 'l')
3030 {
3031 fgval = 0;
3032 bgval = 255;
3033 }
3034 else
3035 {
3036 fgval = 255;
3037 bgval = 0;
3038 }
3039 fg->red = fg->green = fg->blue = fgval;
3040 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003041 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042
3043 /* The "Terminal" highlight group overrules the defaults. */
3044 id = syn_name2id((char_u *)"Terminal");
3045
Bram Moolenaar46359e12017-11-29 22:33:38 +01003046 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3048 if (0
3049# ifdef FEAT_GUI
3050 || gui.in_use
3051# endif
3052# ifdef FEAT_TERMGUICOLORS
3053 || p_tgc
3054# endif
3055 )
3056 {
3057 guicolor_T fg_rgb = INVALCOLOR;
3058 guicolor_T bg_rgb = INVALCOLOR;
3059
3060 if (id != 0)
3061 syn_id2colors(id, &fg_rgb, &bg_rgb);
3062
3063# ifdef FEAT_GUI
3064 if (gui.in_use)
3065 {
3066 if (fg_rgb == INVALCOLOR)
3067 fg_rgb = gui.norm_pixel;
3068 if (bg_rgb == INVALCOLOR)
3069 bg_rgb = gui.back_pixel;
3070 }
3071# ifdef FEAT_TERMGUICOLORS
3072 else
3073# endif
3074# endif
3075# ifdef FEAT_TERMGUICOLORS
3076 {
3077 if (fg_rgb == INVALCOLOR)
3078 fg_rgb = cterm_normal_fg_gui_color;
3079 if (bg_rgb == INVALCOLOR)
3080 bg_rgb = cterm_normal_bg_gui_color;
3081 }
3082# endif
3083 if (fg_rgb != INVALCOLOR)
3084 {
3085 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3086
3087 fg->red = (unsigned)(rgb >> 16);
3088 fg->green = (unsigned)(rgb >> 8) & 255;
3089 fg->blue = (unsigned)rgb & 255;
3090 }
3091 if (bg_rgb != INVALCOLOR)
3092 {
3093 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3094
3095 bg->red = (unsigned)(rgb >> 16);
3096 bg->green = (unsigned)(rgb >> 8) & 255;
3097 bg->blue = (unsigned)rgb & 255;
3098 }
3099 }
3100 else
3101#endif
3102 if (id != 0 && t_colors >= 16)
3103 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003104 if (term_default_cterm_fg >= 0)
3105 cterm_color2rgb(term_default_cterm_fg, fg);
3106 if (term_default_cterm_bg >= 0)
3107 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 else
3110 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003111#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003113#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003114
3115 /* In an MS-Windows console we know the normal colors. */
3116 if (cterm_normal_fg_color > 0)
3117 {
3118 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003119# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 tmp = fg->red;
3121 fg->red = fg->blue;
3122 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003123# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003125# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003126 else
3127 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003128# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 if (cterm_normal_bg_color > 0)
3131 {
3132 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003133# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134 tmp = bg->red;
3135 bg->red = bg->blue;
3136 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003137# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003139# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003140 else
3141 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003142# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003143 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003144}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145
Bram Moolenaar52acb112018-03-18 19:20:22 +01003146/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003147 * Handles a "drop" command from the job in the terminal.
3148 * "item" is the file name, "item->li_next" may have options.
3149 */
3150 static void
3151handle_drop_command(listitem_T *item)
3152{
3153 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003154 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003155 int bufnr;
3156 win_T *wp;
3157 tabpage_T *tp;
3158 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003159 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003160
3161 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3162 FOR_ALL_TAB_WINDOWS(tp, wp)
3163 {
3164 if (wp->w_buffer->b_fnum == bufnr)
3165 {
3166 /* buffer is in a window already, go there */
3167 goto_tabpage_win(tp, wp);
3168 return;
3169 }
3170 }
3171
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003172 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003173
3174 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3175 && opt_item->li_tv.vval.v_dict != NULL)
3176 {
3177 dict_T *dict = opt_item->li_tv.vval.v_dict;
3178 char_u *p;
3179
3180 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3181 if (p == NULL)
3182 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3183 if (p != NULL)
3184 {
3185 if (check_ff_value(p) == FAIL)
3186 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3187 else
3188 ea.force_ff = *p;
3189 }
3190 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3191 if (p == NULL)
3192 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3193 if (p != NULL)
3194 {
3195 ea.cmd = alloc((int)STRLEN(p) + 10);
3196 if (ea.cmd != NULL)
3197 {
3198 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3199 ea.force_enc = 11;
3200 tofree = ea.cmd;
3201 }
3202 }
3203
3204 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3205 if (p != NULL)
3206 get_bad_opt(p, &ea);
3207
3208 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3209 ea.force_bin = FORCE_BIN;
3210 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3211 ea.force_bin = FORCE_BIN;
3212 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3213 ea.force_bin = FORCE_NOBIN;
3214 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3215 ea.force_bin = FORCE_NOBIN;
3216 }
3217
3218 /* open in new window, like ":split fname" */
3219 if (ea.cmd == NULL)
3220 ea.cmd = (char_u *)"split";
3221 ea.arg = fname;
3222 ea.cmdidx = CMD_split;
3223 ex_splitview(&ea);
3224
3225 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003226}
3227
3228/*
3229 * Handles a function call from the job running in a terminal.
3230 * "item" is the function name, "item->li_next" has the arguments.
3231 */
3232 static void
3233handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3234{
3235 char_u *func;
3236 typval_T argvars[2];
3237 typval_T rettv;
3238 int doesrange;
3239
3240 if (item->li_next == NULL)
3241 {
3242 ch_log(channel, "Missing function arguments for call");
3243 return;
3244 }
3245 func = get_tv_string(&item->li_tv);
3246
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003247 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003248 {
3249 ch_log(channel, "Invalid function name: %s", func);
3250 return;
3251 }
3252
3253 argvars[0].v_type = VAR_NUMBER;
3254 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3255 argvars[1] = item->li_next->li_tv;
3256 if (call_func(func, STRLEN(func), &rettv,
3257 2, argvars, /* argv_func */ NULL,
3258 /* firstline */ 1, /* lastline */ 1,
3259 &doesrange, /* evaluate */ TRUE,
3260 /* partial */ NULL, /* selfdict */ NULL) == OK)
3261 {
3262 clear_tv(&rettv);
3263 ch_log(channel, "Function %s called", func);
3264 }
3265 else
3266 ch_log(channel, "Calling function %s failed", func);
3267}
3268
3269/*
3270 * Called by libvterm when it cannot recognize an OSC sequence.
3271 * We recognize a terminal API command.
3272 */
3273 static int
3274parse_osc(const char *command, size_t cmdlen, void *user)
3275{
3276 term_T *term = (term_T *)user;
3277 js_read_T reader;
3278 typval_T tv;
3279 channel_T *channel = term->tl_job == NULL ? NULL
3280 : term->tl_job->jv_channel;
3281
3282 /* We recognize only OSC 5 1 ; {command} */
3283 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3284 return 0; /* not handled */
3285
3286 reader.js_buf = vim_strnsave((char_u *)command + 3, cmdlen - 3);
3287 if (reader.js_buf == NULL)
3288 return 1;
3289 reader.js_fill = NULL;
3290 reader.js_used = 0;
3291 if (json_decode(&reader, &tv, 0) == OK
3292 && tv.v_type == VAR_LIST
3293 && tv.vval.v_list != NULL)
3294 {
3295 listitem_T *item = tv.vval.v_list->lv_first;
3296
3297 if (item == NULL)
3298 ch_log(channel, "Missing command");
3299 else
3300 {
3301 char_u *cmd = get_tv_string(&item->li_tv);
3302
3303 item = item->li_next;
3304 if (item == NULL)
3305 ch_log(channel, "Missing argument for %s", cmd);
3306 else if (STRCMP(cmd, "drop") == 0)
3307 handle_drop_command(item);
3308 else if (STRCMP(cmd, "call") == 0)
3309 handle_call_command(term, channel, item);
3310 else
3311 ch_log(channel, "Invalid command received: %s", cmd);
3312 }
3313 }
3314 else
3315 ch_log(channel, "Invalid JSON received");
3316
3317 vim_free(reader.js_buf);
3318 clear_tv(&tv);
3319 return 1;
3320}
3321
3322static VTermParserCallbacks parser_fallbacks = {
3323 NULL, /* text */
3324 NULL, /* control */
3325 NULL, /* escape */
3326 NULL, /* csi */
3327 parse_osc, /* osc */
3328 NULL, /* dcs */
3329 NULL /* resize */
3330};
3331
3332/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003333 * Create a new vterm and initialize it.
3334 */
3335 static void
3336create_vterm(term_T *term, int rows, int cols)
3337{
3338 VTerm *vterm;
3339 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003340 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003341 VTermValue value;
3342
3343 vterm = vterm_new(rows, cols);
3344 term->tl_vterm = vterm;
3345 screen = vterm_obtain_screen(vterm);
3346 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3347 /* TODO: depends on 'encoding'. */
3348 vterm_set_utf8(vterm, 1);
3349
3350 init_default_colors(term);
3351
3352 vterm_state_set_default_colors(
3353 vterm_obtain_state(vterm),
3354 &term->tl_default_color.fg,
3355 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003356
3357 /* Required to initialize most things. */
3358 vterm_screen_reset(screen, 1 /* hard */);
3359
3360 /* Allow using alternate screen. */
3361 vterm_screen_enable_altscreen(screen, 1);
3362
3363 /* For unix do not use a blinking cursor. In an xterm this causes the
3364 * cursor to blink if it's blinking in the xterm.
3365 * For Windows we respect the system wide setting. */
3366#ifdef WIN3264
3367 if (GetCaretBlinkTime() == INFINITE)
3368 value.boolean = 0;
3369 else
3370 value.boolean = 1;
3371#else
3372 value.boolean = 0;
3373#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003374 state = vterm_obtain_state(vterm);
3375 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3376 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003377}
3378
3379/*
3380 * Return the text to show for the buffer name and status.
3381 */
3382 char_u *
3383term_get_status_text(term_T *term)
3384{
3385 if (term->tl_status_text == NULL)
3386 {
3387 char_u *txt;
3388 size_t len;
3389
3390 if (term->tl_normal_mode)
3391 {
3392 if (term_job_running(term))
3393 txt = (char_u *)_("Terminal");
3394 else
3395 txt = (char_u *)_("Terminal-finished");
3396 }
3397 else if (term->tl_title != NULL)
3398 txt = term->tl_title;
3399 else if (term_none_open(term))
3400 txt = (char_u *)_("active");
3401 else if (term_job_running(term))
3402 txt = (char_u *)_("running");
3403 else
3404 txt = (char_u *)_("finished");
3405 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3406 term->tl_status_text = alloc((int)len);
3407 if (term->tl_status_text != NULL)
3408 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3409 term->tl_buffer->b_fname, txt);
3410 }
3411 return term->tl_status_text;
3412}
3413
3414/*
3415 * Mark references in jobs of terminals.
3416 */
3417 int
3418set_ref_in_term(int copyID)
3419{
3420 int abort = FALSE;
3421 term_T *term;
3422 typval_T tv;
3423
3424 for (term = first_term; term != NULL; term = term->tl_next)
3425 if (term->tl_job != NULL)
3426 {
3427 tv.v_type = VAR_JOB;
3428 tv.vval.v_job = term->tl_job;
3429 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3430 }
3431 return abort;
3432}
3433
3434/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003435 * Cache "Terminal" highlight group colors.
3436 */
3437 void
3438set_terminal_default_colors(int cterm_fg, int cterm_bg)
3439{
3440 term_default_cterm_fg = cterm_fg - 1;
3441 term_default_cterm_bg = cterm_bg - 1;
3442}
3443
3444/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003445 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003446 * Returns NULL when the buffer is not for a terminal window and logs a message
3447 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003448 */
3449 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003450term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003451{
3452 buf_T *buf;
3453
3454 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3455 ++emsg_off;
3456 buf = get_buf_tv(&argvars[0], FALSE);
3457 --emsg_off;
3458 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003459 {
3460 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003461 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003462 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003463 return buf;
3464}
3465
Bram Moolenaard96ff162018-02-18 22:13:29 +01003466 static int
3467same_color(VTermColor *a, VTermColor *b)
3468{
3469 return a->red == b->red
3470 && a->green == b->green
3471 && a->blue == b->blue
3472 && a->ansi_index == b->ansi_index;
3473}
3474
3475 static void
3476dump_term_color(FILE *fd, VTermColor *color)
3477{
3478 fprintf(fd, "%02x%02x%02x%d",
3479 (int)color->red, (int)color->green, (int)color->blue,
3480 (int)color->ansi_index);
3481}
3482
3483/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003484 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003485 *
3486 * Each screen cell in full is:
3487 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3488 * {characters} is a space for an empty cell
3489 * For a double-width character "+" is changed to "*" and the next cell is
3490 * skipped.
3491 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3492 * when "&" use the same as the previous cell.
3493 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3494 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3495 * {color-idx} is a number from 0 to 255
3496 *
3497 * Screen cell with same width, attributes and color as the previous one:
3498 * |{characters}
3499 *
3500 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3501 *
3502 * Repeating the previous screen cell:
3503 * @{count}
3504 */
3505 void
3506f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3507{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003508 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003509 term_T *term;
3510 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003511 int max_height = 0;
3512 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003513 stat_T st;
3514 FILE *fd;
3515 VTermPos pos;
3516 VTermScreen *screen;
3517 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003518 VTermState *state;
3519 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003520
3521 if (check_restricted() || check_secure())
3522 return;
3523 if (buf == NULL)
3524 return;
3525 term = buf->b_term;
3526
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003527 if (argvars[2].v_type != VAR_UNKNOWN)
3528 {
3529 dict_T *d;
3530
3531 if (argvars[2].v_type != VAR_DICT)
3532 {
3533 EMSG(_(e_dictreq));
3534 return;
3535 }
3536 d = argvars[2].vval.v_dict;
3537 if (d != NULL)
3538 {
3539 max_height = get_dict_number(d, (char_u *)"rows");
3540 max_width = get_dict_number(d, (char_u *)"columns");
3541 }
3542 }
3543
Bram Moolenaard96ff162018-02-18 22:13:29 +01003544 fname = get_tv_string_chk(&argvars[1]);
3545 if (fname == NULL)
3546 return;
3547 if (mch_stat((char *)fname, &st) >= 0)
3548 {
3549 EMSG2(_("E953: File exists: %s"), fname);
3550 return;
3551 }
3552
Bram Moolenaard96ff162018-02-18 22:13:29 +01003553 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3554 {
3555 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3556 return;
3557 }
3558
3559 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3560
3561 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003562 state = vterm_obtain_state(term->tl_vterm);
3563 vterm_state_get_cursorpos(state, &cursor_pos);
3564
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003565 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3566 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003567 {
3568 int repeat = 0;
3569
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003570 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3571 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003572 {
3573 VTermScreenCell cell;
3574 int same_attr;
3575 int same_chars = TRUE;
3576 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003577 int is_cursor_pos = (pos.col == cursor_pos.col
3578 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003579
3580 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3581 vim_memset(&cell, 0, sizeof(cell));
3582
3583 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3584 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003585 int c = cell.chars[i];
3586 int pc = prev_cell.chars[i];
3587
3588 /* For the first character NUL is the same as space. */
3589 if (i == 0)
3590 {
3591 c = (c == NUL) ? ' ' : c;
3592 pc = (pc == NUL) ? ' ' : pc;
3593 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003594 if (cell.chars[i] != prev_cell.chars[i])
3595 same_chars = FALSE;
3596 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3597 break;
3598 }
3599 same_attr = vtermAttr2hl(cell.attrs)
3600 == vtermAttr2hl(prev_cell.attrs)
3601 && same_color(&cell.fg, &prev_cell.fg)
3602 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003603 if (same_chars && cell.width == prev_cell.width && same_attr
3604 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003605 {
3606 ++repeat;
3607 }
3608 else
3609 {
3610 if (repeat > 0)
3611 {
3612 fprintf(fd, "@%d", repeat);
3613 repeat = 0;
3614 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003615 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003616
3617 if (cell.chars[0] == NUL)
3618 fputs(" ", fd);
3619 else
3620 {
3621 char_u charbuf[10];
3622 int len;
3623
3624 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3625 && cell.chars[i] != NUL; ++i)
3626 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003627 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003628 fwrite(charbuf, len, 1, fd);
3629 }
3630 }
3631
3632 /* When only the characters differ we don't write anything, the
3633 * following "|", "@" or NL will indicate using the same
3634 * attributes. */
3635 if (cell.width != prev_cell.width || !same_attr)
3636 {
3637 if (cell.width == 2)
3638 {
3639 fputs("*", fd);
3640 ++pos.col;
3641 }
3642 else
3643 fputs("+", fd);
3644
3645 if (same_attr)
3646 {
3647 fputs("&", fd);
3648 }
3649 else
3650 {
3651 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3652 if (same_color(&cell.fg, &prev_cell.fg))
3653 fputs("&", fd);
3654 else
3655 {
3656 fputs("#", fd);
3657 dump_term_color(fd, &cell.fg);
3658 }
3659 if (same_color(&cell.bg, &prev_cell.bg))
3660 fputs("&", fd);
3661 else
3662 {
3663 fputs("#", fd);
3664 dump_term_color(fd, &cell.bg);
3665 }
3666 }
3667 }
3668
3669 prev_cell = cell;
3670 }
3671 }
3672 if (repeat > 0)
3673 fprintf(fd, "@%d", repeat);
3674 fputs("\n", fd);
3675 }
3676
3677 fclose(fd);
3678}
3679
3680/*
3681 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3682 */
3683 static void
3684dump_is_corrupt(garray_T *gap)
3685{
3686 ga_concat(gap, (char_u *)"CORRUPT");
3687}
3688
3689 static void
3690append_cell(garray_T *gap, cellattr_T *cell)
3691{
3692 if (ga_grow(gap, 1) == OK)
3693 {
3694 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3695 ++gap->ga_len;
3696 }
3697}
3698
3699/*
3700 * Read the dump file from "fd" and append lines to the current buffer.
3701 * Return the cell width of the longest line.
3702 */
3703 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003704read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003705{
3706 int c;
3707 garray_T ga_text;
3708 garray_T ga_cell;
3709 char_u *prev_char = NULL;
3710 int attr = 0;
3711 cellattr_T cell;
3712 term_T *term = curbuf->b_term;
3713 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003714 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003715
3716 ga_init2(&ga_text, 1, 90);
3717 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3718 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003719 cursor_pos->row = -1;
3720 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003721
3722 c = fgetc(fd);
3723 for (;;)
3724 {
3725 if (c == EOF)
3726 break;
3727 if (c == '\n')
3728 {
3729 /* End of a line: append it to the buffer. */
3730 if (ga_text.ga_data == NULL)
3731 dump_is_corrupt(&ga_text);
3732 if (ga_grow(&term->tl_scrollback, 1) == OK)
3733 {
3734 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3735 + term->tl_scrollback.ga_len;
3736
3737 if (max_cells < ga_cell.ga_len)
3738 max_cells = ga_cell.ga_len;
3739 line->sb_cols = ga_cell.ga_len;
3740 line->sb_cells = ga_cell.ga_data;
3741 line->sb_fill_attr = term->tl_default_color;
3742 ++term->tl_scrollback.ga_len;
3743 ga_init(&ga_cell);
3744
3745 ga_append(&ga_text, NUL);
3746 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3747 ga_text.ga_len, FALSE);
3748 }
3749 else
3750 ga_clear(&ga_cell);
3751 ga_text.ga_len = 0;
3752
3753 c = fgetc(fd);
3754 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003755 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003756 {
3757 int prev_len = ga_text.ga_len;
3758
Bram Moolenaar9271d052018-02-25 21:39:46 +01003759 if (c == '>')
3760 {
3761 if (cursor_pos->row != -1)
3762 dump_is_corrupt(&ga_text); /* duplicate cursor */
3763 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3764 cursor_pos->col = ga_cell.ga_len;
3765 }
3766
Bram Moolenaard96ff162018-02-18 22:13:29 +01003767 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3768 c = fgetc(fd);
3769 if (c != EOF)
3770 ga_append(&ga_text, c);
3771 for (;;)
3772 {
3773 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003774 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003775 || c == EOF || c == '\n')
3776 break;
3777 ga_append(&ga_text, c);
3778 }
3779
3780 /* save the character for repeating it */
3781 vim_free(prev_char);
3782 if (ga_text.ga_data != NULL)
3783 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3784 ga_text.ga_len - prev_len);
3785
Bram Moolenaar9271d052018-02-25 21:39:46 +01003786 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003787 {
3788 /* use all attributes from previous cell */
3789 }
3790 else if (c == '+' || c == '*')
3791 {
3792 int is_bg;
3793
3794 cell.width = c == '+' ? 1 : 2;
3795
3796 c = fgetc(fd);
3797 if (c == '&')
3798 {
3799 /* use same attr as previous cell */
3800 c = fgetc(fd);
3801 }
3802 else if (isdigit(c))
3803 {
3804 /* get the decimal attribute */
3805 attr = 0;
3806 while (isdigit(c))
3807 {
3808 attr = attr * 10 + (c - '0');
3809 c = fgetc(fd);
3810 }
3811 hl2vtermAttr(attr, &cell);
3812 }
3813 else
3814 dump_is_corrupt(&ga_text);
3815
3816 /* is_bg == 0: fg, is_bg == 1: bg */
3817 for (is_bg = 0; is_bg <= 1; ++is_bg)
3818 {
3819 if (c == '&')
3820 {
3821 /* use same color as previous cell */
3822 c = fgetc(fd);
3823 }
3824 else if (c == '#')
3825 {
3826 int red, green, blue, index = 0;
3827
3828 c = fgetc(fd);
3829 red = hex2nr(c);
3830 c = fgetc(fd);
3831 red = (red << 4) + hex2nr(c);
3832 c = fgetc(fd);
3833 green = hex2nr(c);
3834 c = fgetc(fd);
3835 green = (green << 4) + hex2nr(c);
3836 c = fgetc(fd);
3837 blue = hex2nr(c);
3838 c = fgetc(fd);
3839 blue = (blue << 4) + hex2nr(c);
3840 c = fgetc(fd);
3841 if (!isdigit(c))
3842 dump_is_corrupt(&ga_text);
3843 while (isdigit(c))
3844 {
3845 index = index * 10 + (c - '0');
3846 c = fgetc(fd);
3847 }
3848
3849 if (is_bg)
3850 {
3851 cell.bg.red = red;
3852 cell.bg.green = green;
3853 cell.bg.blue = blue;
3854 cell.bg.ansi_index = index;
3855 }
3856 else
3857 {
3858 cell.fg.red = red;
3859 cell.fg.green = green;
3860 cell.fg.blue = blue;
3861 cell.fg.ansi_index = index;
3862 }
3863 }
3864 else
3865 dump_is_corrupt(&ga_text);
3866 }
3867 }
3868 else
3869 dump_is_corrupt(&ga_text);
3870
3871 append_cell(&ga_cell, &cell);
3872 }
3873 else if (c == '@')
3874 {
3875 if (prev_char == NULL)
3876 dump_is_corrupt(&ga_text);
3877 else
3878 {
3879 int count = 0;
3880
3881 /* repeat previous character, get the count */
3882 for (;;)
3883 {
3884 c = fgetc(fd);
3885 if (!isdigit(c))
3886 break;
3887 count = count * 10 + (c - '0');
3888 }
3889
3890 while (count-- > 0)
3891 {
3892 ga_concat(&ga_text, prev_char);
3893 append_cell(&ga_cell, &cell);
3894 }
3895 }
3896 }
3897 else
3898 {
3899 dump_is_corrupt(&ga_text);
3900 c = fgetc(fd);
3901 }
3902 }
3903
3904 if (ga_text.ga_len > 0)
3905 {
3906 /* trailing characters after last NL */
3907 dump_is_corrupt(&ga_text);
3908 ga_append(&ga_text, NUL);
3909 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3910 ga_text.ga_len, FALSE);
3911 }
3912
3913 ga_clear(&ga_text);
3914 vim_free(prev_char);
3915
3916 return max_cells;
3917}
3918
3919/*
3920 * Common for "term_dumpdiff()" and "term_dumpload()".
3921 */
3922 static void
3923term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
3924{
3925 jobopt_T opt;
3926 buf_T *buf;
3927 char_u buf1[NUMBUFLEN];
3928 char_u buf2[NUMBUFLEN];
3929 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003930 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01003931 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003932 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003933 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003934 char_u *textline = NULL;
3935
3936 /* First open the files. If this fails bail out. */
3937 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
3938 if (do_diff)
3939 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
3940 if (fname1 == NULL || (do_diff && fname2 == NULL))
3941 {
3942 EMSG(_(e_invarg));
3943 return;
3944 }
3945 fd1 = mch_fopen((char *)fname1, READBIN);
3946 if (fd1 == NULL)
3947 {
3948 EMSG2(_(e_notread), fname1);
3949 return;
3950 }
3951 if (do_diff)
3952 {
3953 fd2 = mch_fopen((char *)fname2, READBIN);
3954 if (fd2 == NULL)
3955 {
3956 fclose(fd1);
3957 EMSG2(_(e_notread), fname2);
3958 return;
3959 }
3960 }
3961
3962 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01003963 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
3964 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
3965 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
3966 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
3967 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003968
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01003969 if (opt.jo_term_name == NULL)
3970 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01003971 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01003972
Bram Moolenaarb571c632018-03-21 22:27:59 +01003973 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01003974 if (fname_tofree != NULL)
3975 {
3976 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
3977 opt.jo_term_name = fname_tofree;
3978 }
3979 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003980
Bram Moolenaar13568252018-03-16 20:46:58 +01003981 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003982 if (buf != NULL && buf->b_term != NULL)
3983 {
3984 int i;
3985 linenr_T bot_lnum;
3986 linenr_T lnum;
3987 term_T *term = buf->b_term;
3988 int width;
3989 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003990 VTermPos cursor_pos1;
3991 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003992
Bram Moolenaar52acb112018-03-18 19:20:22 +01003993 init_default_colors(term);
3994
Bram Moolenaard96ff162018-02-18 22:13:29 +01003995 rettv->vval.v_number = buf->b_fnum;
3996
3997 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01003998 width = read_dump_file(fd1, &cursor_pos1);
3999
4000 /* position the cursor */
4001 if (cursor_pos1.row >= 0)
4002 {
4003 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4004 coladvance(cursor_pos1.col);
4005 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004006
4007 /* Delete the empty line that was in the empty buffer. */
4008 ml_delete(1, FALSE);
4009
4010 /* For term_dumpload() we are done here. */
4011 if (!do_diff)
4012 goto theend;
4013
4014 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4015
4016 textline = alloc(width + 1);
4017 if (textline == NULL)
4018 goto theend;
4019 for (i = 0; i < width; ++i)
4020 textline[i] = '=';
4021 textline[width] = NUL;
4022 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4023 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4024 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4025 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4026
4027 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004028 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004029 if (width2 > width)
4030 {
4031 vim_free(textline);
4032 textline = alloc(width2 + 1);
4033 if (textline == NULL)
4034 goto theend;
4035 width = width2;
4036 textline[width] = NUL;
4037 }
4038 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4039
4040 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4041 {
4042 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4043 {
4044 /* bottom part has fewer rows, fill with "-" */
4045 for (i = 0; i < width; ++i)
4046 textline[i] = '-';
4047 }
4048 else
4049 {
4050 char_u *line1;
4051 char_u *line2;
4052 char_u *p1;
4053 char_u *p2;
4054 int col;
4055 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4056 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4057 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4058 ->sb_cells;
4059
4060 /* Make a copy, getting the second line will invalidate it. */
4061 line1 = vim_strsave(ml_get(lnum));
4062 if (line1 == NULL)
4063 break;
4064 p1 = line1;
4065
4066 line2 = ml_get(lnum + bot_lnum);
4067 p2 = line2;
4068 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4069 {
4070 int len1 = utfc_ptr2len(p1);
4071 int len2 = utfc_ptr2len(p2);
4072
4073 textline[col] = ' ';
4074 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004075 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004076 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004077 else if (lnum == cursor_pos1.row + 1
4078 && col == cursor_pos1.col
4079 && (cursor_pos1.row != cursor_pos2.row
4080 || cursor_pos1.col != cursor_pos2.col))
4081 /* cursor in first but not in second */
4082 textline[col] = '>';
4083 else if (lnum == cursor_pos2.row + 1
4084 && col == cursor_pos2.col
4085 && (cursor_pos1.row != cursor_pos2.row
4086 || cursor_pos1.col != cursor_pos2.col))
4087 /* cursor in second but not in first */
4088 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004089 else if (cellattr1 != NULL && cellattr2 != NULL)
4090 {
4091 if ((cellattr1 + col)->width
4092 != (cellattr2 + col)->width)
4093 textline[col] = 'w';
4094 else if (!same_color(&(cellattr1 + col)->fg,
4095 &(cellattr2 + col)->fg))
4096 textline[col] = 'f';
4097 else if (!same_color(&(cellattr1 + col)->bg,
4098 &(cellattr2 + col)->bg))
4099 textline[col] = 'b';
4100 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4101 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4102 textline[col] = 'a';
4103 }
4104 p1 += len1;
4105 p2 += len2;
4106 /* TODO: handle different width */
4107 }
4108 vim_free(line1);
4109
4110 while (col < width)
4111 {
4112 if (*p1 == NUL && *p2 == NUL)
4113 textline[col] = '?';
4114 else if (*p1 == NUL)
4115 {
4116 textline[col] = '+';
4117 p2 += utfc_ptr2len(p2);
4118 }
4119 else
4120 {
4121 textline[col] = '-';
4122 p1 += utfc_ptr2len(p1);
4123 }
4124 ++col;
4125 }
4126 }
4127 if (add_empty_scrollback(term, &term->tl_default_color,
4128 term->tl_top_diff_rows) == OK)
4129 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4130 ++bot_lnum;
4131 }
4132
4133 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4134 {
4135 /* bottom part has more rows, fill with "+" */
4136 for (i = 0; i < width; ++i)
4137 textline[i] = '+';
4138 if (add_empty_scrollback(term, &term->tl_default_color,
4139 term->tl_top_diff_rows) == OK)
4140 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4141 ++lnum;
4142 ++bot_lnum;
4143 }
4144
4145 term->tl_cols = width;
4146 }
4147
4148theend:
4149 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004150 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004151 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004152 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004153 fclose(fd2);
4154}
4155
4156/*
4157 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4158 * bottom files.
4159 * Return FAIL when this is not possible.
4160 */
4161 int
4162term_swap_diff()
4163{
4164 term_T *term = curbuf->b_term;
4165 linenr_T line_count;
4166 linenr_T top_rows;
4167 linenr_T bot_rows;
4168 linenr_T bot_start;
4169 linenr_T lnum;
4170 char_u *p;
4171 sb_line_T *sb_line;
4172
4173 if (term == NULL
4174 || !term_is_finished(curbuf)
4175 || term->tl_top_diff_rows == 0
4176 || term->tl_scrollback.ga_len == 0)
4177 return FAIL;
4178
4179 line_count = curbuf->b_ml.ml_line_count;
4180 top_rows = term->tl_top_diff_rows;
4181 bot_rows = term->tl_bot_diff_rows;
4182 bot_start = line_count - bot_rows;
4183 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4184
4185 /* move lines from top to above the bottom part */
4186 for (lnum = 1; lnum <= top_rows; ++lnum)
4187 {
4188 p = vim_strsave(ml_get(1));
4189 if (p == NULL)
4190 return OK;
4191 ml_append(bot_start, p, 0, FALSE);
4192 ml_delete(1, FALSE);
4193 vim_free(p);
4194 }
4195
4196 /* move lines from bottom to the top */
4197 for (lnum = 1; lnum <= bot_rows; ++lnum)
4198 {
4199 p = vim_strsave(ml_get(bot_start + lnum));
4200 if (p == NULL)
4201 return OK;
4202 ml_delete(bot_start + lnum, FALSE);
4203 ml_append(lnum - 1, p, 0, FALSE);
4204 vim_free(p);
4205 }
4206
4207 if (top_rows == bot_rows)
4208 {
4209 /* rows counts are equal, can swap cell properties */
4210 for (lnum = 0; lnum < top_rows; ++lnum)
4211 {
4212 sb_line_T temp;
4213
4214 temp = *(sb_line + lnum);
4215 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4216 *(sb_line + bot_start + lnum) = temp;
4217 }
4218 }
4219 else
4220 {
4221 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4222 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4223
4224 /* need to copy cell properties into temp memory */
4225 if (temp != NULL)
4226 {
4227 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4228 mch_memmove(term->tl_scrollback.ga_data,
4229 temp + bot_start,
4230 sizeof(sb_line_T) * bot_rows);
4231 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4232 temp + top_rows,
4233 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4234 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4235 + line_count - top_rows,
4236 temp,
4237 sizeof(sb_line_T) * top_rows);
4238 vim_free(temp);
4239 }
4240 }
4241
4242 term->tl_top_diff_rows = bot_rows;
4243 term->tl_bot_diff_rows = top_rows;
4244
4245 update_screen(NOT_VALID);
4246 return OK;
4247}
4248
4249/*
4250 * "term_dumpdiff(filename, filename, options)" function
4251 */
4252 void
4253f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4254{
4255 term_load_dump(argvars, rettv, TRUE);
4256}
4257
4258/*
4259 * "term_dumpload(filename, options)" function
4260 */
4261 void
4262f_term_dumpload(typval_T *argvars, typval_T *rettv)
4263{
4264 term_load_dump(argvars, rettv, FALSE);
4265}
4266
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004267/*
4268 * "term_getaltscreen(buf)" function
4269 */
4270 void
4271f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4272{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004273 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004274
4275 if (buf == NULL)
4276 return;
4277 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4278}
4279
4280/*
4281 * "term_getattr(attr, name)" function
4282 */
4283 void
4284f_term_getattr(typval_T *argvars, typval_T *rettv)
4285{
4286 int attr;
4287 size_t i;
4288 char_u *name;
4289
4290 static struct {
4291 char *name;
4292 int attr;
4293 } attrs[] = {
4294 {"bold", HL_BOLD},
4295 {"italic", HL_ITALIC},
4296 {"underline", HL_UNDERLINE},
4297 {"strike", HL_STRIKETHROUGH},
4298 {"reverse", HL_INVERSE},
4299 };
4300
4301 attr = get_tv_number(&argvars[0]);
4302 name = get_tv_string_chk(&argvars[1]);
4303 if (name == NULL)
4304 return;
4305
4306 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4307 if (STRCMP(name, attrs[i].name) == 0)
4308 {
4309 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4310 break;
4311 }
4312}
4313
4314/*
4315 * "term_getcursor(buf)" function
4316 */
4317 void
4318f_term_getcursor(typval_T *argvars, typval_T *rettv)
4319{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004320 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004321 term_T *term;
4322 list_T *l;
4323 dict_T *d;
4324
4325 if (rettv_list_alloc(rettv) == FAIL)
4326 return;
4327 if (buf == NULL)
4328 return;
4329 term = buf->b_term;
4330
4331 l = rettv->vval.v_list;
4332 list_append_number(l, term->tl_cursor_pos.row + 1);
4333 list_append_number(l, term->tl_cursor_pos.col + 1);
4334
4335 d = dict_alloc();
4336 if (d != NULL)
4337 {
4338 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4339 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4340 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4341 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4342 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4343 ? (char_u *)"" : term->tl_cursor_color);
4344 list_append_dict(l, d);
4345 }
4346}
4347
4348/*
4349 * "term_getjob(buf)" function
4350 */
4351 void
4352f_term_getjob(typval_T *argvars, typval_T *rettv)
4353{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004354 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004355
4356 rettv->v_type = VAR_JOB;
4357 rettv->vval.v_job = NULL;
4358 if (buf == NULL)
4359 return;
4360
4361 rettv->vval.v_job = buf->b_term->tl_job;
4362 if (rettv->vval.v_job != NULL)
4363 ++rettv->vval.v_job->jv_refcount;
4364}
4365
4366 static int
4367get_row_number(typval_T *tv, term_T *term)
4368{
4369 if (tv->v_type == VAR_STRING
4370 && tv->vval.v_string != NULL
4371 && STRCMP(tv->vval.v_string, ".") == 0)
4372 return term->tl_cursor_pos.row;
4373 return (int)get_tv_number(tv) - 1;
4374}
4375
4376/*
4377 * "term_getline(buf, row)" function
4378 */
4379 void
4380f_term_getline(typval_T *argvars, typval_T *rettv)
4381{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004382 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004383 term_T *term;
4384 int row;
4385
4386 rettv->v_type = VAR_STRING;
4387 if (buf == NULL)
4388 return;
4389 term = buf->b_term;
4390 row = get_row_number(&argvars[1], term);
4391
4392 if (term->tl_vterm == NULL)
4393 {
4394 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4395
4396 /* vterm is finished, get the text from the buffer */
4397 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4398 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4399 }
4400 else
4401 {
4402 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4403 VTermRect rect;
4404 int len;
4405 char_u *p;
4406
4407 if (row < 0 || row >= term->tl_rows)
4408 return;
4409 len = term->tl_cols * MB_MAXBYTES + 1;
4410 p = alloc(len);
4411 if (p == NULL)
4412 return;
4413 rettv->vval.v_string = p;
4414
4415 rect.start_col = 0;
4416 rect.end_col = term->tl_cols;
4417 rect.start_row = row;
4418 rect.end_row = row + 1;
4419 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4420 }
4421}
4422
4423/*
4424 * "term_getscrolled(buf)" function
4425 */
4426 void
4427f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4428{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004429 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004430
4431 if (buf == NULL)
4432 return;
4433 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4434}
4435
4436/*
4437 * "term_getsize(buf)" function
4438 */
4439 void
4440f_term_getsize(typval_T *argvars, typval_T *rettv)
4441{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004442 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004443 list_T *l;
4444
4445 if (rettv_list_alloc(rettv) == FAIL)
4446 return;
4447 if (buf == NULL)
4448 return;
4449
4450 l = rettv->vval.v_list;
4451 list_append_number(l, buf->b_term->tl_rows);
4452 list_append_number(l, buf->b_term->tl_cols);
4453}
4454
4455/*
4456 * "term_getstatus(buf)" function
4457 */
4458 void
4459f_term_getstatus(typval_T *argvars, typval_T *rettv)
4460{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004461 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004462 term_T *term;
4463 char_u val[100];
4464
4465 rettv->v_type = VAR_STRING;
4466 if (buf == NULL)
4467 return;
4468 term = buf->b_term;
4469
4470 if (term_job_running(term))
4471 STRCPY(val, "running");
4472 else
4473 STRCPY(val, "finished");
4474 if (term->tl_normal_mode)
4475 STRCAT(val, ",normal");
4476 rettv->vval.v_string = vim_strsave(val);
4477}
4478
4479/*
4480 * "term_gettitle(buf)" function
4481 */
4482 void
4483f_term_gettitle(typval_T *argvars, typval_T *rettv)
4484{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004485 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004486
4487 rettv->v_type = VAR_STRING;
4488 if (buf == NULL)
4489 return;
4490
4491 if (buf->b_term->tl_title != NULL)
4492 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4493}
4494
4495/*
4496 * "term_gettty(buf)" function
4497 */
4498 void
4499f_term_gettty(typval_T *argvars, typval_T *rettv)
4500{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004501 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004502 char_u *p;
4503 int num = 0;
4504
4505 rettv->v_type = VAR_STRING;
4506 if (buf == NULL)
4507 return;
4508 if (argvars[1].v_type != VAR_UNKNOWN)
4509 num = get_tv_number(&argvars[1]);
4510
4511 switch (num)
4512 {
4513 case 0:
4514 if (buf->b_term->tl_job != NULL)
4515 p = buf->b_term->tl_job->jv_tty_out;
4516 else
4517 p = buf->b_term->tl_tty_out;
4518 break;
4519 case 1:
4520 if (buf->b_term->tl_job != NULL)
4521 p = buf->b_term->tl_job->jv_tty_in;
4522 else
4523 p = buf->b_term->tl_tty_in;
4524 break;
4525 default:
4526 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4527 return;
4528 }
4529 if (p != NULL)
4530 rettv->vval.v_string = vim_strsave(p);
4531}
4532
4533/*
4534 * "term_list()" function
4535 */
4536 void
4537f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4538{
4539 term_T *tp;
4540 list_T *l;
4541
4542 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4543 return;
4544
4545 l = rettv->vval.v_list;
4546 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4547 if (tp != NULL && tp->tl_buffer != NULL)
4548 if (list_append_number(l,
4549 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4550 return;
4551}
4552
4553/*
4554 * "term_scrape(buf, row)" function
4555 */
4556 void
4557f_term_scrape(typval_T *argvars, typval_T *rettv)
4558{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004559 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004560 VTermScreen *screen = NULL;
4561 VTermPos pos;
4562 list_T *l;
4563 term_T *term;
4564 char_u *p;
4565 sb_line_T *line;
4566
4567 if (rettv_list_alloc(rettv) == FAIL)
4568 return;
4569 if (buf == NULL)
4570 return;
4571 term = buf->b_term;
4572
4573 l = rettv->vval.v_list;
4574 pos.row = get_row_number(&argvars[1], term);
4575
4576 if (term->tl_vterm != NULL)
4577 {
4578 screen = vterm_obtain_screen(term->tl_vterm);
4579 p = NULL;
4580 line = NULL;
4581 }
4582 else
4583 {
4584 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4585
4586 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4587 return;
4588 p = ml_get_buf(buf, lnum + 1, FALSE);
4589 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4590 }
4591
4592 for (pos.col = 0; pos.col < term->tl_cols; )
4593 {
4594 dict_T *dcell;
4595 int width;
4596 VTermScreenCellAttrs attrs;
4597 VTermColor fg, bg;
4598 char_u rgb[8];
4599 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4600 int off = 0;
4601 int i;
4602
4603 if (screen == NULL)
4604 {
4605 cellattr_T *cellattr;
4606 int len;
4607
4608 /* vterm has finished, get the cell from scrollback */
4609 if (pos.col >= line->sb_cols)
4610 break;
4611 cellattr = line->sb_cells + pos.col;
4612 width = cellattr->width;
4613 attrs = cellattr->attrs;
4614 fg = cellattr->fg;
4615 bg = cellattr->bg;
4616 len = MB_PTR2LEN(p);
4617 mch_memmove(mbs, p, len);
4618 mbs[len] = NUL;
4619 p += len;
4620 }
4621 else
4622 {
4623 VTermScreenCell cell;
4624 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4625 break;
4626 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4627 {
4628 if (cell.chars[i] == 0)
4629 break;
4630 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4631 }
4632 mbs[off] = NUL;
4633 width = cell.width;
4634 attrs = cell.attrs;
4635 fg = cell.fg;
4636 bg = cell.bg;
4637 }
4638 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004639 if (dcell == NULL)
4640 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004641 list_append_dict(l, dcell);
4642
4643 dict_add_nr_str(dcell, "chars", 0, mbs);
4644
4645 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4646 fg.red, fg.green, fg.blue);
4647 dict_add_nr_str(dcell, "fg", 0, rgb);
4648 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4649 bg.red, bg.green, bg.blue);
4650 dict_add_nr_str(dcell, "bg", 0, rgb);
4651
4652 dict_add_nr_str(dcell, "attr",
4653 cell2attr(attrs, fg, bg), NULL);
4654 dict_add_nr_str(dcell, "width", width, NULL);
4655
4656 ++pos.col;
4657 if (width == 2)
4658 ++pos.col;
4659 }
4660}
4661
4662/*
4663 * "term_sendkeys(buf, keys)" function
4664 */
4665 void
4666f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4667{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004668 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004669 char_u *msg;
4670 term_T *term;
4671
4672 rettv->v_type = VAR_UNKNOWN;
4673 if (buf == NULL)
4674 return;
4675
4676 msg = get_tv_string_chk(&argvars[1]);
4677 if (msg == NULL)
4678 return;
4679 term = buf->b_term;
4680 if (term->tl_vterm == NULL)
4681 return;
4682
4683 while (*msg != NUL)
4684 {
4685 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004686 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004687 }
4688}
4689
4690/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004691 * "term_setrestore(buf, command)" function
4692 */
4693 void
4694f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4695{
4696#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004697 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004698 term_T *term;
4699 char_u *cmd;
4700
4701 if (buf == NULL)
4702 return;
4703 term = buf->b_term;
4704 vim_free(term->tl_command);
4705 cmd = get_tv_string_chk(&argvars[1]);
4706 if (cmd != NULL)
4707 term->tl_command = vim_strsave(cmd);
4708 else
4709 term->tl_command = NULL;
4710#endif
4711}
4712
4713/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004714 * "term_setkill(buf, how)" function
4715 */
4716 void
4717f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4718{
4719 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4720 term_T *term;
4721 char_u *how;
4722
4723 if (buf == NULL)
4724 return;
4725 term = buf->b_term;
4726 vim_free(term->tl_kill);
4727 how = get_tv_string_chk(&argvars[1]);
4728 if (how != NULL)
4729 term->tl_kill = vim_strsave(how);
4730 else
4731 term->tl_kill = NULL;
4732}
4733
4734/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004735 * "term_start(command, options)" function
4736 */
4737 void
4738f_term_start(typval_T *argvars, typval_T *rettv)
4739{
4740 jobopt_T opt;
4741 buf_T *buf;
4742
4743 init_job_options(&opt);
4744 if (argvars[1].v_type != VAR_UNKNOWN
4745 && get_job_options(&argvars[1], &opt,
4746 JO_TIMEOUT_ALL + JO_STOPONEXIT
4747 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4748 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4749 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4750 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004751 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004752 + JO2_NORESTORE + JO2_TERM_KILL) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004753 return;
4754
Bram Moolenaar13568252018-03-16 20:46:58 +01004755 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004756
4757 if (buf != NULL && buf->b_term != NULL)
4758 rettv->vval.v_number = buf->b_fnum;
4759}
4760
4761/*
4762 * "term_wait" function
4763 */
4764 void
4765f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4766{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004767 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004768
4769 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004770 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004771 if (buf->b_term->tl_job == NULL)
4772 {
4773 ch_log(NULL, "term_wait(): no job to wait for");
4774 return;
4775 }
4776 if (buf->b_term->tl_job->jv_channel == NULL)
4777 /* channel is closed, nothing to do */
4778 return;
4779
4780 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004781 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004782 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4783 {
4784 /* The job is dead, keep reading channel I/O until the channel is
4785 * closed. buf->b_term may become NULL if the terminal was closed while
4786 * waiting. */
4787 ch_log(NULL, "term_wait(): waiting for channel to close");
4788 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4789 {
4790 mch_check_messages();
4791 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01004792 if (!buf_valid(buf))
4793 /* If the terminal is closed when the channel is closed the
4794 * buffer disappears. */
4795 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004796 ui_delay(10L, FALSE);
4797 }
4798 mch_check_messages();
4799 parse_queued_messages();
4800 }
4801 else
4802 {
4803 long wait = 10L;
4804
4805 mch_check_messages();
4806 parse_queued_messages();
4807
4808 /* Wait for some time for any channel I/O. */
4809 if (argvars[1].v_type != VAR_UNKNOWN)
4810 wait = get_tv_number(&argvars[1]);
4811 ui_delay(wait, TRUE);
4812 mch_check_messages();
4813
4814 /* Flushing messages on channels is hopefully sufficient.
4815 * TODO: is there a better way? */
4816 parse_queued_messages();
4817 }
4818}
4819
4820/*
4821 * Called when a channel has sent all the lines to a terminal.
4822 * Send a CTRL-D to mark the end of the text.
4823 */
4824 void
4825term_send_eof(channel_T *ch)
4826{
4827 term_T *term;
4828
4829 for (term = first_term; term != NULL; term = term->tl_next)
4830 if (term->tl_job == ch->ch_job)
4831 {
4832 if (term->tl_eof_chars != NULL)
4833 {
4834 channel_send(ch, PART_IN, term->tl_eof_chars,
4835 (int)STRLEN(term->tl_eof_chars), NULL);
4836 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
4837 }
4838# ifdef WIN3264
4839 else
4840 /* Default: CTRL-D */
4841 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
4842# endif
4843 }
4844}
4845
4846# if defined(WIN3264) || defined(PROTO)
4847
4848/**************************************
4849 * 2. MS-Windows implementation.
4850 */
4851
4852# ifndef PROTO
4853
4854#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
4855#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01004856#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004857
4858void* (*winpty_config_new)(UINT64, void*);
4859void* (*winpty_open)(void*, void*);
4860void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
4861BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
4862void (*winpty_config_set_mouse_mode)(void*, int);
4863void (*winpty_config_set_initial_size)(void*, int, int);
4864LPCWSTR (*winpty_conin_name)(void*);
4865LPCWSTR (*winpty_conout_name)(void*);
4866LPCWSTR (*winpty_conerr_name)(void*);
4867void (*winpty_free)(void*);
4868void (*winpty_config_free)(void*);
4869void (*winpty_spawn_config_free)(void*);
4870void (*winpty_error_free)(void*);
4871LPCWSTR (*winpty_error_msg)(void*);
4872BOOL (*winpty_set_size)(void*, int, int, void*);
4873HANDLE (*winpty_agent_process)(void*);
4874
4875#define WINPTY_DLL "winpty.dll"
4876
4877static HINSTANCE hWinPtyDLL = NULL;
4878# endif
4879
4880 static int
4881dyn_winpty_init(int verbose)
4882{
4883 int i;
4884 static struct
4885 {
4886 char *name;
4887 FARPROC *ptr;
4888 } winpty_entry[] =
4889 {
4890 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
4891 {"winpty_config_free", (FARPROC*)&winpty_config_free},
4892 {"winpty_config_new", (FARPROC*)&winpty_config_new},
4893 {"winpty_config_set_mouse_mode",
4894 (FARPROC*)&winpty_config_set_mouse_mode},
4895 {"winpty_config_set_initial_size",
4896 (FARPROC*)&winpty_config_set_initial_size},
4897 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
4898 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
4899 {"winpty_error_free", (FARPROC*)&winpty_error_free},
4900 {"winpty_free", (FARPROC*)&winpty_free},
4901 {"winpty_open", (FARPROC*)&winpty_open},
4902 {"winpty_spawn", (FARPROC*)&winpty_spawn},
4903 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
4904 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
4905 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
4906 {"winpty_set_size", (FARPROC*)&winpty_set_size},
4907 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
4908 {NULL, NULL}
4909 };
4910
4911 /* No need to initialize twice. */
4912 if (hWinPtyDLL)
4913 return OK;
4914 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
4915 * winpty.dll. */
4916 if (*p_winptydll != NUL)
4917 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
4918 if (!hWinPtyDLL)
4919 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
4920 if (!hWinPtyDLL)
4921 {
4922 if (verbose)
4923 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
4924 : (char_u *)WINPTY_DLL);
4925 return FAIL;
4926 }
4927 for (i = 0; winpty_entry[i].name != NULL
4928 && winpty_entry[i].ptr != NULL; ++i)
4929 {
4930 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
4931 winpty_entry[i].name)) == NULL)
4932 {
4933 if (verbose)
4934 EMSG2(_(e_loadfunc), winpty_entry[i].name);
4935 return FAIL;
4936 }
4937 }
4938
4939 return OK;
4940}
4941
4942/*
4943 * Create a new terminal of "rows" by "cols" cells.
4944 * Store a reference in "term".
4945 * Return OK or FAIL.
4946 */
4947 static int
4948term_and_job_init(
4949 term_T *term,
4950 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01004951 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004952 jobopt_T *opt)
4953{
4954 WCHAR *cmd_wchar = NULL;
4955 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004956 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004957 channel_T *channel = NULL;
4958 job_T *job = NULL;
4959 DWORD error;
4960 HANDLE jo = NULL;
4961 HANDLE child_process_handle;
4962 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01004963 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004964 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004965 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004966 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004967
4968 if (dyn_winpty_init(TRUE) == FAIL)
4969 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004970 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
4971 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004972
4973 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004974 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004975 cmd = argvar->vval.v_string;
4976 }
4977 else if (argvar->v_type == VAR_LIST)
4978 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004979 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004980 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004981 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004982 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004983 if (cmd == NULL || *cmd == NUL)
4984 {
4985 EMSG(_(e_invarg));
4986 goto failed;
4987 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004988
4989 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004990 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004991 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004992 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004993 if (opt->jo_cwd != NULL)
4994 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004995
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004996 win32_build_env(opt->jo_env, &ga_env, TRUE);
4997 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004998
4999 job = job_alloc();
5000 if (job == NULL)
5001 goto failed;
5002
5003 channel = add_channel();
5004 if (channel == NULL)
5005 goto failed;
5006
5007 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5008 if (term->tl_winpty_config == NULL)
5009 goto failed;
5010
5011 winpty_config_set_mouse_mode(term->tl_winpty_config,
5012 WINPTY_MOUSE_MODE_FORCE);
5013 winpty_config_set_initial_size(term->tl_winpty_config,
5014 term->tl_cols, term->tl_rows);
5015 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5016 if (term->tl_winpty == NULL)
5017 goto failed;
5018
5019 spawn_config = winpty_spawn_config_new(
5020 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5021 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5022 NULL,
5023 cmd_wchar,
5024 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005025 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005026 &winpty_err);
5027 if (spawn_config == NULL)
5028 goto failed;
5029
5030 channel = add_channel();
5031 if (channel == NULL)
5032 goto failed;
5033
5034 job = job_alloc();
5035 if (job == NULL)
5036 goto failed;
5037
5038 if (opt->jo_set & JO_IN_BUF)
5039 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5040
5041 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5042 &child_thread_handle, &error, &winpty_err))
5043 goto failed;
5044
5045 channel_set_pipes(channel,
5046 (sock_T)CreateFileW(
5047 winpty_conin_name(term->tl_winpty),
5048 GENERIC_WRITE, 0, NULL,
5049 OPEN_EXISTING, 0, NULL),
5050 (sock_T)CreateFileW(
5051 winpty_conout_name(term->tl_winpty),
5052 GENERIC_READ, 0, NULL,
5053 OPEN_EXISTING, 0, NULL),
5054 (sock_T)CreateFileW(
5055 winpty_conerr_name(term->tl_winpty),
5056 GENERIC_READ, 0, NULL,
5057 OPEN_EXISTING, 0, NULL));
5058
5059 /* Write lines with CR instead of NL. */
5060 channel->ch_write_text_mode = TRUE;
5061
5062 jo = CreateJobObject(NULL, NULL);
5063 if (jo == NULL)
5064 goto failed;
5065
5066 if (!AssignProcessToJobObject(jo, child_process_handle))
5067 {
5068 /* Failed, switch the way to terminate process with TerminateProcess. */
5069 CloseHandle(jo);
5070 jo = NULL;
5071 }
5072
5073 winpty_spawn_config_free(spawn_config);
5074 vim_free(cmd_wchar);
5075 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005076 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005077
5078 create_vterm(term, term->tl_rows, term->tl_cols);
5079
5080 channel_set_job(channel, job, opt);
5081 job_set_options(job, opt);
5082
5083 job->jv_channel = channel;
5084 job->jv_proc_info.hProcess = child_process_handle;
5085 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5086 job->jv_job_object = jo;
5087 job->jv_status = JOB_STARTED;
5088 job->jv_tty_in = utf16_to_enc(
5089 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5090 job->jv_tty_out = utf16_to_enc(
5091 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5092 ++job->jv_refcount;
5093 term->tl_job = job;
5094
5095 return OK;
5096
5097failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005098 ga_clear(&ga_cmd);
5099 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005100 vim_free(cmd_wchar);
5101 vim_free(cwd_wchar);
5102 if (spawn_config != NULL)
5103 winpty_spawn_config_free(spawn_config);
5104 if (channel != NULL)
5105 channel_clear(channel);
5106 if (job != NULL)
5107 {
5108 job->jv_channel = NULL;
5109 job_cleanup(job);
5110 }
5111 term->tl_job = NULL;
5112 if (jo != NULL)
5113 CloseHandle(jo);
5114 if (term->tl_winpty != NULL)
5115 winpty_free(term->tl_winpty);
5116 term->tl_winpty = NULL;
5117 if (term->tl_winpty_config != NULL)
5118 winpty_config_free(term->tl_winpty_config);
5119 term->tl_winpty_config = NULL;
5120 if (winpty_err != NULL)
5121 {
5122 char_u *msg = utf16_to_enc(
5123 (short_u *)winpty_error_msg(winpty_err), NULL);
5124
5125 EMSG(msg);
5126 winpty_error_free(winpty_err);
5127 }
5128 return FAIL;
5129}
5130
5131 static int
5132create_pty_only(term_T *term, jobopt_T *options)
5133{
5134 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5135 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5136 char in_name[80], out_name[80];
5137 channel_T *channel = NULL;
5138
5139 create_vterm(term, term->tl_rows, term->tl_cols);
5140
5141 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5142 GetCurrentProcessId(),
5143 curbuf->b_fnum);
5144 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5145 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5146 PIPE_UNLIMITED_INSTANCES,
5147 0, 0, NMPWAIT_NOWAIT, NULL);
5148 if (hPipeIn == INVALID_HANDLE_VALUE)
5149 goto failed;
5150
5151 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5152 GetCurrentProcessId(),
5153 curbuf->b_fnum);
5154 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5155 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5156 PIPE_UNLIMITED_INSTANCES,
5157 0, 0, 0, NULL);
5158 if (hPipeOut == INVALID_HANDLE_VALUE)
5159 goto failed;
5160
5161 ConnectNamedPipe(hPipeIn, NULL);
5162 ConnectNamedPipe(hPipeOut, NULL);
5163
5164 term->tl_job = job_alloc();
5165 if (term->tl_job == NULL)
5166 goto failed;
5167 ++term->tl_job->jv_refcount;
5168
5169 /* behave like the job is already finished */
5170 term->tl_job->jv_status = JOB_FINISHED;
5171
5172 channel = add_channel();
5173 if (channel == NULL)
5174 goto failed;
5175 term->tl_job->jv_channel = channel;
5176 channel->ch_keep_open = TRUE;
5177 channel->ch_named_pipe = TRUE;
5178
5179 channel_set_pipes(channel,
5180 (sock_T)hPipeIn,
5181 (sock_T)hPipeOut,
5182 (sock_T)hPipeOut);
5183 channel_set_job(channel, term->tl_job, options);
5184 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5185 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5186
5187 return OK;
5188
5189failed:
5190 if (hPipeIn != NULL)
5191 CloseHandle(hPipeIn);
5192 if (hPipeOut != NULL)
5193 CloseHandle(hPipeOut);
5194 return FAIL;
5195}
5196
5197/*
5198 * Free the terminal emulator part of "term".
5199 */
5200 static void
5201term_free_vterm(term_T *term)
5202{
5203 if (term->tl_winpty != NULL)
5204 winpty_free(term->tl_winpty);
5205 term->tl_winpty = NULL;
5206 if (term->tl_winpty_config != NULL)
5207 winpty_config_free(term->tl_winpty_config);
5208 term->tl_winpty_config = NULL;
5209 if (term->tl_vterm != NULL)
5210 vterm_free(term->tl_vterm);
5211 term->tl_vterm = NULL;
5212}
5213
5214/*
5215 * Request size to terminal.
5216 */
5217 static void
5218term_report_winsize(term_T *term, int rows, int cols)
5219{
5220 if (term->tl_winpty)
5221 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5222}
5223
5224 int
5225terminal_enabled(void)
5226{
5227 return dyn_winpty_init(FALSE) == OK;
5228}
5229
5230# else
5231
5232/**************************************
5233 * 3. Unix-like implementation.
5234 */
5235
5236/*
5237 * Create a new terminal of "rows" by "cols" cells.
5238 * Start job for "cmd".
5239 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005240 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005241 * Return OK or FAIL.
5242 */
5243 static int
5244term_and_job_init(
5245 term_T *term,
5246 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005247 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 jobopt_T *opt)
5249{
5250 create_vterm(term, term->tl_rows, term->tl_cols);
5251
Bram Moolenaar13568252018-03-16 20:46:58 +01005252 /* This may change a string in "argvar". */
5253 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005254 if (term->tl_job != NULL)
5255 ++term->tl_job->jv_refcount;
5256
5257 return term->tl_job != NULL
5258 && term->tl_job->jv_channel != NULL
5259 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5260}
5261
5262 static int
5263create_pty_only(term_T *term, jobopt_T *opt)
5264{
5265 create_vterm(term, term->tl_rows, term->tl_cols);
5266
5267 term->tl_job = job_alloc();
5268 if (term->tl_job == NULL)
5269 return FAIL;
5270 ++term->tl_job->jv_refcount;
5271
5272 /* behave like the job is already finished */
5273 term->tl_job->jv_status = JOB_FINISHED;
5274
5275 return mch_create_pty_channel(term->tl_job, opt);
5276}
5277
5278/*
5279 * Free the terminal emulator part of "term".
5280 */
5281 static void
5282term_free_vterm(term_T *term)
5283{
5284 if (term->tl_vterm != NULL)
5285 vterm_free(term->tl_vterm);
5286 term->tl_vterm = NULL;
5287}
5288
5289/*
5290 * Request size to terminal.
5291 */
5292 static void
5293term_report_winsize(term_T *term, int rows, int cols)
5294{
5295 /* Use an ioctl() to report the new window size to the job. */
5296 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5297 {
5298 int fd = -1;
5299 int part;
5300
5301 for (part = PART_OUT; part < PART_COUNT; ++part)
5302 {
5303 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5304 if (isatty(fd))
5305 break;
5306 }
5307 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5308 mch_signal_job(term->tl_job, (char_u *)"winch");
5309 }
5310}
5311
5312# endif
5313
5314#endif /* FEAT_TERMINAL */