blob: 7162d684c82cce46d233bcdae942b0e78b99ede0 [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 Moolenaar8fbaeb12018-03-25 18:20:17 +020041 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
Bram Moolenaar4a696342018-04-05 18:45:26 +020042 * redirection. Probably in call to channel_set_pipes().
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010043 * - Copy text in the vterm to the Vim buffer once in a while, so that
44 * completion works.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020045 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
46 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020047 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020048 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
49 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020050 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010051 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020052 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020053 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010054 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055 * - add test for giving error for invalid 'termsize' value.
56 * - support minimal size when 'termsize' is "rows*cols".
57 * - support minimal size when 'termsize' is empty?
58 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020059 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 * - For the GUI fill termios with default values, perhaps like pangoterm:
61 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020062 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
63 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020064 */
65
66#include "vim.h"
67
68#if defined(FEAT_TERMINAL) || defined(PROTO)
69
70#ifndef MIN
71# define MIN(x,y) ((x) < (y) ? (x) : (y))
72#endif
73#ifndef MAX
74# define MAX(x,y) ((x) > (y) ? (x) : (y))
75#endif
76
77#include "libvterm/include/vterm.h"
78
79/* This is VTermScreenCell without the characters, thus much smaller. */
80typedef struct {
81 VTermScreenCellAttrs attrs;
82 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010083 VTermColor fg;
84 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020085} cellattr_T;
86
87typedef struct sb_line_S {
88 int sb_cols; /* can differ per line */
89 cellattr_T *sb_cells; /* allocated */
90 cellattr_T sb_fill_attr; /* for short line */
91} sb_line_T;
92
93/* typedef term_T in structs.h */
94struct terminal_S {
95 term_T *tl_next;
96
97 VTerm *tl_vterm;
98 job_T *tl_job;
99 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100100#if defined(FEAT_GUI)
101 int tl_system; /* when non-zero used for :!cmd output */
102 int tl_toprow; /* row with first line of system terminal */
103#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200104
105 /* Set when setting the size of a vterm, reset after redrawing. */
106 int tl_vterm_size_changed;
107
108 /* used when tl_job is NULL and only a pty was created */
109 int tl_tty_fd;
110 char_u *tl_tty_in;
111 char_u *tl_tty_out;
112
113 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
114 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100115 int tl_finish;
116#define TL_FINISH_UNSET NUL
117#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
118#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
119#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200120 char_u *tl_opencmd;
121 char_u *tl_eof_chars;
122
123#ifdef WIN3264
124 void *tl_winpty_config;
125 void *tl_winpty;
126#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100127#if defined(FEAT_SESSION)
128 char_u *tl_command;
129#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100130 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131
132 /* last known vterm size */
133 int tl_rows;
134 int tl_cols;
135 /* vterm size does not follow window size */
136 int tl_rows_fixed;
137 int tl_cols_fixed;
138
139 char_u *tl_title; /* NULL or allocated */
140 char_u *tl_status_text; /* NULL or allocated */
141
142 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200143 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200144 int tl_dirty_row_end; /* row below last one to update */
145
146 garray_T tl_scrollback;
147 int tl_scrollback_scrolled;
148 cellattr_T tl_default_color;
149
Bram Moolenaard96ff162018-02-18 22:13:29 +0100150 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
151 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200153 VTermPos tl_cursor_pos;
154 int tl_cursor_visible;
155 int tl_cursor_blink;
156 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
157 char_u *tl_cursor_color; /* NULL or allocated */
158
159 int tl_using_altscreen;
160};
161
162#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
163#define TMODE_LOOP 2 /* CTRL-W N used */
164
165/*
166 * List of all active terminals.
167 */
168static term_T *first_term = NULL;
169
170/* Terminal active in terminal_loop(). */
171static term_T *in_terminal_loop = NULL;
172
173#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
174#define KEY_BUF_LEN 200
175
176/*
177 * Functions with separate implementation for MS-Windows and Unix-like systems.
178 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100179static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200180static int create_pty_only(term_T *term, jobopt_T *opt);
181static void term_report_winsize(term_T *term, int rows, int cols);
182static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100183#ifdef FEAT_GUI
184static void update_system_term(term_T *term);
185#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100187/* The character that we know (or assume) that the terminal expects for the
188 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100191/* "Terminal" highlight group colors. */
192static int term_default_cterm_fg = -1;
193static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaard317b382018-02-08 22:33:31 +0100195/* Store the last set and the desired cursor properties, so that we only update
196 * them when needed. Doing it unnecessary may result in flicker. */
197static char_u *last_set_cursor_color = (char_u *)"";
198static char_u *desired_cursor_color = (char_u *)"";
199static int last_set_cursor_shape = -1;
200static int desired_cursor_shape = -1;
201static int last_set_cursor_blink = -1;
202static int desired_cursor_blink = -1;
203
204
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200205/**************************************
206 * 1. Generic code for all systems.
207 */
208
209/*
210 * Determine the terminal size from 'termsize' and the current window.
211 * Assumes term->tl_rows and term->tl_cols are zero.
212 */
213 static void
214set_term_and_win_size(term_T *term)
215{
Bram Moolenaar13568252018-03-16 20:46:58 +0100216#ifdef FEAT_GUI
217 if (term->tl_system)
218 {
219 /* Use the whole screen for the system command. However, it will start
220 * at the command line and scroll up as needed, using tl_toprow. */
221 term->tl_rows = Rows;
222 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200223 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100224 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100225#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200226 if (*curwin->w_p_tms != NUL)
227 {
228 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
229
230 term->tl_rows = atoi((char *)curwin->w_p_tms);
231 term->tl_cols = atoi((char *)p);
232 }
233 if (term->tl_rows == 0)
234 term->tl_rows = curwin->w_height;
235 else
236 {
237 win_setheight_win(term->tl_rows, curwin);
238 term->tl_rows_fixed = TRUE;
239 }
240 if (term->tl_cols == 0)
241 term->tl_cols = curwin->w_width;
242 else
243 {
244 win_setwidth_win(term->tl_cols, curwin);
245 term->tl_cols_fixed = TRUE;
246 }
247}
248
249/*
250 * Initialize job options for a terminal job.
251 * Caller may overrule some of them.
252 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100253 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200254init_job_options(jobopt_T *opt)
255{
256 clear_job_options(opt);
257
258 opt->jo_mode = MODE_RAW;
259 opt->jo_out_mode = MODE_RAW;
260 opt->jo_err_mode = MODE_RAW;
261 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
262}
263
264/*
265 * Set job options mandatory for a terminal job.
266 */
267 static void
268setup_job_options(jobopt_T *opt, int rows, int cols)
269{
270 if (!(opt->jo_set & JO_OUT_IO))
271 {
272 /* Connect stdout to the terminal. */
273 opt->jo_io[PART_OUT] = JIO_BUFFER;
274 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
275 opt->jo_modifiable[PART_OUT] = 0;
276 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
277 }
278
279 if (!(opt->jo_set & JO_ERR_IO))
280 {
281 /* Connect stderr to the terminal. */
282 opt->jo_io[PART_ERR] = JIO_BUFFER;
283 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
284 opt->jo_modifiable[PART_ERR] = 0;
285 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
286 }
287
288 opt->jo_pty = TRUE;
289 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
290 opt->jo_term_rows = rows;
291 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
292 opt->jo_term_cols = cols;
293}
294
295/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100296 * Close a terminal buffer (and its window). Used when creating the terminal
297 * fails.
298 */
299 static void
300term_close_buffer(buf_T *buf, buf_T *old_curbuf)
301{
302 free_terminal(buf);
303 if (old_curbuf != NULL)
304 {
305 --curbuf->b_nwindows;
306 curbuf = old_curbuf;
307 curwin->w_buffer = curbuf;
308 ++curbuf->b_nwindows;
309 }
310
311 /* Wiping out the buffer will also close the window and call
312 * free_terminal(). */
313 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
314}
315
316/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200317 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100318 * Use either "argvar" or "argv", the other must be NULL.
319 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
320 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200321 * Returns NULL when failed.
322 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100323 buf_T *
324term_start(
325 typval_T *argvar,
326 char **argv,
327 jobopt_T *opt,
328 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200329{
330 exarg_T split_ea;
331 win_T *old_curwin = curwin;
332 term_T *term;
333 buf_T *old_curbuf = NULL;
334 int res;
335 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100336 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200337
338 if (check_restricted() || check_secure())
339 return NULL;
340
341 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
342 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
343 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
344 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
345 {
346 EMSG(_(e_invarg));
347 return NULL;
348 }
349
350 term = (term_T *)alloc_clear(sizeof(term_T));
351 if (term == NULL)
352 return NULL;
353 term->tl_dirty_row_end = MAX_ROW;
354 term->tl_cursor_visible = TRUE;
355 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
356 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100357#ifdef FEAT_GUI
358 term->tl_system = (flags & TERM_START_SYSTEM);
359#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200360 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
361
362 vim_memset(&split_ea, 0, sizeof(split_ea));
363 if (opt->jo_curwin)
364 {
365 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100366 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367 {
368 no_write_message();
369 vim_free(term);
370 return NULL;
371 }
372 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100373 ECMD_HIDE
374 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
375 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200376 {
377 vim_free(term);
378 return NULL;
379 }
380 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100381 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 {
383 buf_T *buf;
384
385 /* Create a new buffer without a window. Make it the current buffer for
386 * a moment to be able to do the initialisations. */
387 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
388 BLN_NEW | BLN_LISTED);
389 if (buf == NULL || ml_open(buf) == FAIL)
390 {
391 vim_free(term);
392 return NULL;
393 }
394 old_curbuf = curbuf;
395 --curbuf->b_nwindows;
396 curbuf = buf;
397 curwin->w_buffer = buf;
398 ++curbuf->b_nwindows;
399 }
400 else
401 {
402 /* Open a new window or tab. */
403 split_ea.cmdidx = CMD_new;
404 split_ea.cmd = (char_u *)"new";
405 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100406 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200407 {
408 split_ea.line2 = opt->jo_term_rows;
409 split_ea.addr_count = 1;
410 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100411 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200412 {
413 split_ea.line2 = opt->jo_term_cols;
414 split_ea.addr_count = 1;
415 }
416
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100417 if (vertical)
418 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200419 ex_splitview(&split_ea);
420 if (curwin == old_curwin)
421 {
422 /* split failed */
423 vim_free(term);
424 return NULL;
425 }
426 }
427 term->tl_buffer = curbuf;
428 curbuf->b_term = term;
429
430 if (!opt->jo_hidden)
431 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100432 /* Only one size was taken care of with :new, do the other one. With
433 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100434 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200435 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100436 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 win_setwidth(opt->jo_term_cols);
438 }
439
440 /* Link the new terminal in the list of active terminals. */
441 term->tl_next = first_term;
442 first_term = term;
443
444 if (opt->jo_term_name != NULL)
445 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100446 else if (argv != NULL)
447 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200448 else
449 {
450 int i;
451 size_t len;
452 char_u *cmd, *p;
453
454 if (argvar->v_type == VAR_STRING)
455 {
456 cmd = argvar->vval.v_string;
457 if (cmd == NULL)
458 cmd = (char_u *)"";
459 else if (STRCMP(cmd, "NONE") == 0)
460 cmd = (char_u *)"pty";
461 }
462 else if (argvar->v_type != VAR_LIST
463 || argvar->vval.v_list == NULL
464 || argvar->vval.v_list->lv_len < 1
465 || (cmd = get_tv_string_chk(
466 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
467 cmd = (char_u*)"";
468
469 len = STRLEN(cmd) + 10;
470 p = alloc((int)len);
471
472 for (i = 0; p != NULL; ++i)
473 {
474 /* Prepend a ! to the command name to avoid the buffer name equals
475 * the executable, otherwise ":w!" would overwrite it. */
476 if (i == 0)
477 vim_snprintf((char *)p, len, "!%s", cmd);
478 else
479 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
480 if (buflist_findname(p) == NULL)
481 {
482 vim_free(curbuf->b_ffname);
483 curbuf->b_ffname = p;
484 break;
485 }
486 }
487 }
488 curbuf->b_fname = curbuf->b_ffname;
489
490 if (opt->jo_term_opencmd != NULL)
491 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
492
493 if (opt->jo_eof_chars != NULL)
494 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
495
496 set_string_option_direct((char_u *)"buftype", -1,
497 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
498
499 /* Mark the buffer as not modifiable. It can only be made modifiable after
500 * the job finished. */
501 curbuf->b_p_ma = FALSE;
502
503 set_term_and_win_size(term);
504 setup_job_options(opt, term->tl_rows, term->tl_cols);
505
Bram Moolenaar13568252018-03-16 20:46:58 +0100506 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100507 return curbuf;
508
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100509#if defined(FEAT_SESSION)
510 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100511 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100512 {
513 term->tl_command = vim_strsave((char_u *)"NONE");
514 }
515 else if (argvar->v_type == VAR_STRING)
516 {
517 char_u *cmd = argvar->vval.v_string;
518
519 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
520 term->tl_command = vim_strsave(cmd);
521 }
522 else if (argvar->v_type == VAR_LIST
523 && argvar->vval.v_list != NULL
524 && argvar->vval.v_list->lv_len > 0)
525 {
526 garray_T ga;
527 listitem_T *item;
528
529 ga_init2(&ga, 1, 100);
530 for (item = argvar->vval.v_list->lv_first;
531 item != NULL; item = item->li_next)
532 {
533 char_u *s = get_tv_string_chk(&item->li_tv);
534 char_u *p;
535
536 if (s == NULL)
537 break;
538 p = vim_strsave_fnameescape(s, FALSE);
539 if (p == NULL)
540 break;
541 ga_concat(&ga, p);
542 vim_free(p);
543 ga_append(&ga, ' ');
544 }
545 if (item == NULL)
546 {
547 ga_append(&ga, NUL);
548 term->tl_command = ga.ga_data;
549 }
550 else
551 ga_clear(&ga);
552 }
553#endif
554
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100555 if (opt->jo_term_kill != NULL)
556 {
557 char_u *p = skiptowhite(opt->jo_term_kill);
558
559 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
560 }
561
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200562 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100563 if (argv == NULL
564 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 && argvar->vval.v_string != NULL
566 && STRCMP(argvar->vval.v_string, "NONE") == 0)
567 res = create_pty_only(term, opt);
568 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100569 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200570
571 newbuf = curbuf;
572 if (res == OK)
573 {
574 /* Get and remember the size we ended up with. Update the pty. */
575 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
576 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100577#ifdef FEAT_GUI
578 if (term->tl_system)
579 {
580 /* display first line below typed command */
581 term->tl_toprow = msg_row + 1;
582 term->tl_dirty_row_end = 0;
583 }
584#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200585
586 /* Make sure we don't get stuck on sending keys to the job, it leads to
587 * a deadlock if the job is waiting for Vim to read. */
588 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
589
Bram Moolenaar13568252018-03-16 20:46:58 +0100590 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100591 {
592 ++curbuf->b_locked;
593 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
594 --curbuf->b_locked;
595 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100596 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200597 {
598 --curbuf->b_nwindows;
599 curbuf = old_curbuf;
600 curwin->w_buffer = curbuf;
601 ++curbuf->b_nwindows;
602 }
603 }
604 else
605 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100606 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200607 return NULL;
608 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100609
Bram Moolenaar13568252018-03-16 20:46:58 +0100610 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200611 return newbuf;
612}
613
614/*
615 * ":terminal": open a terminal window and execute a job in it.
616 */
617 void
618ex_terminal(exarg_T *eap)
619{
620 typval_T argvar[2];
621 jobopt_T opt;
622 char_u *cmd;
623 char_u *tofree = NULL;
624
625 init_job_options(&opt);
626
627 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100628 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200629 {
630 char_u *p, *ep;
631
632 cmd += 2;
633 p = skiptowhite(cmd);
634 ep = vim_strchr(cmd, '=');
635 if (ep != NULL && ep < p)
636 p = ep;
637
638 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
639 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100640 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
641 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200642 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
643 opt.jo_term_finish = 'o';
644 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
645 opt.jo_curwin = 1;
646 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
647 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100648 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
649 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100650 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
651 && ep != NULL)
652 {
653 opt.jo_set2 |= JO2_TERM_KILL;
654 opt.jo_term_kill = ep + 1;
655 p = skiptowhite(cmd);
656 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
658 && ep != NULL && isdigit(ep[1]))
659 {
660 opt.jo_set2 |= JO2_TERM_ROWS;
661 opt.jo_term_rows = atoi((char *)ep + 1);
662 p = skiptowhite(cmd);
663 }
664 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
665 && ep != NULL && isdigit(ep[1]))
666 {
667 opt.jo_set2 |= JO2_TERM_COLS;
668 opt.jo_term_cols = atoi((char *)ep + 1);
669 p = skiptowhite(cmd);
670 }
671 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
672 && ep != NULL)
673 {
674 char_u *buf = NULL;
675 char_u *keys;
676
677 p = skiptowhite(cmd);
678 *p = NUL;
679 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
680 opt.jo_set2 |= JO2_EOF_CHARS;
681 opt.jo_eof_chars = vim_strsave(keys);
682 vim_free(buf);
683 *p = ' ';
684 }
685 else
686 {
687 if (*p)
688 *p = NUL;
689 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100690 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200691 }
692 cmd = skipwhite(p);
693 }
694 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100695 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200696 /* Make a copy of 'shell', an autocommand may change the option. */
697 tofree = cmd = vim_strsave(p_sh);
698
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100699 /* default to close when the shell exits */
700 if (opt.jo_term_finish == NUL)
701 opt.jo_term_finish = 'c';
702 }
703
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200704 if (eap->addr_count > 0)
705 {
706 /* Write lines from current buffer to the job. */
707 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
708 opt.jo_io[PART_IN] = JIO_BUFFER;
709 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
710 opt.jo_in_top = eap->line1;
711 opt.jo_in_bot = eap->line2;
712 }
713
714 argvar[0].v_type = VAR_STRING;
715 argvar[0].vval.v_string = cmd;
716 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100717 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100719
720theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200721 vim_free(opt.jo_eof_chars);
722}
723
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100724#if defined(FEAT_SESSION) || defined(PROTO)
725/*
726 * Write a :terminal command to the session file to restore the terminal in
727 * window "wp".
728 * Return FAIL if writing fails.
729 */
730 int
731term_write_session(FILE *fd, win_T *wp)
732{
733 term_T *term = wp->w_buffer->b_term;
734
735 /* Create the terminal and run the command. This is not without
736 * risk, but let's assume the user only creates a session when this
737 * will be OK. */
738 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
739 term->tl_cols, term->tl_rows) < 0)
740 return FAIL;
741 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
742 return FAIL;
743
744 return put_eol(fd);
745}
746
747/*
748 * Return TRUE if "buf" has a terminal that should be restored.
749 */
750 int
751term_should_restore(buf_T *buf)
752{
753 term_T *term = buf->b_term;
754
755 return term != NULL && (term->tl_command == NULL
756 || STRCMP(term->tl_command, "NONE") != 0);
757}
758#endif
759
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200760/*
761 * Free the scrollback buffer for "term".
762 */
763 static void
764free_scrollback(term_T *term)
765{
766 int i;
767
768 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
769 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
770 ga_clear(&term->tl_scrollback);
771}
772
773/*
774 * Free a terminal and everything it refers to.
775 * Kills the job if there is one.
776 * Called when wiping out a buffer.
777 */
778 void
779free_terminal(buf_T *buf)
780{
781 term_T *term = buf->b_term;
782 term_T *tp;
783
784 if (term == NULL)
785 return;
786 if (first_term == term)
787 first_term = term->tl_next;
788 else
789 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
790 if (tp->tl_next == term)
791 {
792 tp->tl_next = term->tl_next;
793 break;
794 }
795
796 if (term->tl_job != NULL)
797 {
798 if (term->tl_job->jv_status != JOB_ENDED
799 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100800 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801 job_stop(term->tl_job, NULL, "kill");
802 job_unref(term->tl_job);
803 }
804
805 free_scrollback(term);
806
807 term_free_vterm(term);
808 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100809#ifdef FEAT_SESSION
810 vim_free(term->tl_command);
811#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100812 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 vim_free(term->tl_status_text);
814 vim_free(term->tl_opencmd);
815 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100816 if (desired_cursor_color == term->tl_cursor_color)
817 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818 vim_free(term->tl_cursor_color);
819 vim_free(term);
820 buf->b_term = NULL;
821 if (in_terminal_loop == term)
822 in_terminal_loop = NULL;
823}
824
825/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100826 * Get the part that is connected to the tty. Normally this is PART_IN, but
827 * when writing buffer lines to the job it can be another. This makes it
828 * possible to do "1,5term vim -".
829 */
830 static ch_part_T
831get_tty_part(term_T *term)
832{
833#ifdef UNIX
834 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
835 int i;
836
837 for (i = 0; i < 3; ++i)
838 {
839 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
840
841 if (isatty(fd))
842 return parts[i];
843 }
844#endif
845 return PART_IN;
846}
847
848/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200849 * Write job output "msg[len]" to the vterm.
850 */
851 static void
852term_write_job_output(term_T *term, char_u *msg, size_t len)
853{
854 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100855 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200856
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100857 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200858
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100859 /* flush vterm buffer when vterm responded to control sequence */
860 if (prevlen != vterm_output_get_buffer_current(vterm))
861 {
862 char buf[KEY_BUF_LEN];
863 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
864
865 if (curlen > 0)
866 channel_send(term->tl_job->jv_channel, get_tty_part(term),
867 (char_u *)buf, (int)curlen, NULL);
868 }
869
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200870 /* this invokes the damage callbacks */
871 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
872}
873
874 static void
875update_cursor(term_T *term, int redraw)
876{
877 if (term->tl_normal_mode)
878 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100879#ifdef FEAT_GUI
880 if (term->tl_system)
881 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
882 term->tl_cursor_pos.col);
883 else
884#endif
885 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200886 if (redraw)
887 {
888 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
889 cursor_on();
890 out_flush();
891#ifdef FEAT_GUI
892 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100893 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200894 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100895 gui_mch_flush();
896 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200897#endif
898 }
899}
900
901/*
902 * Invoked when "msg" output from a job was received. Write it to the terminal
903 * of "buffer".
904 */
905 void
906write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
907{
908 size_t len = STRLEN(msg);
909 term_T *term = buffer->b_term;
910
911 if (term->tl_vterm == NULL)
912 {
913 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
914 return;
915 }
916 ch_log(channel, "writing %d bytes to terminal", (int)len);
917 term_write_job_output(term, msg, len);
918
Bram Moolenaar13568252018-03-16 20:46:58 +0100919#ifdef FEAT_GUI
920 if (term->tl_system)
921 {
922 /* show system output, scrolling up the screen as needed */
923 update_system_term(term);
924 update_cursor(term, TRUE);
925 }
926 else
927#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200928 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
929 * contents, thus no screen update is needed. */
930 if (!term->tl_normal_mode)
931 {
932 /* TODO: only update once in a while. */
933 ch_log(term->tl_job->jv_channel, "updating screen");
934 if (buffer == curbuf)
935 {
936 update_screen(0);
937 update_cursor(term, TRUE);
938 }
939 else
940 redraw_after_callback(TRUE);
941 }
942}
943
944/*
945 * Send a mouse position and click to the vterm
946 */
947 static int
948term_send_mouse(VTerm *vterm, int button, int pressed)
949{
950 VTermModifier mod = VTERM_MOD_NONE;
951
952 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200953 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100954 if (button != 0)
955 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200956 return TRUE;
957}
958
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100959static int enter_mouse_col = -1;
960static int enter_mouse_row = -1;
961
962/*
963 * Handle a mouse click, drag or release.
964 * Return TRUE when a mouse event is sent to the terminal.
965 */
966 static int
967term_mouse_click(VTerm *vterm, int key)
968{
969#if defined(FEAT_CLIPBOARD)
970 /* For modeless selection mouse drag and release events are ignored, unless
971 * they are preceded with a mouse down event */
972 static int ignore_drag_release = TRUE;
973 VTermMouseState mouse_state;
974
975 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
976 if (mouse_state.flags == 0)
977 {
978 /* Terminal is not using the mouse, use modeless selection. */
979 switch (key)
980 {
981 case K_LEFTDRAG:
982 case K_LEFTRELEASE:
983 case K_RIGHTDRAG:
984 case K_RIGHTRELEASE:
985 /* Ignore drag and release events when the button-down wasn't
986 * seen before. */
987 if (ignore_drag_release)
988 {
989 int save_mouse_col, save_mouse_row;
990
991 if (enter_mouse_col < 0)
992 break;
993
994 /* mouse click in the window gave us focus, handle that
995 * click now */
996 save_mouse_col = mouse_col;
997 save_mouse_row = mouse_row;
998 mouse_col = enter_mouse_col;
999 mouse_row = enter_mouse_row;
1000 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1001 mouse_col = save_mouse_col;
1002 mouse_row = save_mouse_row;
1003 }
1004 /* FALLTHROUGH */
1005 case K_LEFTMOUSE:
1006 case K_RIGHTMOUSE:
1007 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1008 ignore_drag_release = TRUE;
1009 else
1010 ignore_drag_release = FALSE;
1011 /* Should we call mouse_has() here? */
1012 if (clip_star.available)
1013 {
1014 int button, is_click, is_drag;
1015
1016 button = get_mouse_button(KEY2TERMCAP1(key),
1017 &is_click, &is_drag);
1018 if (mouse_model_popup() && button == MOUSE_LEFT
1019 && (mod_mask & MOD_MASK_SHIFT))
1020 {
1021 /* Translate shift-left to right button. */
1022 button = MOUSE_RIGHT;
1023 mod_mask &= ~MOD_MASK_SHIFT;
1024 }
1025 clip_modeless(button, is_click, is_drag);
1026 }
1027 break;
1028
1029 case K_MIDDLEMOUSE:
1030 if (clip_star.available)
1031 insert_reg('*', TRUE);
1032 break;
1033 }
1034 enter_mouse_col = -1;
1035 return FALSE;
1036 }
1037#endif
1038 enter_mouse_col = -1;
1039
1040 switch (key)
1041 {
1042 case K_LEFTMOUSE:
1043 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1044 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1045 case K_LEFTRELEASE:
1046 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1047 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1048 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1049 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1050 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1051 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1052 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1053 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1054 }
1055 return TRUE;
1056}
1057
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001058/*
1059 * Convert typed key "c" into bytes to send to the job.
1060 * Return the number of bytes in "buf".
1061 */
1062 static int
1063term_convert_key(term_T *term, int c, char *buf)
1064{
1065 VTerm *vterm = term->tl_vterm;
1066 VTermKey key = VTERM_KEY_NONE;
1067 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001068 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001069
1070 switch (c)
1071 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001072 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1073
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001074 /* don't use VTERM_KEY_BACKSPACE, it always
1075 * becomes 0x7f DEL */
1076 case K_BS: c = term_backspace_char; break;
1077
1078 case ESC: key = VTERM_KEY_ESCAPE; break;
1079 case K_DEL: key = VTERM_KEY_DEL; break;
1080 case K_DOWN: key = VTERM_KEY_DOWN; break;
1081 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1082 key = VTERM_KEY_DOWN; break;
1083 case K_END: key = VTERM_KEY_END; break;
1084 case K_S_END: mod = VTERM_MOD_SHIFT;
1085 key = VTERM_KEY_END; break;
1086 case K_C_END: mod = VTERM_MOD_CTRL;
1087 key = VTERM_KEY_END; break;
1088 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1089 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1090 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1091 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1092 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1093 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1094 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1095 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1096 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1097 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1098 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1099 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1100 case K_HOME: key = VTERM_KEY_HOME; break;
1101 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1102 key = VTERM_KEY_HOME; break;
1103 case K_C_HOME: mod = VTERM_MOD_CTRL;
1104 key = VTERM_KEY_HOME; break;
1105 case K_INS: key = VTERM_KEY_INS; break;
1106 case K_K0: key = VTERM_KEY_KP_0; break;
1107 case K_K1: key = VTERM_KEY_KP_1; break;
1108 case K_K2: key = VTERM_KEY_KP_2; break;
1109 case K_K3: key = VTERM_KEY_KP_3; break;
1110 case K_K4: key = VTERM_KEY_KP_4; break;
1111 case K_K5: key = VTERM_KEY_KP_5; break;
1112 case K_K6: key = VTERM_KEY_KP_6; break;
1113 case K_K7: key = VTERM_KEY_KP_7; break;
1114 case K_K8: key = VTERM_KEY_KP_8; break;
1115 case K_K9: key = VTERM_KEY_KP_9; break;
1116 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1117 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1118 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1119 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1120 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1121 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1122 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1123 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1124 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1125 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1126 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1127 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1128 case K_LEFT: key = VTERM_KEY_LEFT; break;
1129 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1130 key = VTERM_KEY_LEFT; break;
1131 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1132 key = VTERM_KEY_LEFT; break;
1133 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1134 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1135 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1136 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1137 key = VTERM_KEY_RIGHT; break;
1138 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1139 key = VTERM_KEY_RIGHT; break;
1140 case K_UP: key = VTERM_KEY_UP; break;
1141 case K_S_UP: mod = VTERM_MOD_SHIFT;
1142 key = VTERM_KEY_UP; break;
1143 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001144 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1145 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001146
Bram Moolenaara42ad572017-11-16 13:08:04 +01001147 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1148 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001149 case K_MOUSELEFT: /* TODO */ return 0;
1150 case K_MOUSERIGHT: /* TODO */ return 0;
1151
1152 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001153 case K_LEFTMOUSE_NM:
1154 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001155 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001156 case K_LEFTRELEASE_NM:
1157 case K_MOUSEMOVE:
1158 case K_MIDDLEMOUSE:
1159 case K_MIDDLEDRAG:
1160 case K_MIDDLERELEASE:
1161 case K_RIGHTMOUSE:
1162 case K_RIGHTDRAG:
1163 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1164 return 0;
1165 other = TRUE;
1166 break;
1167
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001168 case K_X1MOUSE: /* TODO */ return 0;
1169 case K_X1DRAG: /* TODO */ return 0;
1170 case K_X1RELEASE: /* TODO */ return 0;
1171 case K_X2MOUSE: /* TODO */ return 0;
1172 case K_X2DRAG: /* TODO */ return 0;
1173 case K_X2RELEASE: /* TODO */ return 0;
1174
1175 case K_IGNORE: return 0;
1176 case K_NOP: return 0;
1177 case K_UNDO: return 0;
1178 case K_HELP: return 0;
1179 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1180 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1181 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1182 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1183 case K_SELECT: return 0;
1184#ifdef FEAT_GUI
1185 case K_VER_SCROLLBAR: return 0;
1186 case K_HOR_SCROLLBAR: return 0;
1187#endif
1188#ifdef FEAT_GUI_TABLINE
1189 case K_TABLINE: return 0;
1190 case K_TABMENU: return 0;
1191#endif
1192#ifdef FEAT_NETBEANS_INTG
1193 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1194#endif
1195#ifdef FEAT_DND
1196 case K_DROP: return 0;
1197#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001198 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001199 case K_PS: vterm_keyboard_start_paste(vterm);
1200 other = TRUE;
1201 break;
1202 case K_PE: vterm_keyboard_end_paste(vterm);
1203 other = TRUE;
1204 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001205 }
1206
1207 /*
1208 * Convert special keys to vterm keys:
1209 * - Write keys to vterm: vterm_keyboard_key()
1210 * - Write output to channel.
1211 * TODO: use mod_mask
1212 */
1213 if (key != VTERM_KEY_NONE)
1214 /* Special key, let vterm convert it. */
1215 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001216 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001217 /* Normal character, let vterm convert it. */
1218 vterm_keyboard_unichar(vterm, c, mod);
1219
1220 /* Read back the converted escape sequence. */
1221 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1222}
1223
1224/*
1225 * Return TRUE if the job for "term" is still running.
1226 */
1227 int
1228term_job_running(term_T *term)
1229{
1230 /* Also consider the job finished when the channel is closed, to avoid a
1231 * race condition when updating the title. */
1232 return term != NULL
1233 && term->tl_job != NULL
1234 && channel_is_open(term->tl_job->jv_channel)
1235 && (term->tl_job->jv_status == JOB_STARTED
1236 || term->tl_job->jv_channel->ch_keep_open);
1237}
1238
1239/*
1240 * Return TRUE if "term" has an active channel and used ":term NONE".
1241 */
1242 int
1243term_none_open(term_T *term)
1244{
1245 /* Also consider the job finished when the channel is closed, to avoid a
1246 * race condition when updating the title. */
1247 return term != NULL
1248 && term->tl_job != NULL
1249 && channel_is_open(term->tl_job->jv_channel)
1250 && term->tl_job->jv_channel->ch_keep_open;
1251}
1252
1253/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001254 * Used when exiting: kill the job in "buf" if so desired.
1255 * Return OK when the job finished.
1256 * Return FAIL when the job is still running.
1257 */
1258 int
1259term_try_stop_job(buf_T *buf)
1260{
1261 int count;
1262 char *how = (char *)buf->b_term->tl_kill;
1263
1264#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1265 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1266 {
1267 char_u buff[DIALOG_MSG_SIZE];
1268 int ret;
1269
1270 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1271 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1272 if (ret == VIM_YES)
1273 how = "kill";
1274 else if (ret == VIM_CANCEL)
1275 return FAIL;
1276 }
1277#endif
1278 if (how == NULL || *how == NUL)
1279 return FAIL;
1280
1281 job_stop(buf->b_term->tl_job, NULL, how);
1282
1283 /* wait for up to a second for the job to die */
1284 for (count = 0; count < 100; ++count)
1285 {
1286 /* buffer, terminal and job may be cleaned up while waiting */
1287 if (!buf_valid(buf)
1288 || buf->b_term == NULL
1289 || buf->b_term->tl_job == NULL)
1290 return OK;
1291
1292 /* call job_status() to update jv_status */
1293 job_status(buf->b_term->tl_job);
1294 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1295 return OK;
1296 ui_delay(10L, FALSE);
1297 mch_check_messages();
1298 parse_queued_messages();
1299 }
1300 return FAIL;
1301}
1302
1303/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304 * Add the last line of the scrollback buffer to the buffer in the window.
1305 */
1306 static void
1307add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1308{
1309 buf_T *buf = term->tl_buffer;
1310 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1311 linenr_T lnum = buf->b_ml.ml_line_count;
1312
1313#ifdef WIN3264
1314 if (!enc_utf8 && enc_codepage > 0)
1315 {
1316 WCHAR *ret = NULL;
1317 int length = 0;
1318
1319 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1320 &ret, &length);
1321 if (ret != NULL)
1322 {
1323 WideCharToMultiByte_alloc(enc_codepage, 0,
1324 ret, length, (char **)&text, &len, 0, 0);
1325 vim_free(ret);
1326 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1327 vim_free(text);
1328 }
1329 }
1330 else
1331#endif
1332 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1333 if (empty)
1334 {
1335 /* Delete the empty line that was in the empty buffer. */
1336 curbuf = buf;
1337 ml_delete(1, FALSE);
1338 curbuf = curwin->w_buffer;
1339 }
1340}
1341
1342 static void
1343cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1344{
1345 attr->width = cell->width;
1346 attr->attrs = cell->attrs;
1347 attr->fg = cell->fg;
1348 attr->bg = cell->bg;
1349}
1350
1351 static int
1352equal_celattr(cellattr_T *a, cellattr_T *b)
1353{
1354 /* Comparing the colors should be sufficient. */
1355 return a->fg.red == b->fg.red
1356 && a->fg.green == b->fg.green
1357 && a->fg.blue == b->fg.blue
1358 && a->bg.red == b->bg.red
1359 && a->bg.green == b->bg.green
1360 && a->bg.blue == b->bg.blue;
1361}
1362
Bram Moolenaard96ff162018-02-18 22:13:29 +01001363/*
1364 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1365 * line at this position. Otherwise at the end.
1366 */
1367 static int
1368add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1369{
1370 if (ga_grow(&term->tl_scrollback, 1) == OK)
1371 {
1372 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1373 + term->tl_scrollback.ga_len;
1374
1375 if (lnum > 0)
1376 {
1377 int i;
1378
1379 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1380 {
1381 *line = *(line - 1);
1382 --line;
1383 }
1384 }
1385 line->sb_cols = 0;
1386 line->sb_cells = NULL;
1387 line->sb_fill_attr = *fill_attr;
1388 ++term->tl_scrollback.ga_len;
1389 return OK;
1390 }
1391 return FALSE;
1392}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001393
1394/*
1395 * Add the current lines of the terminal to scrollback and to the buffer.
1396 * Called after the job has ended and when switching to Terminal-Normal mode.
1397 */
1398 static void
1399move_terminal_to_buffer(term_T *term)
1400{
1401 win_T *wp;
1402 int len;
1403 int lines_skipped = 0;
1404 VTermPos pos;
1405 VTermScreenCell cell;
1406 cellattr_T fill_attr, new_fill_attr;
1407 cellattr_T *p;
1408 VTermScreen *screen;
1409
1410 if (term->tl_vterm == NULL)
1411 return;
1412 screen = vterm_obtain_screen(term->tl_vterm);
1413 fill_attr = new_fill_attr = term->tl_default_color;
1414
1415 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1416 {
1417 len = 0;
1418 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1419 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1420 && cell.chars[0] != NUL)
1421 {
1422 len = pos.col + 1;
1423 new_fill_attr = term->tl_default_color;
1424 }
1425 else
1426 /* Assume the last attr is the filler attr. */
1427 cell2cellattr(&cell, &new_fill_attr);
1428
1429 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1430 ++lines_skipped;
1431 else
1432 {
1433 while (lines_skipped > 0)
1434 {
1435 /* Line was skipped, add an empty line. */
1436 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001437 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001438 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001439 }
1440
1441 if (len == 0)
1442 p = NULL;
1443 else
1444 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1445 if ((p != NULL || len == 0)
1446 && ga_grow(&term->tl_scrollback, 1) == OK)
1447 {
1448 garray_T ga;
1449 int width;
1450 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1451 + term->tl_scrollback.ga_len;
1452
1453 ga_init2(&ga, 1, 100);
1454 for (pos.col = 0; pos.col < len; pos.col += width)
1455 {
1456 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1457 {
1458 width = 1;
1459 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1460 if (ga_grow(&ga, 1) == OK)
1461 ga.ga_len += utf_char2bytes(' ',
1462 (char_u *)ga.ga_data + ga.ga_len);
1463 }
1464 else
1465 {
1466 width = cell.width;
1467
1468 cell2cellattr(&cell, &p[pos.col]);
1469
1470 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1471 {
1472 int i;
1473 int c;
1474
1475 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1476 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1477 (char_u *)ga.ga_data + ga.ga_len);
1478 }
1479 }
1480 }
1481 line->sb_cols = len;
1482 line->sb_cells = p;
1483 line->sb_fill_attr = new_fill_attr;
1484 fill_attr = new_fill_attr;
1485 ++term->tl_scrollback.ga_len;
1486
1487 if (ga_grow(&ga, 1) == FAIL)
1488 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1489 else
1490 {
1491 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1492 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1493 }
1494 ga_clear(&ga);
1495 }
1496 else
1497 vim_free(p);
1498 }
1499 }
1500
1501 /* Obtain the current background color. */
1502 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1503 &term->tl_default_color.fg, &term->tl_default_color.bg);
1504
1505 FOR_ALL_WINDOWS(wp)
1506 {
1507 if (wp->w_buffer == term->tl_buffer)
1508 {
1509 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1510 wp->w_cursor.col = 0;
1511 wp->w_valid = 0;
1512 if (wp->w_cursor.lnum >= wp->w_height)
1513 {
1514 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1515
1516 if (wp->w_topline < min_topline)
1517 wp->w_topline = min_topline;
1518 }
1519 redraw_win_later(wp, NOT_VALID);
1520 }
1521 }
1522}
1523
1524 static void
1525set_terminal_mode(term_T *term, int normal_mode)
1526{
1527 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001528 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001529 if (term->tl_buffer == curbuf)
1530 maketitle();
1531}
1532
1533/*
1534 * Called after the job if finished and Terminal mode is not active:
1535 * Move the vterm contents into the scrollback buffer and free the vterm.
1536 */
1537 static void
1538cleanup_vterm(term_T *term)
1539{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001540 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001541 move_terminal_to_buffer(term);
1542 term_free_vterm(term);
1543 set_terminal_mode(term, FALSE);
1544}
1545
1546/*
1547 * Switch from Terminal-Job mode to Terminal-Normal mode.
1548 * Suspends updating the terminal window.
1549 */
1550 static void
1551term_enter_normal_mode(void)
1552{
1553 term_T *term = curbuf->b_term;
1554
1555 /* Append the current terminal contents to the buffer. */
1556 move_terminal_to_buffer(term);
1557
1558 set_terminal_mode(term, TRUE);
1559
1560 /* Move the window cursor to the position of the cursor in the
1561 * terminal. */
1562 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1563 + term->tl_cursor_pos.row + 1;
1564 check_cursor();
1565 coladvance(term->tl_cursor_pos.col);
1566
1567 /* Display the same lines as in the terminal. */
1568 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1569}
1570
1571/*
1572 * Returns TRUE if the current window contains a terminal and we are in
1573 * Terminal-Normal mode.
1574 */
1575 int
1576term_in_normal_mode(void)
1577{
1578 term_T *term = curbuf->b_term;
1579
1580 return term != NULL && term->tl_normal_mode;
1581}
1582
1583/*
1584 * Switch from Terminal-Normal mode to Terminal-Job mode.
1585 * Restores updating the terminal window.
1586 */
1587 void
1588term_enter_job_mode()
1589{
1590 term_T *term = curbuf->b_term;
1591 sb_line_T *line;
1592 garray_T *gap;
1593
1594 /* Remove the terminal contents from the scrollback and the buffer. */
1595 gap = &term->tl_scrollback;
1596 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1597 && gap->ga_len > 0)
1598 {
1599 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1600 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1601 vim_free(line->sb_cells);
1602 --gap->ga_len;
1603 }
1604 check_cursor();
1605
1606 set_terminal_mode(term, FALSE);
1607
1608 if (term->tl_channel_closed)
1609 cleanup_vterm(term);
1610 redraw_buf_and_status_later(curbuf, NOT_VALID);
1611}
1612
1613/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001614 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 * Note: while waiting a terminal may be closed and freed if the channel is
1616 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617 */
1618 static int
1619term_vgetc()
1620{
1621 int c;
1622 int save_State = State;
1623
1624 State = TERMINAL;
1625 got_int = FALSE;
1626#ifdef WIN3264
1627 ctrl_break_was_pressed = FALSE;
1628#endif
1629 c = vgetc();
1630 got_int = FALSE;
1631 State = save_State;
1632 return c;
1633}
1634
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001635static int mouse_was_outside = FALSE;
1636
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001638 * Send keys to terminal.
1639 * Return FAIL when the key needs to be handled in Normal mode.
1640 * Return OK when the key was dropped or sent to the terminal.
1641 */
1642 int
1643send_keys_to_term(term_T *term, int c, int typed)
1644{
1645 char msg[KEY_BUF_LEN];
1646 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001647 int dragging_outside = FALSE;
1648
1649 /* Catch keys that need to be handled as in Normal mode. */
1650 switch (c)
1651 {
1652 case NUL:
1653 case K_ZERO:
1654 if (typed)
1655 stuffcharReadbuff(c);
1656 return FAIL;
1657
1658 case K_IGNORE:
1659 return FAIL;
1660
1661 case K_LEFTDRAG:
1662 case K_MIDDLEDRAG:
1663 case K_RIGHTDRAG:
1664 case K_X1DRAG:
1665 case K_X2DRAG:
1666 dragging_outside = mouse_was_outside;
1667 /* FALLTHROUGH */
1668 case K_LEFTMOUSE:
1669 case K_LEFTMOUSE_NM:
1670 case K_LEFTRELEASE:
1671 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001672 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 case K_MIDDLEMOUSE:
1674 case K_MIDDLERELEASE:
1675 case K_RIGHTMOUSE:
1676 case K_RIGHTRELEASE:
1677 case K_X1MOUSE:
1678 case K_X1RELEASE:
1679 case K_X2MOUSE:
1680 case K_X2RELEASE:
1681
1682 case K_MOUSEUP:
1683 case K_MOUSEDOWN:
1684 case K_MOUSELEFT:
1685 case K_MOUSERIGHT:
1686 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001687 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001688 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001689 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001690 || dragging_outside)
1691 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001692 /* click or scroll outside the current window or on status line
1693 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 if (typed)
1695 {
1696 stuffcharReadbuff(c);
1697 mouse_was_outside = TRUE;
1698 }
1699 return FAIL;
1700 }
1701 }
1702 if (typed)
1703 mouse_was_outside = FALSE;
1704
1705 /* Convert the typed key to a sequence of bytes for the job. */
1706 len = term_convert_key(term, c, msg);
1707 if (len > 0)
1708 /* TODO: if FAIL is returned, stop? */
1709 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1710 (char_u *)msg, (int)len, NULL);
1711
1712 return OK;
1713}
1714
1715 static void
1716position_cursor(win_T *wp, VTermPos *pos)
1717{
1718 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1719 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1720 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1721}
1722
1723/*
1724 * Handle CTRL-W "": send register contents to the job.
1725 */
1726 static void
1727term_paste_register(int prev_c UNUSED)
1728{
1729 int c;
1730 list_T *l;
1731 listitem_T *item;
1732 long reglen = 0;
1733 int type;
1734
1735#ifdef FEAT_CMDL_INFO
1736 if (add_to_showcmd(prev_c))
1737 if (add_to_showcmd('"'))
1738 out_flush();
1739#endif
1740 c = term_vgetc();
1741#ifdef FEAT_CMDL_INFO
1742 clear_showcmd();
1743#endif
1744 if (!term_use_loop())
1745 /* job finished while waiting for a character */
1746 return;
1747
1748 /* CTRL-W "= prompt for expression to evaluate. */
1749 if (c == '=' && get_expr_register() != '=')
1750 return;
1751 if (!term_use_loop())
1752 /* job finished while waiting for a character */
1753 return;
1754
1755 l = (list_T *)get_reg_contents(c, GREG_LIST);
1756 if (l != NULL)
1757 {
1758 type = get_reg_type(c, &reglen);
1759 for (item = l->lv_first; item != NULL; item = item->li_next)
1760 {
1761 char_u *s = get_tv_string(&item->li_tv);
1762#ifdef WIN3264
1763 char_u *tmp = s;
1764
1765 if (!enc_utf8 && enc_codepage > 0)
1766 {
1767 WCHAR *ret = NULL;
1768 int length = 0;
1769
1770 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1771 (int)STRLEN(s), &ret, &length);
1772 if (ret != NULL)
1773 {
1774 WideCharToMultiByte_alloc(CP_UTF8, 0,
1775 ret, length, (char **)&s, &length, 0, 0);
1776 vim_free(ret);
1777 }
1778 }
1779#endif
1780 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1781 s, (int)STRLEN(s), NULL);
1782#ifdef WIN3264
1783 if (tmp != s)
1784 vim_free(s);
1785#endif
1786
1787 if (item->li_next != NULL || type == MLINE)
1788 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1789 (char_u *)"\r", 1, NULL);
1790 }
1791 list_free(l);
1792 }
1793}
1794
1795#if defined(FEAT_GUI) || defined(PROTO)
1796/*
1797 * Return TRUE when the cursor of the terminal should be displayed.
1798 */
1799 int
1800terminal_is_active()
1801{
1802 return in_terminal_loop != NULL;
1803}
1804
1805 cursorentry_T *
1806term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1807{
1808 term_T *term = in_terminal_loop;
1809 static cursorentry_T entry;
1810
1811 vim_memset(&entry, 0, sizeof(entry));
1812 entry.shape = entry.mshape =
1813 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1814 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1815 SHAPE_BLOCK;
1816 entry.percentage = 20;
1817 if (term->tl_cursor_blink)
1818 {
1819 entry.blinkwait = 700;
1820 entry.blinkon = 400;
1821 entry.blinkoff = 250;
1822 }
1823 *fg = gui.back_pixel;
1824 if (term->tl_cursor_color == NULL)
1825 *bg = gui.norm_pixel;
1826 else
1827 *bg = color_name2handle(term->tl_cursor_color);
1828 entry.name = "n";
1829 entry.used_for = SHAPE_CURSOR;
1830
1831 return &entry;
1832}
1833#endif
1834
Bram Moolenaard317b382018-02-08 22:33:31 +01001835 static void
1836may_output_cursor_props(void)
1837{
1838 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1839 || last_set_cursor_shape != desired_cursor_shape
1840 || last_set_cursor_blink != desired_cursor_blink)
1841 {
1842 last_set_cursor_color = desired_cursor_color;
1843 last_set_cursor_shape = desired_cursor_shape;
1844 last_set_cursor_blink = desired_cursor_blink;
1845 term_cursor_color(desired_cursor_color);
1846 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1847 /* this will restore the initial cursor style, if possible */
1848 ui_cursor_shape_forced(TRUE);
1849 else
1850 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1851 }
1852}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001853
Bram Moolenaard317b382018-02-08 22:33:31 +01001854/*
1855 * Set the cursor color and shape, if not last set to these.
1856 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857 static void
1858may_set_cursor_props(term_T *term)
1859{
1860#ifdef FEAT_GUI
1861 /* For the GUI the cursor properties are obtained with
1862 * term_get_cursor_shape(). */
1863 if (gui.in_use)
1864 return;
1865#endif
1866 if (in_terminal_loop == term)
1867 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001868 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001869 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001870 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001871 desired_cursor_color = (char_u *)"";
1872 desired_cursor_shape = term->tl_cursor_shape;
1873 desired_cursor_blink = term->tl_cursor_blink;
1874 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875 }
1876}
1877
Bram Moolenaard317b382018-02-08 22:33:31 +01001878/*
1879 * Reset the desired cursor properties and restore them when needed.
1880 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001881 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001882prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883{
1884#ifdef FEAT_GUI
1885 if (gui.in_use)
1886 return;
1887#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001888 desired_cursor_color = (char_u *)"";
1889 desired_cursor_shape = -1;
1890 desired_cursor_blink = -1;
1891 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001892}
1893
1894/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001895 * Called when entering a window with the mouse. If this is a terminal window
1896 * we may want to change state.
1897 */
1898 void
1899term_win_entered()
1900{
1901 term_T *term = curbuf->b_term;
1902
1903 if (term != NULL)
1904 {
1905 if (term_use_loop())
1906 {
1907 reset_VIsual_and_resel();
1908 if (State & INSERT)
1909 stop_insert_mode = TRUE;
1910 }
1911 mouse_was_outside = FALSE;
1912 enter_mouse_col = mouse_col;
1913 enter_mouse_row = mouse_row;
1914 }
1915}
1916
1917/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001918 * Returns TRUE if the current window contains a terminal and we are sending
1919 * keys to the job.
1920 */
1921 int
1922term_use_loop(void)
1923{
1924 term_T *term = curbuf->b_term;
1925
1926 return term != NULL
1927 && !term->tl_normal_mode
1928 && term->tl_vterm != NULL
1929 && term_job_running(term);
1930}
1931
1932/*
1933 * Wait for input and send it to the job.
1934 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1935 * when there is no more typahead.
1936 * Return when the start of a CTRL-W command is typed or anything else that
1937 * should be handled as a Normal mode command.
1938 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1939 * the terminal was closed.
1940 */
1941 int
1942terminal_loop(int blocking)
1943{
1944 int c;
1945 int termkey = 0;
1946 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001947#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001948 int tty_fd = curbuf->b_term->tl_job->jv_channel
1949 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001950#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001951 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001952
1953 /* Remember the terminal we are sending keys to. However, the terminal
1954 * might be closed while waiting for a character, e.g. typing "exit" in a
1955 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1956 * stored reference. */
1957 in_terminal_loop = curbuf->b_term;
1958
1959 if (*curwin->w_p_tk != NUL)
1960 termkey = string_to_key(curwin->w_p_tk, TRUE);
1961 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1962 may_set_cursor_props(curbuf->b_term);
1963
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001964 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001965 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001966#ifdef FEAT_GUI
1967 if (!curbuf->b_term->tl_system)
1968#endif
1969 /* TODO: skip screen update when handling a sequence of keys. */
1970 /* Repeat redrawing in case a message is received while redrawing.
1971 */
1972 while (must_redraw != 0)
1973 if (update_screen(0) == FAIL)
1974 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001975 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001976 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001977
1978 c = term_vgetc();
1979 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001980 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001981 /* Job finished while waiting for a character. Push back the
1982 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001983 if (c != K_IGNORE)
1984 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001985 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001986 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001987 if (c == K_IGNORE)
1988 continue;
1989
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001990#ifdef UNIX
1991 /*
1992 * The shell or another program may change the tty settings. Getting
1993 * them for every typed character is a bit of overhead, but it's needed
1994 * for the first character typed, e.g. when Vim starts in a shell.
1995 */
1996 if (isatty(tty_fd))
1997 {
1998 ttyinfo_T info;
1999
2000 /* Get the current backspace character of the pty. */
2001 if (get_tty_info(tty_fd, &info) == OK)
2002 term_backspace_char = info.backspace;
2003 }
2004#endif
2005
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006#ifdef WIN3264
2007 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2008 * Use CTRL-BREAK to kill the job. */
2009 if (ctrl_break_was_pressed)
2010 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2011#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002012 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2013 * Not in a system terminal. */
2014 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2015#ifdef FEAT_GUI
2016 && !curbuf->b_term->tl_system
2017#endif
2018 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002019 {
2020 int prev_c = c;
2021
2022#ifdef FEAT_CMDL_INFO
2023 if (add_to_showcmd(c))
2024 out_flush();
2025#endif
2026 c = term_vgetc();
2027#ifdef FEAT_CMDL_INFO
2028 clear_showcmd();
2029#endif
2030 if (!term_use_loop())
2031 /* job finished while waiting for a character */
2032 break;
2033
2034 if (prev_c == Ctrl_BSL)
2035 {
2036 if (c == Ctrl_N)
2037 {
2038 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2039 term_enter_normal_mode();
2040 ret = FAIL;
2041 goto theend;
2042 }
2043 /* Send both keys to the terminal. */
2044 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2045 }
2046 else if (c == Ctrl_C)
2047 {
2048 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2049 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2050 }
2051 else if (termkey == 0 && c == '.')
2052 {
2053 /* "CTRL-W .": send CTRL-W to the job */
2054 c = Ctrl_W;
2055 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002056 else if (termkey == 0 && c == Ctrl_BSL)
2057 {
2058 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2059 c = Ctrl_BSL;
2060 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002061 else if (c == 'N')
2062 {
2063 /* CTRL-W N : go to Terminal-Normal mode. */
2064 term_enter_normal_mode();
2065 ret = FAIL;
2066 goto theend;
2067 }
2068 else if (c == '"')
2069 {
2070 term_paste_register(prev_c);
2071 continue;
2072 }
2073 else if (termkey == 0 || c != termkey)
2074 {
2075 stuffcharReadbuff(Ctrl_W);
2076 stuffcharReadbuff(c);
2077 ret = OK;
2078 goto theend;
2079 }
2080 }
2081# ifdef WIN3264
2082 if (!enc_utf8 && has_mbyte && c >= 0x80)
2083 {
2084 WCHAR wc;
2085 char_u mb[3];
2086
2087 mb[0] = (unsigned)c >> 8;
2088 mb[1] = c;
2089 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2090 c = wc;
2091 }
2092# endif
2093 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2094 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002095 if (c == K_MOUSEMOVE)
2096 /* We are sure to come back here, don't reset the cursor color
2097 * and shape to avoid flickering. */
2098 restore_cursor = FALSE;
2099
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100 ret = OK;
2101 goto theend;
2102 }
2103 }
2104 ret = FAIL;
2105
2106theend:
2107 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002108 if (restore_cursor)
2109 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002110 return ret;
2111}
2112
2113/*
2114 * Called when a job has finished.
2115 * This updates the title and status, but does not close the vterm, because
2116 * there might still be pending output in the channel.
2117 */
2118 void
2119term_job_ended(job_T *job)
2120{
2121 term_T *term;
2122 int did_one = FALSE;
2123
2124 for (term = first_term; term != NULL; term = term->tl_next)
2125 if (term->tl_job == job)
2126 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002127 VIM_CLEAR(term->tl_title);
2128 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002129 redraw_buf_and_status_later(term->tl_buffer, VALID);
2130 did_one = TRUE;
2131 }
2132 if (did_one)
2133 redraw_statuslines();
2134 if (curbuf->b_term != NULL)
2135 {
2136 if (curbuf->b_term->tl_job == job)
2137 maketitle();
2138 update_cursor(curbuf->b_term, TRUE);
2139 }
2140}
2141
2142 static void
2143may_toggle_cursor(term_T *term)
2144{
2145 if (in_terminal_loop == term)
2146 {
2147 if (term->tl_cursor_visible)
2148 cursor_on();
2149 else
2150 cursor_off();
2151 }
2152}
2153
2154/*
2155 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002156 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157 */
2158 static int
2159color2index(VTermColor *color, int fg, int *boldp)
2160{
2161 int red = color->red;
2162 int blue = color->blue;
2163 int green = color->green;
2164
Bram Moolenaar46359e12017-11-29 22:33:38 +01002165 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002167 /* First 16 colors and default: use the ANSI index, because these
2168 * colors can be redefined. */
2169 if (t_colors >= 16)
2170 return color->ansi_index;
2171 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002172 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002173 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002174 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002175 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2176 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2177 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002178 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002179 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2180 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2181 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2182 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2183 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2184 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2185 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2186 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2187 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2188 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2189 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002190 }
2191 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002192
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193 if (t_colors >= 256)
2194 {
2195 if (red == blue && red == green)
2196 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002197 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002198 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002199 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2200 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2201 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 int i;
2203
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002204 if (red < 5)
2205 return 17; /* 00/00/00 */
2206 if (red > 245) /* ff/ff/ff */
2207 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208 for (i = 0; i < 23; ++i)
2209 if (red < cutoff[i])
2210 return i + 233;
2211 return 256;
2212 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002213 {
2214 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2215 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002217 /* 216-color cube */
2218 for (ri = 0; ri < 5; ++ri)
2219 if (red < cutoff[ri])
2220 break;
2221 for (gi = 0; gi < 5; ++gi)
2222 if (green < cutoff[gi])
2223 break;
2224 for (bi = 0; bi < 5; ++bi)
2225 if (blue < cutoff[bi])
2226 break;
2227 return 17 + ri * 36 + gi * 6 + bi;
2228 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 }
2230 return 0;
2231}
2232
2233/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002234 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235 */
2236 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002237vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238{
2239 int attr = 0;
2240
2241 if (cellattrs.bold)
2242 attr |= HL_BOLD;
2243 if (cellattrs.underline)
2244 attr |= HL_UNDERLINE;
2245 if (cellattrs.italic)
2246 attr |= HL_ITALIC;
2247 if (cellattrs.strike)
2248 attr |= HL_STRIKETHROUGH;
2249 if (cellattrs.reverse)
2250 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002251 return attr;
2252}
2253
2254/*
2255 * Store Vterm attributes in "cell" from highlight flags.
2256 */
2257 static void
2258hl2vtermAttr(int attr, cellattr_T *cell)
2259{
2260 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2261 if (attr & HL_BOLD)
2262 cell->attrs.bold = 1;
2263 if (attr & HL_UNDERLINE)
2264 cell->attrs.underline = 1;
2265 if (attr & HL_ITALIC)
2266 cell->attrs.italic = 1;
2267 if (attr & HL_STRIKETHROUGH)
2268 cell->attrs.strike = 1;
2269 if (attr & HL_INVERSE)
2270 cell->attrs.reverse = 1;
2271}
2272
2273/*
2274 * Convert the attributes of a vterm cell into an attribute index.
2275 */
2276 static int
2277cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2278{
2279 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280
2281#ifdef FEAT_GUI
2282 if (gui.in_use)
2283 {
2284 guicolor_T fg, bg;
2285
2286 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2287 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2288 return get_gui_attr_idx(attr, fg, bg);
2289 }
2290 else
2291#endif
2292#ifdef FEAT_TERMGUICOLORS
2293 if (p_tgc)
2294 {
2295 guicolor_T fg, bg;
2296
2297 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2298 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2299
2300 return get_tgc_attr_idx(attr, fg, bg);
2301 }
2302 else
2303#endif
2304 {
2305 int bold = MAYBE;
2306 int fg = color2index(&cellfg, TRUE, &bold);
2307 int bg = color2index(&cellbg, FALSE, &bold);
2308
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002309 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002310 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002311 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002312 if (fg == 0 && term_default_cterm_fg >= 0)
2313 fg = term_default_cterm_fg + 1;
2314 if (bg == 0 && term_default_cterm_bg >= 0)
2315 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002316 }
2317
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002318 /* with 8 colors set the bold attribute to get a bright foreground */
2319 if (bold == TRUE)
2320 attr |= HL_BOLD;
2321 return get_cterm_attr_idx(attr, fg, bg);
2322 }
2323 return 0;
2324}
2325
2326 static int
2327handle_damage(VTermRect rect, void *user)
2328{
2329 term_T *term = (term_T *)user;
2330
2331 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2332 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2333 redraw_buf_later(term->tl_buffer, NOT_VALID);
2334 return 1;
2335}
2336
2337 static int
2338handle_moverect(VTermRect dest, VTermRect src, void *user)
2339{
2340 term_T *term = (term_T *)user;
2341
2342 /* Scrolling up is done much more efficiently by deleting lines instead of
2343 * redrawing the text. */
2344 if (dest.start_col == src.start_col
2345 && dest.end_col == src.end_col
2346 && dest.start_row < src.start_row)
2347 {
2348 win_T *wp;
2349 VTermColor fg, bg;
2350 VTermScreenCellAttrs attr;
2351 int clear_attr;
2352
2353 /* Set the color to clear lines with. */
2354 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2355 &fg, &bg);
2356 vim_memset(&attr, 0, sizeof(attr));
2357 clear_attr = cell2attr(attr, fg, bg);
2358
2359 FOR_ALL_WINDOWS(wp)
2360 {
2361 if (wp->w_buffer == term->tl_buffer)
2362 win_del_lines(wp, dest.start_row,
2363 src.start_row - dest.start_row, FALSE, FALSE,
2364 clear_attr);
2365 }
2366 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002367
2368 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2369 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2370
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002371 redraw_buf_later(term->tl_buffer, NOT_VALID);
2372 return 1;
2373}
2374
2375 static int
2376handle_movecursor(
2377 VTermPos pos,
2378 VTermPos oldpos UNUSED,
2379 int visible,
2380 void *user)
2381{
2382 term_T *term = (term_T *)user;
2383 win_T *wp;
2384
2385 term->tl_cursor_pos = pos;
2386 term->tl_cursor_visible = visible;
2387
2388 FOR_ALL_WINDOWS(wp)
2389 {
2390 if (wp->w_buffer == term->tl_buffer)
2391 position_cursor(wp, &pos);
2392 }
2393 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2394 {
2395 may_toggle_cursor(term);
2396 update_cursor(term, term->tl_cursor_visible);
2397 }
2398
2399 return 1;
2400}
2401
2402 static int
2403handle_settermprop(
2404 VTermProp prop,
2405 VTermValue *value,
2406 void *user)
2407{
2408 term_T *term = (term_T *)user;
2409
2410 switch (prop)
2411 {
2412 case VTERM_PROP_TITLE:
2413 vim_free(term->tl_title);
2414 /* a blank title isn't useful, make it empty, so that "running" is
2415 * displayed */
2416 if (*skipwhite((char_u *)value->string) == NUL)
2417 term->tl_title = NULL;
2418#ifdef WIN3264
2419 else if (!enc_utf8 && enc_codepage > 0)
2420 {
2421 WCHAR *ret = NULL;
2422 int length = 0;
2423
2424 MultiByteToWideChar_alloc(CP_UTF8, 0,
2425 (char*)value->string, (int)STRLEN(value->string),
2426 &ret, &length);
2427 if (ret != NULL)
2428 {
2429 WideCharToMultiByte_alloc(enc_codepage, 0,
2430 ret, length, (char**)&term->tl_title,
2431 &length, 0, 0);
2432 vim_free(ret);
2433 }
2434 }
2435#endif
2436 else
2437 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002438 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439 if (term == curbuf->b_term)
2440 maketitle();
2441 break;
2442
2443 case VTERM_PROP_CURSORVISIBLE:
2444 term->tl_cursor_visible = value->boolean;
2445 may_toggle_cursor(term);
2446 out_flush();
2447 break;
2448
2449 case VTERM_PROP_CURSORBLINK:
2450 term->tl_cursor_blink = value->boolean;
2451 may_set_cursor_props(term);
2452 break;
2453
2454 case VTERM_PROP_CURSORSHAPE:
2455 term->tl_cursor_shape = value->number;
2456 may_set_cursor_props(term);
2457 break;
2458
2459 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002460 if (desired_cursor_color == term->tl_cursor_color)
2461 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002462 vim_free(term->tl_cursor_color);
2463 if (*value->string == NUL)
2464 term->tl_cursor_color = NULL;
2465 else
2466 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2467 may_set_cursor_props(term);
2468 break;
2469
2470 case VTERM_PROP_ALTSCREEN:
2471 /* TODO: do anything else? */
2472 term->tl_using_altscreen = value->boolean;
2473 break;
2474
2475 default:
2476 break;
2477 }
2478 /* Always return 1, otherwise vterm doesn't store the value internally. */
2479 return 1;
2480}
2481
2482/*
2483 * The job running in the terminal resized the terminal.
2484 */
2485 static int
2486handle_resize(int rows, int cols, void *user)
2487{
2488 term_T *term = (term_T *)user;
2489 win_T *wp;
2490
2491 term->tl_rows = rows;
2492 term->tl_cols = cols;
2493 if (term->tl_vterm_size_changed)
2494 /* Size was set by vterm_set_size(), don't set the window size. */
2495 term->tl_vterm_size_changed = FALSE;
2496 else
2497 {
2498 FOR_ALL_WINDOWS(wp)
2499 {
2500 if (wp->w_buffer == term->tl_buffer)
2501 {
2502 win_setheight_win(rows, wp);
2503 win_setwidth_win(cols, wp);
2504 }
2505 }
2506 redraw_buf_later(term->tl_buffer, NOT_VALID);
2507 }
2508 return 1;
2509}
2510
2511/*
2512 * Handle a line that is pushed off the top of the screen.
2513 */
2514 static int
2515handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2516{
2517 term_T *term = (term_T *)user;
2518
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002519 /* If the number of lines that are stored goes over 'termscrollback' then
2520 * delete the first 10%. */
2521 if (term->tl_scrollback.ga_len > p_tlsl)
2522 {
2523 int todo = p_tlsl / 10;
2524 int i;
2525
2526 curbuf = term->tl_buffer;
2527 for (i = 0; i < todo; ++i)
2528 {
2529 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2530 ml_delete(1, FALSE);
2531 }
2532 curbuf = curwin->w_buffer;
2533
2534 term->tl_scrollback.ga_len -= todo;
2535 mch_memmove(term->tl_scrollback.ga_data,
2536 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2537 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2538 }
2539
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002540 if (ga_grow(&term->tl_scrollback, 1) == OK)
2541 {
2542 cellattr_T *p = NULL;
2543 int len = 0;
2544 int i;
2545 int c;
2546 int col;
2547 sb_line_T *line;
2548 garray_T ga;
2549 cellattr_T fill_attr = term->tl_default_color;
2550
2551 /* do not store empty cells at the end */
2552 for (i = 0; i < cols; ++i)
2553 if (cells[i].chars[0] != 0)
2554 len = i + 1;
2555 else
2556 cell2cellattr(&cells[i], &fill_attr);
2557
2558 ga_init2(&ga, 1, 100);
2559 if (len > 0)
2560 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2561 if (p != NULL)
2562 {
2563 for (col = 0; col < len; col += cells[col].width)
2564 {
2565 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2566 {
2567 ga.ga_len = 0;
2568 break;
2569 }
2570 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2571 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2572 (char_u *)ga.ga_data + ga.ga_len);
2573 cell2cellattr(&cells[col], &p[col]);
2574 }
2575 }
2576 if (ga_grow(&ga, 1) == FAIL)
2577 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2578 else
2579 {
2580 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2581 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2582 }
2583 ga_clear(&ga);
2584
2585 line = (sb_line_T *)term->tl_scrollback.ga_data
2586 + term->tl_scrollback.ga_len;
2587 line->sb_cols = len;
2588 line->sb_cells = p;
2589 line->sb_fill_attr = fill_attr;
2590 ++term->tl_scrollback.ga_len;
2591 ++term->tl_scrollback_scrolled;
2592 }
2593 return 0; /* ignored */
2594}
2595
2596static VTermScreenCallbacks screen_callbacks = {
2597 handle_damage, /* damage */
2598 handle_moverect, /* moverect */
2599 handle_movecursor, /* movecursor */
2600 handle_settermprop, /* settermprop */
2601 NULL, /* bell */
2602 handle_resize, /* resize */
2603 handle_pushline, /* sb_pushline */
2604 NULL /* sb_popline */
2605};
2606
2607/*
2608 * Called when a channel has been closed.
2609 * If this was a channel for a terminal window then finish it up.
2610 */
2611 void
2612term_channel_closed(channel_T *ch)
2613{
2614 term_T *term;
2615 int did_one = FALSE;
2616
2617 for (term = first_term; term != NULL; term = term->tl_next)
2618 if (term->tl_job == ch->ch_job)
2619 {
2620 term->tl_channel_closed = TRUE;
2621 did_one = TRUE;
2622
Bram Moolenaard23a8232018-02-10 18:45:26 +01002623 VIM_CLEAR(term->tl_title);
2624 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002625
2626 /* Unless in Terminal-Normal mode: clear the vterm. */
2627 if (!term->tl_normal_mode)
2628 {
2629 int fnum = term->tl_buffer->b_fnum;
2630
2631 cleanup_vterm(term);
2632
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002633 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002634 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002635 aco_save_T aco;
2636
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002637 /* ++close or term_finish == "close" */
2638 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002639 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002640 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002641 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002642 break;
2643 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002644 if (term->tl_finish == TL_FINISH_OPEN
2645 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002646 {
2647 char buf[50];
2648
2649 /* TODO: use term_opencmd */
2650 ch_log(NULL, "terminal job finished, opening window");
2651 vim_snprintf(buf, sizeof(buf),
2652 term->tl_opencmd == NULL
2653 ? "botright sbuf %d"
2654 : (char *)term->tl_opencmd, fnum);
2655 do_cmdline_cmd((char_u *)buf);
2656 }
2657 else
2658 ch_log(NULL, "terminal job finished");
2659 }
2660
2661 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2662 }
2663 if (did_one)
2664 {
2665 redraw_statuslines();
2666
2667 /* Need to break out of vgetc(). */
2668 ins_char_typebuf(K_IGNORE);
2669 typebuf_was_filled = TRUE;
2670
2671 term = curbuf->b_term;
2672 if (term != NULL)
2673 {
2674 if (term->tl_job == ch->ch_job)
2675 maketitle();
2676 update_cursor(term, term->tl_cursor_visible);
2677 }
2678 }
2679}
2680
2681/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002682 * Fill one screen line from a line of the terminal.
2683 * Advances "pos" to past the last column.
2684 */
2685 static void
2686term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2687{
2688 int off = screen_get_current_line_off();
2689
2690 for (pos->col = 0; pos->col < max_col; )
2691 {
2692 VTermScreenCell cell;
2693 int c;
2694
2695 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2696 vim_memset(&cell, 0, sizeof(cell));
2697
2698 c = cell.chars[0];
2699 if (c == NUL)
2700 {
2701 ScreenLines[off] = ' ';
2702 if (enc_utf8)
2703 ScreenLinesUC[off] = NUL;
2704 }
2705 else
2706 {
2707 if (enc_utf8)
2708 {
2709 int i;
2710
2711 /* composing chars */
2712 for (i = 0; i < Screen_mco
2713 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2714 {
2715 ScreenLinesC[i][off] = cell.chars[i + 1];
2716 if (cell.chars[i + 1] == 0)
2717 break;
2718 }
2719 if (c >= 0x80 || (Screen_mco > 0
2720 && ScreenLinesC[0][off] != 0))
2721 {
2722 ScreenLines[off] = ' ';
2723 ScreenLinesUC[off] = c;
2724 }
2725 else
2726 {
2727 ScreenLines[off] = c;
2728 ScreenLinesUC[off] = NUL;
2729 }
2730 }
2731#ifdef WIN3264
2732 else if (has_mbyte && c >= 0x80)
2733 {
2734 char_u mb[MB_MAXBYTES+1];
2735 WCHAR wc = c;
2736
2737 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2738 (char*)mb, 2, 0, 0) > 1)
2739 {
2740 ScreenLines[off] = mb[0];
2741 ScreenLines[off + 1] = mb[1];
2742 cell.width = mb_ptr2cells(mb);
2743 }
2744 else
2745 ScreenLines[off] = c;
2746 }
2747#endif
2748 else
2749 ScreenLines[off] = c;
2750 }
2751 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2752
2753 ++pos->col;
2754 ++off;
2755 if (cell.width == 2)
2756 {
2757 if (enc_utf8)
2758 ScreenLinesUC[off] = NUL;
2759
2760 /* don't set the second byte to NUL for a DBCS encoding, it
2761 * has been set above */
2762 if (enc_utf8 || !has_mbyte)
2763 ScreenLines[off] = NUL;
2764
2765 ++pos->col;
2766 ++off;
2767 }
2768 }
2769}
2770
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002771#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002772 static void
2773update_system_term(term_T *term)
2774{
2775 VTermPos pos;
2776 VTermScreen *screen;
2777
2778 if (term->tl_vterm == NULL)
2779 return;
2780 screen = vterm_obtain_screen(term->tl_vterm);
2781
2782 /* Scroll up to make more room for terminal lines if needed. */
2783 while (term->tl_toprow > 0
2784 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2785 {
2786 int save_p_more = p_more;
2787
2788 p_more = FALSE;
2789 msg_row = Rows - 1;
2790 msg_puts((char_u *)"\n");
2791 p_more = save_p_more;
2792 --term->tl_toprow;
2793 }
2794
2795 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2796 && pos.row < Rows; ++pos.row)
2797 {
2798 if (pos.row < term->tl_rows)
2799 {
2800 int max_col = MIN(Columns, term->tl_cols);
2801
2802 term_line2screenline(screen, &pos, max_col);
2803 }
2804 else
2805 pos.col = 0;
2806
2807 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2808 }
2809
2810 term->tl_dirty_row_start = MAX_ROW;
2811 term->tl_dirty_row_end = 0;
2812 update_cursor(term, TRUE);
2813}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002814#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002815
2816/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002817 * Called to update a window that contains an active terminal.
2818 * Returns FAIL when there is no terminal running in this window or in
2819 * Terminal-Normal mode.
2820 */
2821 int
2822term_update_window(win_T *wp)
2823{
2824 term_T *term = wp->w_buffer->b_term;
2825 VTerm *vterm;
2826 VTermScreen *screen;
2827 VTermState *state;
2828 VTermPos pos;
2829
2830 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2831 return FAIL;
2832
2833 vterm = term->tl_vterm;
2834 screen = vterm_obtain_screen(vterm);
2835 state = vterm_obtain_state(vterm);
2836
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002837 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002838 {
2839 term->tl_dirty_row_start = 0;
2840 term->tl_dirty_row_end = MAX_ROW;
2841 }
2842
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002843 /*
2844 * If the window was resized a redraw will be triggered and we get here.
2845 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2846 */
2847 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2848 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2849 {
2850 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2851 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2852 win_T *twp;
2853
2854 FOR_ALL_WINDOWS(twp)
2855 {
2856 /* When more than one window shows the same terminal, use the
2857 * smallest size. */
2858 if (twp->w_buffer == term->tl_buffer)
2859 {
2860 if (!term->tl_rows_fixed && rows > twp->w_height)
2861 rows = twp->w_height;
2862 if (!term->tl_cols_fixed && cols > twp->w_width)
2863 cols = twp->w_width;
2864 }
2865 }
2866
2867 term->tl_vterm_size_changed = TRUE;
2868 vterm_set_size(vterm, rows, cols);
2869 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2870 rows);
2871 term_report_winsize(term, rows, cols);
2872 }
2873
2874 /* The cursor may have been moved when resizing. */
2875 vterm_state_get_cursorpos(state, &pos);
2876 position_cursor(wp, &pos);
2877
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002878 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2879 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 if (pos.row < term->tl_rows)
2882 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002883 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002884
Bram Moolenaar13568252018-03-16 20:46:58 +01002885 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002886 }
2887 else
2888 pos.col = 0;
2889
Bram Moolenaarf118d482018-03-13 13:14:00 +01002890 screen_line(wp->w_winrow + pos.row
2891#ifdef FEAT_MENU
2892 + winbar_height(wp)
2893#endif
2894 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002895 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002896 term->tl_dirty_row_start = MAX_ROW;
2897 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898
2899 return OK;
2900}
2901
2902/*
2903 * Return TRUE if "wp" is a terminal window where the job has finished.
2904 */
2905 int
2906term_is_finished(buf_T *buf)
2907{
2908 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2909}
2910
2911/*
2912 * Return TRUE if "wp" is a terminal window where the job has finished or we
2913 * are in Terminal-Normal mode, thus we show the buffer contents.
2914 */
2915 int
2916term_show_buffer(buf_T *buf)
2917{
2918 term_T *term = buf->b_term;
2919
2920 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2921}
2922
2923/*
2924 * The current buffer is going to be changed. If there is terminal
2925 * highlighting remove it now.
2926 */
2927 void
2928term_change_in_curbuf(void)
2929{
2930 term_T *term = curbuf->b_term;
2931
2932 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2933 {
2934 free_scrollback(term);
2935 redraw_buf_later(term->tl_buffer, NOT_VALID);
2936
2937 /* The buffer is now like a normal buffer, it cannot be easily
2938 * abandoned when changed. */
2939 set_string_option_direct((char_u *)"buftype", -1,
2940 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2941 }
2942}
2943
2944/*
2945 * Get the screen attribute for a position in the buffer.
2946 * Use a negative "col" to get the filler background color.
2947 */
2948 int
2949term_get_attr(buf_T *buf, linenr_T lnum, int col)
2950{
2951 term_T *term = buf->b_term;
2952 sb_line_T *line;
2953 cellattr_T *cellattr;
2954
2955 if (lnum > term->tl_scrollback.ga_len)
2956 cellattr = &term->tl_default_color;
2957 else
2958 {
2959 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2960 if (col < 0 || col >= line->sb_cols)
2961 cellattr = &line->sb_fill_attr;
2962 else
2963 cellattr = line->sb_cells + col;
2964 }
2965 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2966}
2967
2968static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002969 { 0, 0, 0, 1}, /* black */
2970 {224, 0, 0, 2}, /* dark red */
2971 { 0, 224, 0, 3}, /* dark green */
2972 {224, 224, 0, 4}, /* dark yellow / brown */
2973 { 0, 0, 224, 5}, /* dark blue */
2974 {224, 0, 224, 6}, /* dark magenta */
2975 { 0, 224, 224, 7}, /* dark cyan */
2976 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977
Bram Moolenaar46359e12017-11-29 22:33:38 +01002978 {128, 128, 128, 9}, /* dark grey */
2979 {255, 64, 64, 10}, /* light red */
2980 { 64, 255, 64, 11}, /* light green */
2981 {255, 255, 64, 12}, /* yellow */
2982 { 64, 64, 255, 13}, /* light blue */
2983 {255, 64, 255, 14}, /* light magenta */
2984 { 64, 255, 255, 15}, /* light cyan */
2985 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986};
2987
2988static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002989 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002990};
2991
2992static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002993 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2994 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002995};
2996
2997/*
2998 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002999 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 */
3001 static void
3002cterm_color2rgb(int nr, VTermColor *rgb)
3003{
3004 int idx;
3005
3006 if (nr < 16)
3007 {
3008 *rgb = ansi_table[nr];
3009 }
3010 else if (nr < 232)
3011 {
3012 /* 216 color cube */
3013 idx = nr - 16;
3014 rgb->blue = cube_value[idx % 6];
3015 rgb->green = cube_value[idx / 6 % 6];
3016 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003017 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 }
3019 else if (nr < 256)
3020 {
3021 /* 24 grey scale ramp */
3022 idx = nr - 232;
3023 rgb->blue = grey_ramp[idx];
3024 rgb->green = grey_ramp[idx];
3025 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003026 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003027 }
3028}
3029
3030/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003031 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032 */
3033 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003034init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003035{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003036 VTermColor *fg, *bg;
3037 int fgval, bgval;
3038 int id;
3039
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003040 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3041 term->tl_default_color.width = 1;
3042 fg = &term->tl_default_color.fg;
3043 bg = &term->tl_default_color.bg;
3044
3045 /* Vterm uses a default black background. Set it to white when
3046 * 'background' is "light". */
3047 if (*p_bg == 'l')
3048 {
3049 fgval = 0;
3050 bgval = 255;
3051 }
3052 else
3053 {
3054 fgval = 255;
3055 bgval = 0;
3056 }
3057 fg->red = fg->green = fg->blue = fgval;
3058 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003059 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003060
3061 /* The "Terminal" highlight group overrules the defaults. */
3062 id = syn_name2id((char_u *)"Terminal");
3063
Bram Moolenaar46359e12017-11-29 22:33:38 +01003064 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003065#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3066 if (0
3067# ifdef FEAT_GUI
3068 || gui.in_use
3069# endif
3070# ifdef FEAT_TERMGUICOLORS
3071 || p_tgc
3072# endif
3073 )
3074 {
3075 guicolor_T fg_rgb = INVALCOLOR;
3076 guicolor_T bg_rgb = INVALCOLOR;
3077
3078 if (id != 0)
3079 syn_id2colors(id, &fg_rgb, &bg_rgb);
3080
3081# ifdef FEAT_GUI
3082 if (gui.in_use)
3083 {
3084 if (fg_rgb == INVALCOLOR)
3085 fg_rgb = gui.norm_pixel;
3086 if (bg_rgb == INVALCOLOR)
3087 bg_rgb = gui.back_pixel;
3088 }
3089# ifdef FEAT_TERMGUICOLORS
3090 else
3091# endif
3092# endif
3093# ifdef FEAT_TERMGUICOLORS
3094 {
3095 if (fg_rgb == INVALCOLOR)
3096 fg_rgb = cterm_normal_fg_gui_color;
3097 if (bg_rgb == INVALCOLOR)
3098 bg_rgb = cterm_normal_bg_gui_color;
3099 }
3100# endif
3101 if (fg_rgb != INVALCOLOR)
3102 {
3103 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3104
3105 fg->red = (unsigned)(rgb >> 16);
3106 fg->green = (unsigned)(rgb >> 8) & 255;
3107 fg->blue = (unsigned)rgb & 255;
3108 }
3109 if (bg_rgb != INVALCOLOR)
3110 {
3111 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3112
3113 bg->red = (unsigned)(rgb >> 16);
3114 bg->green = (unsigned)(rgb >> 8) & 255;
3115 bg->blue = (unsigned)rgb & 255;
3116 }
3117 }
3118 else
3119#endif
3120 if (id != 0 && t_colors >= 16)
3121 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003122 if (term_default_cterm_fg >= 0)
3123 cterm_color2rgb(term_default_cterm_fg, fg);
3124 if (term_default_cterm_bg >= 0)
3125 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003126 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003127 else
3128 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003129#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003131#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003132
3133 /* In an MS-Windows console we know the normal colors. */
3134 if (cterm_normal_fg_color > 0)
3135 {
3136 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003137# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138 tmp = fg->red;
3139 fg->red = fg->blue;
3140 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003141# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003142 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003143# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003144 else
3145 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003146# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003147
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003148 if (cterm_normal_bg_color > 0)
3149 {
3150 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003151# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003152 tmp = bg->red;
3153 bg->red = bg->blue;
3154 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003155# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003157# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003158 else
3159 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003160# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003161 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003162}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003163
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003164#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3165/*
3166 * Set the 16 ANSI colors from array of RGB values
3167 */
3168 static void
3169set_vterm_palette(VTerm *vterm, long_u *rgb)
3170{
3171 int index = 0;
3172 VTermState *state = vterm_obtain_state(vterm);
3173 for (; index < 16; index++)
3174 {
3175 VTermColor color;
3176 color.red = (unsigned)(rgb[index] >> 16);
3177 color.green = (unsigned)(rgb[index] >> 8) & 255;
3178 color.blue = (unsigned)rgb[index] & 255;
3179 vterm_state_set_palette_color(state, index, &color);
3180 }
3181}
3182
3183/*
3184 * Set the ANSI color palette from a list of colors
3185 */
3186 static int
3187set_ansi_colors_list(VTerm *vterm, list_T *list)
3188{
3189 int n = 0;
3190 long_u rgb[16];
3191 listitem_T *li = list->lv_first;
3192
3193 for (; li != NULL && n < 16; li = li->li_next, n++)
3194 {
3195 char_u *color_name;
3196 guicolor_T guicolor;
3197
3198 color_name = get_tv_string_chk(&li->li_tv);
3199 if (color_name == NULL)
3200 return FAIL;
3201
3202 guicolor = GUI_GET_COLOR(color_name);
3203 if (guicolor == INVALCOLOR)
3204 return FAIL;
3205
3206 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3207 }
3208
3209 if (n != 16 || li != NULL)
3210 return FAIL;
3211
3212 set_vterm_palette(vterm, rgb);
3213
3214 return OK;
3215}
3216
3217/*
3218 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3219 */
3220 static void
3221init_vterm_ansi_colors(VTerm *vterm)
3222{
3223 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3224
3225 if (var != NULL
3226 && (var->di_tv.v_type != VAR_LIST
3227 || var->di_tv.vval.v_list == NULL
3228 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3229 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3230}
3231#endif
3232
Bram Moolenaar52acb112018-03-18 19:20:22 +01003233/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003234 * Handles a "drop" command from the job in the terminal.
3235 * "item" is the file name, "item->li_next" may have options.
3236 */
3237 static void
3238handle_drop_command(listitem_T *item)
3239{
3240 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003241 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003242 int bufnr;
3243 win_T *wp;
3244 tabpage_T *tp;
3245 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003246 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003247
3248 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3249 FOR_ALL_TAB_WINDOWS(tp, wp)
3250 {
3251 if (wp->w_buffer->b_fnum == bufnr)
3252 {
3253 /* buffer is in a window already, go there */
3254 goto_tabpage_win(tp, wp);
3255 return;
3256 }
3257 }
3258
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003259 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003260
3261 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3262 && opt_item->li_tv.vval.v_dict != NULL)
3263 {
3264 dict_T *dict = opt_item->li_tv.vval.v_dict;
3265 char_u *p;
3266
3267 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3268 if (p == NULL)
3269 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3270 if (p != NULL)
3271 {
3272 if (check_ff_value(p) == FAIL)
3273 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3274 else
3275 ea.force_ff = *p;
3276 }
3277 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3278 if (p == NULL)
3279 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3280 if (p != NULL)
3281 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003282 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003283 if (ea.cmd != NULL)
3284 {
3285 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3286 ea.force_enc = 11;
3287 tofree = ea.cmd;
3288 }
3289 }
3290
3291 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3292 if (p != NULL)
3293 get_bad_opt(p, &ea);
3294
3295 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3296 ea.force_bin = FORCE_BIN;
3297 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3298 ea.force_bin = FORCE_BIN;
3299 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3300 ea.force_bin = FORCE_NOBIN;
3301 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3302 ea.force_bin = FORCE_NOBIN;
3303 }
3304
3305 /* open in new window, like ":split fname" */
3306 if (ea.cmd == NULL)
3307 ea.cmd = (char_u *)"split";
3308 ea.arg = fname;
3309 ea.cmdidx = CMD_split;
3310 ex_splitview(&ea);
3311
3312 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003313}
3314
3315/*
3316 * Handles a function call from the job running in a terminal.
3317 * "item" is the function name, "item->li_next" has the arguments.
3318 */
3319 static void
3320handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3321{
3322 char_u *func;
3323 typval_T argvars[2];
3324 typval_T rettv;
3325 int doesrange;
3326
3327 if (item->li_next == NULL)
3328 {
3329 ch_log(channel, "Missing function arguments for call");
3330 return;
3331 }
3332 func = get_tv_string(&item->li_tv);
3333
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003334 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003335 {
3336 ch_log(channel, "Invalid function name: %s", func);
3337 return;
3338 }
3339
3340 argvars[0].v_type = VAR_NUMBER;
3341 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3342 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003343 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003344 2, argvars, /* argv_func */ NULL,
3345 /* firstline */ 1, /* lastline */ 1,
3346 &doesrange, /* evaluate */ TRUE,
3347 /* partial */ NULL, /* selfdict */ NULL) == OK)
3348 {
3349 clear_tv(&rettv);
3350 ch_log(channel, "Function %s called", func);
3351 }
3352 else
3353 ch_log(channel, "Calling function %s failed", func);
3354}
3355
3356/*
3357 * Called by libvterm when it cannot recognize an OSC sequence.
3358 * We recognize a terminal API command.
3359 */
3360 static int
3361parse_osc(const char *command, size_t cmdlen, void *user)
3362{
3363 term_T *term = (term_T *)user;
3364 js_read_T reader;
3365 typval_T tv;
3366 channel_T *channel = term->tl_job == NULL ? NULL
3367 : term->tl_job->jv_channel;
3368
3369 /* We recognize only OSC 5 1 ; {command} */
3370 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3371 return 0; /* not handled */
3372
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003373 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003374 if (reader.js_buf == NULL)
3375 return 1;
3376 reader.js_fill = NULL;
3377 reader.js_used = 0;
3378 if (json_decode(&reader, &tv, 0) == OK
3379 && tv.v_type == VAR_LIST
3380 && tv.vval.v_list != NULL)
3381 {
3382 listitem_T *item = tv.vval.v_list->lv_first;
3383
3384 if (item == NULL)
3385 ch_log(channel, "Missing command");
3386 else
3387 {
3388 char_u *cmd = get_tv_string(&item->li_tv);
3389
3390 item = item->li_next;
3391 if (item == NULL)
3392 ch_log(channel, "Missing argument for %s", cmd);
3393 else if (STRCMP(cmd, "drop") == 0)
3394 handle_drop_command(item);
3395 else if (STRCMP(cmd, "call") == 0)
3396 handle_call_command(term, channel, item);
3397 else
3398 ch_log(channel, "Invalid command received: %s", cmd);
3399 }
3400 }
3401 else
3402 ch_log(channel, "Invalid JSON received");
3403
3404 vim_free(reader.js_buf);
3405 clear_tv(&tv);
3406 return 1;
3407}
3408
3409static VTermParserCallbacks parser_fallbacks = {
3410 NULL, /* text */
3411 NULL, /* control */
3412 NULL, /* escape */
3413 NULL, /* csi */
3414 parse_osc, /* osc */
3415 NULL, /* dcs */
3416 NULL /* resize */
3417};
3418
3419/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003420 * Use Vim's allocation functions for vterm so profiling works.
3421 */
3422 static void *
3423vterm_malloc(size_t size, void *data UNUSED)
3424{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003425 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003426}
3427
3428 static void
3429vterm_memfree(void *ptr, void *data UNUSED)
3430{
3431 vim_free(ptr);
3432}
3433
3434static VTermAllocatorFunctions vterm_allocator = {
3435 &vterm_malloc,
3436 &vterm_memfree
3437};
3438
3439/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003440 * Create a new vterm and initialize it.
3441 */
3442 static void
3443create_vterm(term_T *term, int rows, int cols)
3444{
3445 VTerm *vterm;
3446 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003447 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003448 VTermValue value;
3449
Bram Moolenaar756ef112018-04-10 12:04:27 +02003450 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003451 term->tl_vterm = vterm;
3452 screen = vterm_obtain_screen(vterm);
3453 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3454 /* TODO: depends on 'encoding'. */
3455 vterm_set_utf8(vterm, 1);
3456
3457 init_default_colors(term);
3458
3459 vterm_state_set_default_colors(
3460 vterm_obtain_state(vterm),
3461 &term->tl_default_color.fg,
3462 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003463
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003464 if (t_colors >= 16)
3465 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3466
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467 /* Required to initialize most things. */
3468 vterm_screen_reset(screen, 1 /* hard */);
3469
3470 /* Allow using alternate screen. */
3471 vterm_screen_enable_altscreen(screen, 1);
3472
3473 /* For unix do not use a blinking cursor. In an xterm this causes the
3474 * cursor to blink if it's blinking in the xterm.
3475 * For Windows we respect the system wide setting. */
3476#ifdef WIN3264
3477 if (GetCaretBlinkTime() == INFINITE)
3478 value.boolean = 0;
3479 else
3480 value.boolean = 1;
3481#else
3482 value.boolean = 0;
3483#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003484 state = vterm_obtain_state(vterm);
3485 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3486 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003487}
3488
3489/*
3490 * Return the text to show for the buffer name and status.
3491 */
3492 char_u *
3493term_get_status_text(term_T *term)
3494{
3495 if (term->tl_status_text == NULL)
3496 {
3497 char_u *txt;
3498 size_t len;
3499
3500 if (term->tl_normal_mode)
3501 {
3502 if (term_job_running(term))
3503 txt = (char_u *)_("Terminal");
3504 else
3505 txt = (char_u *)_("Terminal-finished");
3506 }
3507 else if (term->tl_title != NULL)
3508 txt = term->tl_title;
3509 else if (term_none_open(term))
3510 txt = (char_u *)_("active");
3511 else if (term_job_running(term))
3512 txt = (char_u *)_("running");
3513 else
3514 txt = (char_u *)_("finished");
3515 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3516 term->tl_status_text = alloc((int)len);
3517 if (term->tl_status_text != NULL)
3518 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3519 term->tl_buffer->b_fname, txt);
3520 }
3521 return term->tl_status_text;
3522}
3523
3524/*
3525 * Mark references in jobs of terminals.
3526 */
3527 int
3528set_ref_in_term(int copyID)
3529{
3530 int abort = FALSE;
3531 term_T *term;
3532 typval_T tv;
3533
3534 for (term = first_term; term != NULL; term = term->tl_next)
3535 if (term->tl_job != NULL)
3536 {
3537 tv.v_type = VAR_JOB;
3538 tv.vval.v_job = term->tl_job;
3539 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3540 }
3541 return abort;
3542}
3543
3544/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003545 * Cache "Terminal" highlight group colors.
3546 */
3547 void
3548set_terminal_default_colors(int cterm_fg, int cterm_bg)
3549{
3550 term_default_cterm_fg = cterm_fg - 1;
3551 term_default_cterm_bg = cterm_bg - 1;
3552}
3553
3554/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003555 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003556 * Returns NULL when the buffer is not for a terminal window and logs a message
3557 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003558 */
3559 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003560term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561{
3562 buf_T *buf;
3563
3564 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3565 ++emsg_off;
3566 buf = get_buf_tv(&argvars[0], FALSE);
3567 --emsg_off;
3568 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003569 {
3570 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003571 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003572 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003573 return buf;
3574}
3575
Bram Moolenaard96ff162018-02-18 22:13:29 +01003576 static int
3577same_color(VTermColor *a, VTermColor *b)
3578{
3579 return a->red == b->red
3580 && a->green == b->green
3581 && a->blue == b->blue
3582 && a->ansi_index == b->ansi_index;
3583}
3584
3585 static void
3586dump_term_color(FILE *fd, VTermColor *color)
3587{
3588 fprintf(fd, "%02x%02x%02x%d",
3589 (int)color->red, (int)color->green, (int)color->blue,
3590 (int)color->ansi_index);
3591}
3592
3593/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003594 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003595 *
3596 * Each screen cell in full is:
3597 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3598 * {characters} is a space for an empty cell
3599 * For a double-width character "+" is changed to "*" and the next cell is
3600 * skipped.
3601 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3602 * when "&" use the same as the previous cell.
3603 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3604 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3605 * {color-idx} is a number from 0 to 255
3606 *
3607 * Screen cell with same width, attributes and color as the previous one:
3608 * |{characters}
3609 *
3610 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3611 *
3612 * Repeating the previous screen cell:
3613 * @{count}
3614 */
3615 void
3616f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3617{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003618 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003619 term_T *term;
3620 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003621 int max_height = 0;
3622 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003623 stat_T st;
3624 FILE *fd;
3625 VTermPos pos;
3626 VTermScreen *screen;
3627 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003628 VTermState *state;
3629 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003630
3631 if (check_restricted() || check_secure())
3632 return;
3633 if (buf == NULL)
3634 return;
3635 term = buf->b_term;
3636
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003637 if (argvars[2].v_type != VAR_UNKNOWN)
3638 {
3639 dict_T *d;
3640
3641 if (argvars[2].v_type != VAR_DICT)
3642 {
3643 EMSG(_(e_dictreq));
3644 return;
3645 }
3646 d = argvars[2].vval.v_dict;
3647 if (d != NULL)
3648 {
3649 max_height = get_dict_number(d, (char_u *)"rows");
3650 max_width = get_dict_number(d, (char_u *)"columns");
3651 }
3652 }
3653
Bram Moolenaard96ff162018-02-18 22:13:29 +01003654 fname = get_tv_string_chk(&argvars[1]);
3655 if (fname == NULL)
3656 return;
3657 if (mch_stat((char *)fname, &st) >= 0)
3658 {
3659 EMSG2(_("E953: File exists: %s"), fname);
3660 return;
3661 }
3662
Bram Moolenaard96ff162018-02-18 22:13:29 +01003663 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3664 {
3665 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3666 return;
3667 }
3668
3669 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3670
3671 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003672 state = vterm_obtain_state(term->tl_vterm);
3673 vterm_state_get_cursorpos(state, &cursor_pos);
3674
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003675 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3676 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003677 {
3678 int repeat = 0;
3679
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003680 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3681 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003682 {
3683 VTermScreenCell cell;
3684 int same_attr;
3685 int same_chars = TRUE;
3686 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003687 int is_cursor_pos = (pos.col == cursor_pos.col
3688 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003689
3690 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3691 vim_memset(&cell, 0, sizeof(cell));
3692
3693 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3694 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003695 int c = cell.chars[i];
3696 int pc = prev_cell.chars[i];
3697
3698 /* For the first character NUL is the same as space. */
3699 if (i == 0)
3700 {
3701 c = (c == NUL) ? ' ' : c;
3702 pc = (pc == NUL) ? ' ' : pc;
3703 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003704 if (cell.chars[i] != prev_cell.chars[i])
3705 same_chars = FALSE;
3706 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3707 break;
3708 }
3709 same_attr = vtermAttr2hl(cell.attrs)
3710 == vtermAttr2hl(prev_cell.attrs)
3711 && same_color(&cell.fg, &prev_cell.fg)
3712 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003713 if (same_chars && cell.width == prev_cell.width && same_attr
3714 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003715 {
3716 ++repeat;
3717 }
3718 else
3719 {
3720 if (repeat > 0)
3721 {
3722 fprintf(fd, "@%d", repeat);
3723 repeat = 0;
3724 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003725 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003726
3727 if (cell.chars[0] == NUL)
3728 fputs(" ", fd);
3729 else
3730 {
3731 char_u charbuf[10];
3732 int len;
3733
3734 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3735 && cell.chars[i] != NUL; ++i)
3736 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003737 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003738 fwrite(charbuf, len, 1, fd);
3739 }
3740 }
3741
3742 /* When only the characters differ we don't write anything, the
3743 * following "|", "@" or NL will indicate using the same
3744 * attributes. */
3745 if (cell.width != prev_cell.width || !same_attr)
3746 {
3747 if (cell.width == 2)
3748 {
3749 fputs("*", fd);
3750 ++pos.col;
3751 }
3752 else
3753 fputs("+", fd);
3754
3755 if (same_attr)
3756 {
3757 fputs("&", fd);
3758 }
3759 else
3760 {
3761 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3762 if (same_color(&cell.fg, &prev_cell.fg))
3763 fputs("&", fd);
3764 else
3765 {
3766 fputs("#", fd);
3767 dump_term_color(fd, &cell.fg);
3768 }
3769 if (same_color(&cell.bg, &prev_cell.bg))
3770 fputs("&", fd);
3771 else
3772 {
3773 fputs("#", fd);
3774 dump_term_color(fd, &cell.bg);
3775 }
3776 }
3777 }
3778
3779 prev_cell = cell;
3780 }
3781 }
3782 if (repeat > 0)
3783 fprintf(fd, "@%d", repeat);
3784 fputs("\n", fd);
3785 }
3786
3787 fclose(fd);
3788}
3789
3790/*
3791 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3792 */
3793 static void
3794dump_is_corrupt(garray_T *gap)
3795{
3796 ga_concat(gap, (char_u *)"CORRUPT");
3797}
3798
3799 static void
3800append_cell(garray_T *gap, cellattr_T *cell)
3801{
3802 if (ga_grow(gap, 1) == OK)
3803 {
3804 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3805 ++gap->ga_len;
3806 }
3807}
3808
3809/*
3810 * Read the dump file from "fd" and append lines to the current buffer.
3811 * Return the cell width of the longest line.
3812 */
3813 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003814read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003815{
3816 int c;
3817 garray_T ga_text;
3818 garray_T ga_cell;
3819 char_u *prev_char = NULL;
3820 int attr = 0;
3821 cellattr_T cell;
3822 term_T *term = curbuf->b_term;
3823 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003824 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003825
3826 ga_init2(&ga_text, 1, 90);
3827 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3828 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003829 cursor_pos->row = -1;
3830 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003831
3832 c = fgetc(fd);
3833 for (;;)
3834 {
3835 if (c == EOF)
3836 break;
3837 if (c == '\n')
3838 {
3839 /* End of a line: append it to the buffer. */
3840 if (ga_text.ga_data == NULL)
3841 dump_is_corrupt(&ga_text);
3842 if (ga_grow(&term->tl_scrollback, 1) == OK)
3843 {
3844 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3845 + term->tl_scrollback.ga_len;
3846
3847 if (max_cells < ga_cell.ga_len)
3848 max_cells = ga_cell.ga_len;
3849 line->sb_cols = ga_cell.ga_len;
3850 line->sb_cells = ga_cell.ga_data;
3851 line->sb_fill_attr = term->tl_default_color;
3852 ++term->tl_scrollback.ga_len;
3853 ga_init(&ga_cell);
3854
3855 ga_append(&ga_text, NUL);
3856 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3857 ga_text.ga_len, FALSE);
3858 }
3859 else
3860 ga_clear(&ga_cell);
3861 ga_text.ga_len = 0;
3862
3863 c = fgetc(fd);
3864 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003865 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003866 {
3867 int prev_len = ga_text.ga_len;
3868
Bram Moolenaar9271d052018-02-25 21:39:46 +01003869 if (c == '>')
3870 {
3871 if (cursor_pos->row != -1)
3872 dump_is_corrupt(&ga_text); /* duplicate cursor */
3873 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3874 cursor_pos->col = ga_cell.ga_len;
3875 }
3876
Bram Moolenaard96ff162018-02-18 22:13:29 +01003877 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3878 c = fgetc(fd);
3879 if (c != EOF)
3880 ga_append(&ga_text, c);
3881 for (;;)
3882 {
3883 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003884 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003885 || c == EOF || c == '\n')
3886 break;
3887 ga_append(&ga_text, c);
3888 }
3889
3890 /* save the character for repeating it */
3891 vim_free(prev_char);
3892 if (ga_text.ga_data != NULL)
3893 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3894 ga_text.ga_len - prev_len);
3895
Bram Moolenaar9271d052018-02-25 21:39:46 +01003896 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003897 {
3898 /* use all attributes from previous cell */
3899 }
3900 else if (c == '+' || c == '*')
3901 {
3902 int is_bg;
3903
3904 cell.width = c == '+' ? 1 : 2;
3905
3906 c = fgetc(fd);
3907 if (c == '&')
3908 {
3909 /* use same attr as previous cell */
3910 c = fgetc(fd);
3911 }
3912 else if (isdigit(c))
3913 {
3914 /* get the decimal attribute */
3915 attr = 0;
3916 while (isdigit(c))
3917 {
3918 attr = attr * 10 + (c - '0');
3919 c = fgetc(fd);
3920 }
3921 hl2vtermAttr(attr, &cell);
3922 }
3923 else
3924 dump_is_corrupt(&ga_text);
3925
3926 /* is_bg == 0: fg, is_bg == 1: bg */
3927 for (is_bg = 0; is_bg <= 1; ++is_bg)
3928 {
3929 if (c == '&')
3930 {
3931 /* use same color as previous cell */
3932 c = fgetc(fd);
3933 }
3934 else if (c == '#')
3935 {
3936 int red, green, blue, index = 0;
3937
3938 c = fgetc(fd);
3939 red = hex2nr(c);
3940 c = fgetc(fd);
3941 red = (red << 4) + hex2nr(c);
3942 c = fgetc(fd);
3943 green = hex2nr(c);
3944 c = fgetc(fd);
3945 green = (green << 4) + hex2nr(c);
3946 c = fgetc(fd);
3947 blue = hex2nr(c);
3948 c = fgetc(fd);
3949 blue = (blue << 4) + hex2nr(c);
3950 c = fgetc(fd);
3951 if (!isdigit(c))
3952 dump_is_corrupt(&ga_text);
3953 while (isdigit(c))
3954 {
3955 index = index * 10 + (c - '0');
3956 c = fgetc(fd);
3957 }
3958
3959 if (is_bg)
3960 {
3961 cell.bg.red = red;
3962 cell.bg.green = green;
3963 cell.bg.blue = blue;
3964 cell.bg.ansi_index = index;
3965 }
3966 else
3967 {
3968 cell.fg.red = red;
3969 cell.fg.green = green;
3970 cell.fg.blue = blue;
3971 cell.fg.ansi_index = index;
3972 }
3973 }
3974 else
3975 dump_is_corrupt(&ga_text);
3976 }
3977 }
3978 else
3979 dump_is_corrupt(&ga_text);
3980
3981 append_cell(&ga_cell, &cell);
3982 }
3983 else if (c == '@')
3984 {
3985 if (prev_char == NULL)
3986 dump_is_corrupt(&ga_text);
3987 else
3988 {
3989 int count = 0;
3990
3991 /* repeat previous character, get the count */
3992 for (;;)
3993 {
3994 c = fgetc(fd);
3995 if (!isdigit(c))
3996 break;
3997 count = count * 10 + (c - '0');
3998 }
3999
4000 while (count-- > 0)
4001 {
4002 ga_concat(&ga_text, prev_char);
4003 append_cell(&ga_cell, &cell);
4004 }
4005 }
4006 }
4007 else
4008 {
4009 dump_is_corrupt(&ga_text);
4010 c = fgetc(fd);
4011 }
4012 }
4013
4014 if (ga_text.ga_len > 0)
4015 {
4016 /* trailing characters after last NL */
4017 dump_is_corrupt(&ga_text);
4018 ga_append(&ga_text, NUL);
4019 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4020 ga_text.ga_len, FALSE);
4021 }
4022
4023 ga_clear(&ga_text);
4024 vim_free(prev_char);
4025
4026 return max_cells;
4027}
4028
4029/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004030 * Return an allocated string with at least "text_width" "=" characters and
4031 * "fname" inserted in the middle.
4032 */
4033 static char_u *
4034get_separator(int text_width, char_u *fname)
4035{
4036 int width = MAX(text_width, curwin->w_width);
4037 char_u *textline;
4038 int fname_size;
4039 char_u *p = fname;
4040 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004041 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004042
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004043 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004044 if (textline == NULL)
4045 return NULL;
4046
4047 fname_size = vim_strsize(fname);
4048 if (fname_size < width - 8)
4049 {
4050 /* enough room, don't use the full window width */
4051 width = MAX(text_width, fname_size + 8);
4052 }
4053 else if (fname_size > width - 8)
4054 {
4055 /* full name doesn't fit, use only the tail */
4056 p = gettail(fname);
4057 fname_size = vim_strsize(p);
4058 }
4059 /* skip characters until the name fits */
4060 while (fname_size > width - 8)
4061 {
4062 p += (*mb_ptr2len)(p);
4063 fname_size = vim_strsize(p);
4064 }
4065
4066 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4067 textline[i] = '=';
4068 textline[i++] = ' ';
4069
4070 STRCPY(textline + i, p);
4071 off = STRLEN(textline);
4072 textline[off] = ' ';
4073 for (i = 1; i < (width - fname_size) / 2; ++i)
4074 textline[off + i] = '=';
4075 textline[off + i] = NUL;
4076
4077 return textline;
4078}
4079
4080/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004081 * Common for "term_dumpdiff()" and "term_dumpload()".
4082 */
4083 static void
4084term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4085{
4086 jobopt_T opt;
4087 buf_T *buf;
4088 char_u buf1[NUMBUFLEN];
4089 char_u buf2[NUMBUFLEN];
4090 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004091 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004092 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004093 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004094 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004095 char_u *textline = NULL;
4096
4097 /* First open the files. If this fails bail out. */
4098 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4099 if (do_diff)
4100 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4101 if (fname1 == NULL || (do_diff && fname2 == NULL))
4102 {
4103 EMSG(_(e_invarg));
4104 return;
4105 }
4106 fd1 = mch_fopen((char *)fname1, READBIN);
4107 if (fd1 == NULL)
4108 {
4109 EMSG2(_(e_notread), fname1);
4110 return;
4111 }
4112 if (do_diff)
4113 {
4114 fd2 = mch_fopen((char *)fname2, READBIN);
4115 if (fd2 == NULL)
4116 {
4117 fclose(fd1);
4118 EMSG2(_(e_notread), fname2);
4119 return;
4120 }
4121 }
4122
4123 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004124 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4125 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4126 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4127 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4128 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004129
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004130 if (opt.jo_term_name == NULL)
4131 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004132 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004133
Bram Moolenaarb571c632018-03-21 22:27:59 +01004134 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004135 if (fname_tofree != NULL)
4136 {
4137 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4138 opt.jo_term_name = fname_tofree;
4139 }
4140 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004141
Bram Moolenaar13568252018-03-16 20:46:58 +01004142 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004143 if (buf != NULL && buf->b_term != NULL)
4144 {
4145 int i;
4146 linenr_T bot_lnum;
4147 linenr_T lnum;
4148 term_T *term = buf->b_term;
4149 int width;
4150 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004151 VTermPos cursor_pos1;
4152 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004153
Bram Moolenaar52acb112018-03-18 19:20:22 +01004154 init_default_colors(term);
4155
Bram Moolenaard96ff162018-02-18 22:13:29 +01004156 rettv->vval.v_number = buf->b_fnum;
4157
4158 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004159 width = read_dump_file(fd1, &cursor_pos1);
4160
4161 /* position the cursor */
4162 if (cursor_pos1.row >= 0)
4163 {
4164 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4165 coladvance(cursor_pos1.col);
4166 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004167
4168 /* Delete the empty line that was in the empty buffer. */
4169 ml_delete(1, FALSE);
4170
4171 /* For term_dumpload() we are done here. */
4172 if (!do_diff)
4173 goto theend;
4174
4175 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4176
Bram Moolenaar4a696342018-04-05 18:45:26 +02004177 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004178 if (textline == NULL)
4179 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004180 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4181 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4182 vim_free(textline);
4183
4184 textline = get_separator(width, fname2);
4185 if (textline == NULL)
4186 goto theend;
4187 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4188 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004189 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004190
4191 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004192 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004193 if (width2 > width)
4194 {
4195 vim_free(textline);
4196 textline = alloc(width2 + 1);
4197 if (textline == NULL)
4198 goto theend;
4199 width = width2;
4200 textline[width] = NUL;
4201 }
4202 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4203
4204 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4205 {
4206 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4207 {
4208 /* bottom part has fewer rows, fill with "-" */
4209 for (i = 0; i < width; ++i)
4210 textline[i] = '-';
4211 }
4212 else
4213 {
4214 char_u *line1;
4215 char_u *line2;
4216 char_u *p1;
4217 char_u *p2;
4218 int col;
4219 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4220 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4221 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4222 ->sb_cells;
4223
4224 /* Make a copy, getting the second line will invalidate it. */
4225 line1 = vim_strsave(ml_get(lnum));
4226 if (line1 == NULL)
4227 break;
4228 p1 = line1;
4229
4230 line2 = ml_get(lnum + bot_lnum);
4231 p2 = line2;
4232 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4233 {
4234 int len1 = utfc_ptr2len(p1);
4235 int len2 = utfc_ptr2len(p2);
4236
4237 textline[col] = ' ';
4238 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004239 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004240 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004241 else if (lnum == cursor_pos1.row + 1
4242 && col == cursor_pos1.col
4243 && (cursor_pos1.row != cursor_pos2.row
4244 || cursor_pos1.col != cursor_pos2.col))
4245 /* cursor in first but not in second */
4246 textline[col] = '>';
4247 else if (lnum == cursor_pos2.row + 1
4248 && col == cursor_pos2.col
4249 && (cursor_pos1.row != cursor_pos2.row
4250 || cursor_pos1.col != cursor_pos2.col))
4251 /* cursor in second but not in first */
4252 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004253 else if (cellattr1 != NULL && cellattr2 != NULL)
4254 {
4255 if ((cellattr1 + col)->width
4256 != (cellattr2 + col)->width)
4257 textline[col] = 'w';
4258 else if (!same_color(&(cellattr1 + col)->fg,
4259 &(cellattr2 + col)->fg))
4260 textline[col] = 'f';
4261 else if (!same_color(&(cellattr1 + col)->bg,
4262 &(cellattr2 + col)->bg))
4263 textline[col] = 'b';
4264 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4265 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4266 textline[col] = 'a';
4267 }
4268 p1 += len1;
4269 p2 += len2;
4270 /* TODO: handle different width */
4271 }
4272 vim_free(line1);
4273
4274 while (col < width)
4275 {
4276 if (*p1 == NUL && *p2 == NUL)
4277 textline[col] = '?';
4278 else if (*p1 == NUL)
4279 {
4280 textline[col] = '+';
4281 p2 += utfc_ptr2len(p2);
4282 }
4283 else
4284 {
4285 textline[col] = '-';
4286 p1 += utfc_ptr2len(p1);
4287 }
4288 ++col;
4289 }
4290 }
4291 if (add_empty_scrollback(term, &term->tl_default_color,
4292 term->tl_top_diff_rows) == OK)
4293 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4294 ++bot_lnum;
4295 }
4296
4297 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4298 {
4299 /* bottom part has more rows, fill with "+" */
4300 for (i = 0; i < width; ++i)
4301 textline[i] = '+';
4302 if (add_empty_scrollback(term, &term->tl_default_color,
4303 term->tl_top_diff_rows) == OK)
4304 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4305 ++lnum;
4306 ++bot_lnum;
4307 }
4308
4309 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004310
4311 /* looks better without wrapping */
4312 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004313 }
4314
4315theend:
4316 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004317 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004318 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004319 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320 fclose(fd2);
4321}
4322
4323/*
4324 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4325 * bottom files.
4326 * Return FAIL when this is not possible.
4327 */
4328 int
4329term_swap_diff()
4330{
4331 term_T *term = curbuf->b_term;
4332 linenr_T line_count;
4333 linenr_T top_rows;
4334 linenr_T bot_rows;
4335 linenr_T bot_start;
4336 linenr_T lnum;
4337 char_u *p;
4338 sb_line_T *sb_line;
4339
4340 if (term == NULL
4341 || !term_is_finished(curbuf)
4342 || term->tl_top_diff_rows == 0
4343 || term->tl_scrollback.ga_len == 0)
4344 return FAIL;
4345
4346 line_count = curbuf->b_ml.ml_line_count;
4347 top_rows = term->tl_top_diff_rows;
4348 bot_rows = term->tl_bot_diff_rows;
4349 bot_start = line_count - bot_rows;
4350 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4351
4352 /* move lines from top to above the bottom part */
4353 for (lnum = 1; lnum <= top_rows; ++lnum)
4354 {
4355 p = vim_strsave(ml_get(1));
4356 if (p == NULL)
4357 return OK;
4358 ml_append(bot_start, p, 0, FALSE);
4359 ml_delete(1, FALSE);
4360 vim_free(p);
4361 }
4362
4363 /* move lines from bottom to the top */
4364 for (lnum = 1; lnum <= bot_rows; ++lnum)
4365 {
4366 p = vim_strsave(ml_get(bot_start + lnum));
4367 if (p == NULL)
4368 return OK;
4369 ml_delete(bot_start + lnum, FALSE);
4370 ml_append(lnum - 1, p, 0, FALSE);
4371 vim_free(p);
4372 }
4373
4374 if (top_rows == bot_rows)
4375 {
4376 /* rows counts are equal, can swap cell properties */
4377 for (lnum = 0; lnum < top_rows; ++lnum)
4378 {
4379 sb_line_T temp;
4380
4381 temp = *(sb_line + lnum);
4382 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4383 *(sb_line + bot_start + lnum) = temp;
4384 }
4385 }
4386 else
4387 {
4388 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4389 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4390
4391 /* need to copy cell properties into temp memory */
4392 if (temp != NULL)
4393 {
4394 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4395 mch_memmove(term->tl_scrollback.ga_data,
4396 temp + bot_start,
4397 sizeof(sb_line_T) * bot_rows);
4398 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4399 temp + top_rows,
4400 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4401 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4402 + line_count - top_rows,
4403 temp,
4404 sizeof(sb_line_T) * top_rows);
4405 vim_free(temp);
4406 }
4407 }
4408
4409 term->tl_top_diff_rows = bot_rows;
4410 term->tl_bot_diff_rows = top_rows;
4411
4412 update_screen(NOT_VALID);
4413 return OK;
4414}
4415
4416/*
4417 * "term_dumpdiff(filename, filename, options)" function
4418 */
4419 void
4420f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4421{
4422 term_load_dump(argvars, rettv, TRUE);
4423}
4424
4425/*
4426 * "term_dumpload(filename, options)" function
4427 */
4428 void
4429f_term_dumpload(typval_T *argvars, typval_T *rettv)
4430{
4431 term_load_dump(argvars, rettv, FALSE);
4432}
4433
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004434/*
4435 * "term_getaltscreen(buf)" function
4436 */
4437 void
4438f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4439{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004440 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004441
4442 if (buf == NULL)
4443 return;
4444 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4445}
4446
4447/*
4448 * "term_getattr(attr, name)" function
4449 */
4450 void
4451f_term_getattr(typval_T *argvars, typval_T *rettv)
4452{
4453 int attr;
4454 size_t i;
4455 char_u *name;
4456
4457 static struct {
4458 char *name;
4459 int attr;
4460 } attrs[] = {
4461 {"bold", HL_BOLD},
4462 {"italic", HL_ITALIC},
4463 {"underline", HL_UNDERLINE},
4464 {"strike", HL_STRIKETHROUGH},
4465 {"reverse", HL_INVERSE},
4466 };
4467
4468 attr = get_tv_number(&argvars[0]);
4469 name = get_tv_string_chk(&argvars[1]);
4470 if (name == NULL)
4471 return;
4472
4473 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4474 if (STRCMP(name, attrs[i].name) == 0)
4475 {
4476 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4477 break;
4478 }
4479}
4480
4481/*
4482 * "term_getcursor(buf)" function
4483 */
4484 void
4485f_term_getcursor(typval_T *argvars, typval_T *rettv)
4486{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004487 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004488 term_T *term;
4489 list_T *l;
4490 dict_T *d;
4491
4492 if (rettv_list_alloc(rettv) == FAIL)
4493 return;
4494 if (buf == NULL)
4495 return;
4496 term = buf->b_term;
4497
4498 l = rettv->vval.v_list;
4499 list_append_number(l, term->tl_cursor_pos.row + 1);
4500 list_append_number(l, term->tl_cursor_pos.col + 1);
4501
4502 d = dict_alloc();
4503 if (d != NULL)
4504 {
4505 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4506 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4507 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4508 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4509 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4510 ? (char_u *)"" : term->tl_cursor_color);
4511 list_append_dict(l, d);
4512 }
4513}
4514
4515/*
4516 * "term_getjob(buf)" function
4517 */
4518 void
4519f_term_getjob(typval_T *argvars, typval_T *rettv)
4520{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004521 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004522
4523 rettv->v_type = VAR_JOB;
4524 rettv->vval.v_job = NULL;
4525 if (buf == NULL)
4526 return;
4527
4528 rettv->vval.v_job = buf->b_term->tl_job;
4529 if (rettv->vval.v_job != NULL)
4530 ++rettv->vval.v_job->jv_refcount;
4531}
4532
4533 static int
4534get_row_number(typval_T *tv, term_T *term)
4535{
4536 if (tv->v_type == VAR_STRING
4537 && tv->vval.v_string != NULL
4538 && STRCMP(tv->vval.v_string, ".") == 0)
4539 return term->tl_cursor_pos.row;
4540 return (int)get_tv_number(tv) - 1;
4541}
4542
4543/*
4544 * "term_getline(buf, row)" function
4545 */
4546 void
4547f_term_getline(typval_T *argvars, typval_T *rettv)
4548{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004549 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004550 term_T *term;
4551 int row;
4552
4553 rettv->v_type = VAR_STRING;
4554 if (buf == NULL)
4555 return;
4556 term = buf->b_term;
4557 row = get_row_number(&argvars[1], term);
4558
4559 if (term->tl_vterm == NULL)
4560 {
4561 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4562
4563 /* vterm is finished, get the text from the buffer */
4564 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4565 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4566 }
4567 else
4568 {
4569 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4570 VTermRect rect;
4571 int len;
4572 char_u *p;
4573
4574 if (row < 0 || row >= term->tl_rows)
4575 return;
4576 len = term->tl_cols * MB_MAXBYTES + 1;
4577 p = alloc(len);
4578 if (p == NULL)
4579 return;
4580 rettv->vval.v_string = p;
4581
4582 rect.start_col = 0;
4583 rect.end_col = term->tl_cols;
4584 rect.start_row = row;
4585 rect.end_row = row + 1;
4586 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4587 }
4588}
4589
4590/*
4591 * "term_getscrolled(buf)" function
4592 */
4593 void
4594f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4595{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004596 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004597
4598 if (buf == NULL)
4599 return;
4600 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4601}
4602
4603/*
4604 * "term_getsize(buf)" function
4605 */
4606 void
4607f_term_getsize(typval_T *argvars, typval_T *rettv)
4608{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004609 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004610 list_T *l;
4611
4612 if (rettv_list_alloc(rettv) == FAIL)
4613 return;
4614 if (buf == NULL)
4615 return;
4616
4617 l = rettv->vval.v_list;
4618 list_append_number(l, buf->b_term->tl_rows);
4619 list_append_number(l, buf->b_term->tl_cols);
4620}
4621
4622/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004623 * "term_setsize(buf, rows, cols)" function
4624 */
4625 void
4626f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4627{
4628 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4629 term_T *term;
4630 varnumber_T rows, cols;
4631
4632 if (buf == NULL || buf->b_term->tl_vterm == NULL)
4633 return;
4634 term = buf->b_term;
4635 rows = get_tv_number(&argvars[1]);
4636 rows = rows <= 0 ? term->tl_rows : rows;
4637 cols = get_tv_number(&argvars[2]);
4638 cols = cols <= 0 ? term->tl_cols : cols;
4639 vterm_set_size(term->tl_vterm, rows, cols);
4640 /* handle_resize() will resize the windows */
4641
4642 /* Get and remember the size we ended up with. Update the pty. */
4643 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4644 term_report_winsize(term, term->tl_rows, term->tl_cols);
4645}
4646
4647/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004648 * "term_getstatus(buf)" function
4649 */
4650 void
4651f_term_getstatus(typval_T *argvars, typval_T *rettv)
4652{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004653 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004654 term_T *term;
4655 char_u val[100];
4656
4657 rettv->v_type = VAR_STRING;
4658 if (buf == NULL)
4659 return;
4660 term = buf->b_term;
4661
4662 if (term_job_running(term))
4663 STRCPY(val, "running");
4664 else
4665 STRCPY(val, "finished");
4666 if (term->tl_normal_mode)
4667 STRCAT(val, ",normal");
4668 rettv->vval.v_string = vim_strsave(val);
4669}
4670
4671/*
4672 * "term_gettitle(buf)" function
4673 */
4674 void
4675f_term_gettitle(typval_T *argvars, typval_T *rettv)
4676{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004677 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004678
4679 rettv->v_type = VAR_STRING;
4680 if (buf == NULL)
4681 return;
4682
4683 if (buf->b_term->tl_title != NULL)
4684 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4685}
4686
4687/*
4688 * "term_gettty(buf)" function
4689 */
4690 void
4691f_term_gettty(typval_T *argvars, typval_T *rettv)
4692{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004693 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004694 char_u *p;
4695 int num = 0;
4696
4697 rettv->v_type = VAR_STRING;
4698 if (buf == NULL)
4699 return;
4700 if (argvars[1].v_type != VAR_UNKNOWN)
4701 num = get_tv_number(&argvars[1]);
4702
4703 switch (num)
4704 {
4705 case 0:
4706 if (buf->b_term->tl_job != NULL)
4707 p = buf->b_term->tl_job->jv_tty_out;
4708 else
4709 p = buf->b_term->tl_tty_out;
4710 break;
4711 case 1:
4712 if (buf->b_term->tl_job != NULL)
4713 p = buf->b_term->tl_job->jv_tty_in;
4714 else
4715 p = buf->b_term->tl_tty_in;
4716 break;
4717 default:
4718 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4719 return;
4720 }
4721 if (p != NULL)
4722 rettv->vval.v_string = vim_strsave(p);
4723}
4724
4725/*
4726 * "term_list()" function
4727 */
4728 void
4729f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4730{
4731 term_T *tp;
4732 list_T *l;
4733
4734 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4735 return;
4736
4737 l = rettv->vval.v_list;
4738 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4739 if (tp != NULL && tp->tl_buffer != NULL)
4740 if (list_append_number(l,
4741 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4742 return;
4743}
4744
4745/*
4746 * "term_scrape(buf, row)" function
4747 */
4748 void
4749f_term_scrape(typval_T *argvars, typval_T *rettv)
4750{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004751 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004752 VTermScreen *screen = NULL;
4753 VTermPos pos;
4754 list_T *l;
4755 term_T *term;
4756 char_u *p;
4757 sb_line_T *line;
4758
4759 if (rettv_list_alloc(rettv) == FAIL)
4760 return;
4761 if (buf == NULL)
4762 return;
4763 term = buf->b_term;
4764
4765 l = rettv->vval.v_list;
4766 pos.row = get_row_number(&argvars[1], term);
4767
4768 if (term->tl_vterm != NULL)
4769 {
4770 screen = vterm_obtain_screen(term->tl_vterm);
4771 p = NULL;
4772 line = NULL;
4773 }
4774 else
4775 {
4776 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4777
4778 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4779 return;
4780 p = ml_get_buf(buf, lnum + 1, FALSE);
4781 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4782 }
4783
4784 for (pos.col = 0; pos.col < term->tl_cols; )
4785 {
4786 dict_T *dcell;
4787 int width;
4788 VTermScreenCellAttrs attrs;
4789 VTermColor fg, bg;
4790 char_u rgb[8];
4791 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4792 int off = 0;
4793 int i;
4794
4795 if (screen == NULL)
4796 {
4797 cellattr_T *cellattr;
4798 int len;
4799
4800 /* vterm has finished, get the cell from scrollback */
4801 if (pos.col >= line->sb_cols)
4802 break;
4803 cellattr = line->sb_cells + pos.col;
4804 width = cellattr->width;
4805 attrs = cellattr->attrs;
4806 fg = cellattr->fg;
4807 bg = cellattr->bg;
4808 len = MB_PTR2LEN(p);
4809 mch_memmove(mbs, p, len);
4810 mbs[len] = NUL;
4811 p += len;
4812 }
4813 else
4814 {
4815 VTermScreenCell cell;
4816 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4817 break;
4818 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4819 {
4820 if (cell.chars[i] == 0)
4821 break;
4822 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4823 }
4824 mbs[off] = NUL;
4825 width = cell.width;
4826 attrs = cell.attrs;
4827 fg = cell.fg;
4828 bg = cell.bg;
4829 }
4830 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004831 if (dcell == NULL)
4832 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004833 list_append_dict(l, dcell);
4834
4835 dict_add_nr_str(dcell, "chars", 0, mbs);
4836
4837 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4838 fg.red, fg.green, fg.blue);
4839 dict_add_nr_str(dcell, "fg", 0, rgb);
4840 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4841 bg.red, bg.green, bg.blue);
4842 dict_add_nr_str(dcell, "bg", 0, rgb);
4843
4844 dict_add_nr_str(dcell, "attr",
4845 cell2attr(attrs, fg, bg), NULL);
4846 dict_add_nr_str(dcell, "width", width, NULL);
4847
4848 ++pos.col;
4849 if (width == 2)
4850 ++pos.col;
4851 }
4852}
4853
4854/*
4855 * "term_sendkeys(buf, keys)" function
4856 */
4857 void
4858f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4859{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004860 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004861 char_u *msg;
4862 term_T *term;
4863
4864 rettv->v_type = VAR_UNKNOWN;
4865 if (buf == NULL)
4866 return;
4867
4868 msg = get_tv_string_chk(&argvars[1]);
4869 if (msg == NULL)
4870 return;
4871 term = buf->b_term;
4872 if (term->tl_vterm == NULL)
4873 return;
4874
4875 while (*msg != NUL)
4876 {
4877 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004878 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004879 }
4880}
4881
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004882#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4883/*
4884 * "term_getansicolors(buf)" function
4885 */
4886 void
4887f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4888{
4889 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4890 term_T *term;
4891 VTermState *state;
4892 VTermColor color;
4893 char_u hexbuf[10];
4894 int index;
4895 list_T *list;
4896
4897 if (rettv_list_alloc(rettv) == FAIL)
4898 return;
4899
4900 if (buf == NULL)
4901 return;
4902 term = buf->b_term;
4903 if (term->tl_vterm == NULL)
4904 return;
4905
4906 list = rettv->vval.v_list;
4907 state = vterm_obtain_state(term->tl_vterm);
4908 for (index = 0; index < 16; index++)
4909 {
4910 vterm_state_get_palette_color(state, index, &color);
4911 sprintf((char *)hexbuf, "#%02x%02x%02x",
4912 color.red, color.green, color.blue);
4913 if (list_append_string(list, hexbuf, 7) == FAIL)
4914 return;
4915 }
4916}
4917
4918/*
4919 * "term_setansicolors(buf, list)" function
4920 */
4921 void
4922f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4923{
4924 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4925 term_T *term;
4926
4927 if (buf == NULL)
4928 return;
4929 term = buf->b_term;
4930 if (term->tl_vterm == NULL)
4931 return;
4932
4933 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4934 {
4935 EMSG(_(e_listreq));
4936 return;
4937 }
4938
4939 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4940 EMSG(_(e_invarg));
4941}
4942#endif
4943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004944/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004945 * "term_setrestore(buf, command)" function
4946 */
4947 void
4948f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4949{
4950#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004951 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004952 term_T *term;
4953 char_u *cmd;
4954
4955 if (buf == NULL)
4956 return;
4957 term = buf->b_term;
4958 vim_free(term->tl_command);
4959 cmd = get_tv_string_chk(&argvars[1]);
4960 if (cmd != NULL)
4961 term->tl_command = vim_strsave(cmd);
4962 else
4963 term->tl_command = NULL;
4964#endif
4965}
4966
4967/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004968 * "term_setkill(buf, how)" function
4969 */
4970 void
4971f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4972{
4973 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4974 term_T *term;
4975 char_u *how;
4976
4977 if (buf == NULL)
4978 return;
4979 term = buf->b_term;
4980 vim_free(term->tl_kill);
4981 how = get_tv_string_chk(&argvars[1]);
4982 if (how != NULL)
4983 term->tl_kill = vim_strsave(how);
4984 else
4985 term->tl_kill = NULL;
4986}
4987
4988/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004989 * "term_start(command, options)" function
4990 */
4991 void
4992f_term_start(typval_T *argvars, typval_T *rettv)
4993{
4994 jobopt_T opt;
4995 buf_T *buf;
4996
4997 init_job_options(&opt);
4998 if (argvars[1].v_type != VAR_UNKNOWN
4999 && get_job_options(&argvars[1], &opt,
5000 JO_TIMEOUT_ALL + JO_STOPONEXIT
5001 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5002 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5003 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5004 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005005 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005006 + JO2_NORESTORE + JO2_TERM_KILL
5007 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005008 return;
5009
Bram Moolenaar13568252018-03-16 20:46:58 +01005010 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005011
5012 if (buf != NULL && buf->b_term != NULL)
5013 rettv->vval.v_number = buf->b_fnum;
5014}
5015
5016/*
5017 * "term_wait" function
5018 */
5019 void
5020f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5021{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005022 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005023
5024 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005025 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005026 if (buf->b_term->tl_job == NULL)
5027 {
5028 ch_log(NULL, "term_wait(): no job to wait for");
5029 return;
5030 }
5031 if (buf->b_term->tl_job->jv_channel == NULL)
5032 /* channel is closed, nothing to do */
5033 return;
5034
5035 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005036 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005037 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5038 {
5039 /* The job is dead, keep reading channel I/O until the channel is
5040 * closed. buf->b_term may become NULL if the terminal was closed while
5041 * waiting. */
5042 ch_log(NULL, "term_wait(): waiting for channel to close");
5043 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5044 {
5045 mch_check_messages();
5046 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005047 if (!buf_valid(buf))
5048 /* If the terminal is closed when the channel is closed the
5049 * buffer disappears. */
5050 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005051 ui_delay(10L, FALSE);
5052 }
5053 mch_check_messages();
5054 parse_queued_messages();
5055 }
5056 else
5057 {
5058 long wait = 10L;
5059
5060 mch_check_messages();
5061 parse_queued_messages();
5062
5063 /* Wait for some time for any channel I/O. */
5064 if (argvars[1].v_type != VAR_UNKNOWN)
5065 wait = get_tv_number(&argvars[1]);
5066 ui_delay(wait, TRUE);
5067 mch_check_messages();
5068
5069 /* Flushing messages on channels is hopefully sufficient.
5070 * TODO: is there a better way? */
5071 parse_queued_messages();
5072 }
5073}
5074
5075/*
5076 * Called when a channel has sent all the lines to a terminal.
5077 * Send a CTRL-D to mark the end of the text.
5078 */
5079 void
5080term_send_eof(channel_T *ch)
5081{
5082 term_T *term;
5083
5084 for (term = first_term; term != NULL; term = term->tl_next)
5085 if (term->tl_job == ch->ch_job)
5086 {
5087 if (term->tl_eof_chars != NULL)
5088 {
5089 channel_send(ch, PART_IN, term->tl_eof_chars,
5090 (int)STRLEN(term->tl_eof_chars), NULL);
5091 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5092 }
5093# ifdef WIN3264
5094 else
5095 /* Default: CTRL-D */
5096 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5097# endif
5098 }
5099}
5100
5101# if defined(WIN3264) || defined(PROTO)
5102
5103/**************************************
5104 * 2. MS-Windows implementation.
5105 */
5106
5107# ifndef PROTO
5108
5109#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5110#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005111#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005112
5113void* (*winpty_config_new)(UINT64, void*);
5114void* (*winpty_open)(void*, void*);
5115void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5116BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5117void (*winpty_config_set_mouse_mode)(void*, int);
5118void (*winpty_config_set_initial_size)(void*, int, int);
5119LPCWSTR (*winpty_conin_name)(void*);
5120LPCWSTR (*winpty_conout_name)(void*);
5121LPCWSTR (*winpty_conerr_name)(void*);
5122void (*winpty_free)(void*);
5123void (*winpty_config_free)(void*);
5124void (*winpty_spawn_config_free)(void*);
5125void (*winpty_error_free)(void*);
5126LPCWSTR (*winpty_error_msg)(void*);
5127BOOL (*winpty_set_size)(void*, int, int, void*);
5128HANDLE (*winpty_agent_process)(void*);
5129
5130#define WINPTY_DLL "winpty.dll"
5131
5132static HINSTANCE hWinPtyDLL = NULL;
5133# endif
5134
5135 static int
5136dyn_winpty_init(int verbose)
5137{
5138 int i;
5139 static struct
5140 {
5141 char *name;
5142 FARPROC *ptr;
5143 } winpty_entry[] =
5144 {
5145 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5146 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5147 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5148 {"winpty_config_set_mouse_mode",
5149 (FARPROC*)&winpty_config_set_mouse_mode},
5150 {"winpty_config_set_initial_size",
5151 (FARPROC*)&winpty_config_set_initial_size},
5152 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5153 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5154 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5155 {"winpty_free", (FARPROC*)&winpty_free},
5156 {"winpty_open", (FARPROC*)&winpty_open},
5157 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5158 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5159 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5160 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5161 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5162 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5163 {NULL, NULL}
5164 };
5165
5166 /* No need to initialize twice. */
5167 if (hWinPtyDLL)
5168 return OK;
5169 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5170 * winpty.dll. */
5171 if (*p_winptydll != NUL)
5172 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5173 if (!hWinPtyDLL)
5174 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5175 if (!hWinPtyDLL)
5176 {
5177 if (verbose)
5178 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5179 : (char_u *)WINPTY_DLL);
5180 return FAIL;
5181 }
5182 for (i = 0; winpty_entry[i].name != NULL
5183 && winpty_entry[i].ptr != NULL; ++i)
5184 {
5185 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5186 winpty_entry[i].name)) == NULL)
5187 {
5188 if (verbose)
5189 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5190 return FAIL;
5191 }
5192 }
5193
5194 return OK;
5195}
5196
5197/*
5198 * Create a new terminal of "rows" by "cols" cells.
5199 * Store a reference in "term".
5200 * Return OK or FAIL.
5201 */
5202 static int
5203term_and_job_init(
5204 term_T *term,
5205 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005206 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005207 jobopt_T *opt)
5208{
5209 WCHAR *cmd_wchar = NULL;
5210 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005211 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005212 channel_T *channel = NULL;
5213 job_T *job = NULL;
5214 DWORD error;
5215 HANDLE jo = NULL;
5216 HANDLE child_process_handle;
5217 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005218 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005219 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005220 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005221 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005222
5223 if (dyn_winpty_init(TRUE) == FAIL)
5224 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005225 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5226 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005227
5228 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005229 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005230 cmd = argvar->vval.v_string;
5231 }
5232 else if (argvar->v_type == VAR_LIST)
5233 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005234 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005235 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005236 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005237 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005238 if (cmd == NULL || *cmd == NUL)
5239 {
5240 EMSG(_(e_invarg));
5241 goto failed;
5242 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005243
5244 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005245 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005246 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005247 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005248 if (opt->jo_cwd != NULL)
5249 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005250
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005251 win32_build_env(opt->jo_env, &ga_env, TRUE);
5252 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005253
5254 job = job_alloc();
5255 if (job == NULL)
5256 goto failed;
5257
5258 channel = add_channel();
5259 if (channel == NULL)
5260 goto failed;
5261
5262 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5263 if (term->tl_winpty_config == NULL)
5264 goto failed;
5265
5266 winpty_config_set_mouse_mode(term->tl_winpty_config,
5267 WINPTY_MOUSE_MODE_FORCE);
5268 winpty_config_set_initial_size(term->tl_winpty_config,
5269 term->tl_cols, term->tl_rows);
5270 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5271 if (term->tl_winpty == NULL)
5272 goto failed;
5273
5274 spawn_config = winpty_spawn_config_new(
5275 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5276 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5277 NULL,
5278 cmd_wchar,
5279 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005280 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005281 &winpty_err);
5282 if (spawn_config == NULL)
5283 goto failed;
5284
5285 channel = add_channel();
5286 if (channel == NULL)
5287 goto failed;
5288
5289 job = job_alloc();
5290 if (job == NULL)
5291 goto failed;
5292
5293 if (opt->jo_set & JO_IN_BUF)
5294 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5295
5296 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5297 &child_thread_handle, &error, &winpty_err))
5298 goto failed;
5299
5300 channel_set_pipes(channel,
5301 (sock_T)CreateFileW(
5302 winpty_conin_name(term->tl_winpty),
5303 GENERIC_WRITE, 0, NULL,
5304 OPEN_EXISTING, 0, NULL),
5305 (sock_T)CreateFileW(
5306 winpty_conout_name(term->tl_winpty),
5307 GENERIC_READ, 0, NULL,
5308 OPEN_EXISTING, 0, NULL),
5309 (sock_T)CreateFileW(
5310 winpty_conerr_name(term->tl_winpty),
5311 GENERIC_READ, 0, NULL,
5312 OPEN_EXISTING, 0, NULL));
5313
5314 /* Write lines with CR instead of NL. */
5315 channel->ch_write_text_mode = TRUE;
5316
5317 jo = CreateJobObject(NULL, NULL);
5318 if (jo == NULL)
5319 goto failed;
5320
5321 if (!AssignProcessToJobObject(jo, child_process_handle))
5322 {
5323 /* Failed, switch the way to terminate process with TerminateProcess. */
5324 CloseHandle(jo);
5325 jo = NULL;
5326 }
5327
5328 winpty_spawn_config_free(spawn_config);
5329 vim_free(cmd_wchar);
5330 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005331 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005332
5333 create_vterm(term, term->tl_rows, term->tl_cols);
5334
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005335#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5336 if (opt->jo_set2 & JO2_ANSI_COLORS)
5337 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5338 else
5339 init_vterm_ansi_colors(term->tl_vterm);
5340#endif
5341
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005342 channel_set_job(channel, job, opt);
5343 job_set_options(job, opt);
5344
5345 job->jv_channel = channel;
5346 job->jv_proc_info.hProcess = child_process_handle;
5347 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5348 job->jv_job_object = jo;
5349 job->jv_status = JOB_STARTED;
5350 job->jv_tty_in = utf16_to_enc(
5351 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5352 job->jv_tty_out = utf16_to_enc(
5353 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5354 ++job->jv_refcount;
5355 term->tl_job = job;
5356
5357 return OK;
5358
5359failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005360 ga_clear(&ga_cmd);
5361 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005362 vim_free(cmd_wchar);
5363 vim_free(cwd_wchar);
5364 if (spawn_config != NULL)
5365 winpty_spawn_config_free(spawn_config);
5366 if (channel != NULL)
5367 channel_clear(channel);
5368 if (job != NULL)
5369 {
5370 job->jv_channel = NULL;
5371 job_cleanup(job);
5372 }
5373 term->tl_job = NULL;
5374 if (jo != NULL)
5375 CloseHandle(jo);
5376 if (term->tl_winpty != NULL)
5377 winpty_free(term->tl_winpty);
5378 term->tl_winpty = NULL;
5379 if (term->tl_winpty_config != NULL)
5380 winpty_config_free(term->tl_winpty_config);
5381 term->tl_winpty_config = NULL;
5382 if (winpty_err != NULL)
5383 {
5384 char_u *msg = utf16_to_enc(
5385 (short_u *)winpty_error_msg(winpty_err), NULL);
5386
5387 EMSG(msg);
5388 winpty_error_free(winpty_err);
5389 }
5390 return FAIL;
5391}
5392
5393 static int
5394create_pty_only(term_T *term, jobopt_T *options)
5395{
5396 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5397 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5398 char in_name[80], out_name[80];
5399 channel_T *channel = NULL;
5400
5401 create_vterm(term, term->tl_rows, term->tl_cols);
5402
5403 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5404 GetCurrentProcessId(),
5405 curbuf->b_fnum);
5406 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5407 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5408 PIPE_UNLIMITED_INSTANCES,
5409 0, 0, NMPWAIT_NOWAIT, NULL);
5410 if (hPipeIn == INVALID_HANDLE_VALUE)
5411 goto failed;
5412
5413 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5414 GetCurrentProcessId(),
5415 curbuf->b_fnum);
5416 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5417 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5418 PIPE_UNLIMITED_INSTANCES,
5419 0, 0, 0, NULL);
5420 if (hPipeOut == INVALID_HANDLE_VALUE)
5421 goto failed;
5422
5423 ConnectNamedPipe(hPipeIn, NULL);
5424 ConnectNamedPipe(hPipeOut, NULL);
5425
5426 term->tl_job = job_alloc();
5427 if (term->tl_job == NULL)
5428 goto failed;
5429 ++term->tl_job->jv_refcount;
5430
5431 /* behave like the job is already finished */
5432 term->tl_job->jv_status = JOB_FINISHED;
5433
5434 channel = add_channel();
5435 if (channel == NULL)
5436 goto failed;
5437 term->tl_job->jv_channel = channel;
5438 channel->ch_keep_open = TRUE;
5439 channel->ch_named_pipe = TRUE;
5440
5441 channel_set_pipes(channel,
5442 (sock_T)hPipeIn,
5443 (sock_T)hPipeOut,
5444 (sock_T)hPipeOut);
5445 channel_set_job(channel, term->tl_job, options);
5446 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5447 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5448
5449 return OK;
5450
5451failed:
5452 if (hPipeIn != NULL)
5453 CloseHandle(hPipeIn);
5454 if (hPipeOut != NULL)
5455 CloseHandle(hPipeOut);
5456 return FAIL;
5457}
5458
5459/*
5460 * Free the terminal emulator part of "term".
5461 */
5462 static void
5463term_free_vterm(term_T *term)
5464{
5465 if (term->tl_winpty != NULL)
5466 winpty_free(term->tl_winpty);
5467 term->tl_winpty = NULL;
5468 if (term->tl_winpty_config != NULL)
5469 winpty_config_free(term->tl_winpty_config);
5470 term->tl_winpty_config = NULL;
5471 if (term->tl_vterm != NULL)
5472 vterm_free(term->tl_vterm);
5473 term->tl_vterm = NULL;
5474}
5475
5476/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005477 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005478 */
5479 static void
5480term_report_winsize(term_T *term, int rows, int cols)
5481{
5482 if (term->tl_winpty)
5483 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5484}
5485
5486 int
5487terminal_enabled(void)
5488{
5489 return dyn_winpty_init(FALSE) == OK;
5490}
5491
5492# else
5493
5494/**************************************
5495 * 3. Unix-like implementation.
5496 */
5497
5498/*
5499 * Create a new terminal of "rows" by "cols" cells.
5500 * Start job for "cmd".
5501 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005502 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005503 * Return OK or FAIL.
5504 */
5505 static int
5506term_and_job_init(
5507 term_T *term,
5508 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005509 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005510 jobopt_T *opt)
5511{
5512 create_vterm(term, term->tl_rows, term->tl_cols);
5513
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005514#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5515 if (opt->jo_set2 & JO2_ANSI_COLORS)
5516 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5517 else
5518 init_vterm_ansi_colors(term->tl_vterm);
5519#endif
5520
Bram Moolenaar13568252018-03-16 20:46:58 +01005521 /* This may change a string in "argvar". */
5522 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005523 if (term->tl_job != NULL)
5524 ++term->tl_job->jv_refcount;
5525
5526 return term->tl_job != NULL
5527 && term->tl_job->jv_channel != NULL
5528 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5529}
5530
5531 static int
5532create_pty_only(term_T *term, jobopt_T *opt)
5533{
5534 create_vterm(term, term->tl_rows, term->tl_cols);
5535
5536 term->tl_job = job_alloc();
5537 if (term->tl_job == NULL)
5538 return FAIL;
5539 ++term->tl_job->jv_refcount;
5540
5541 /* behave like the job is already finished */
5542 term->tl_job->jv_status = JOB_FINISHED;
5543
5544 return mch_create_pty_channel(term->tl_job, opt);
5545}
5546
5547/*
5548 * Free the terminal emulator part of "term".
5549 */
5550 static void
5551term_free_vterm(term_T *term)
5552{
5553 if (term->tl_vterm != NULL)
5554 vterm_free(term->tl_vterm);
5555 term->tl_vterm = NULL;
5556}
5557
5558/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005559 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005560 */
5561 static void
5562term_report_winsize(term_T *term, int rows, int cols)
5563{
5564 /* Use an ioctl() to report the new window size to the job. */
5565 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5566 {
5567 int fd = -1;
5568 int part;
5569
5570 for (part = PART_OUT; part < PART_COUNT; ++part)
5571 {
5572 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5573 if (isatty(fd))
5574 break;
5575 }
5576 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5577 mch_signal_job(term->tl_job, (char_u *)"winch");
5578 }
5579}
5580
5581# endif
5582
5583#endif /* FEAT_TERMINAL */