blob: 9a62edd67ba2177b2453d4ce2610a6db0256c804 [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 * - implement term_setsize()
Bram Moolenaarf59c6e82018-04-10 15:59:11 +020044 * - add an optional limit for the scrollback size. When reaching it remove
45 * 10% at the start.
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010046 * - Copy text in the vterm to the Vim buffer once in a while, so that
47 * completion works.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020048 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
49 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020050 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020051 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
52 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020053 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010054 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020055 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010057 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020058 * - add test for giving error for invalid 'termsize' value.
59 * - support minimal size when 'termsize' is "rows*cols".
60 * - support minimal size when 'termsize' is empty?
61 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020062 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020063 * - For the GUI fill termios with default values, perhaps like pangoterm:
64 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020065 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
66 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067 */
68
69#include "vim.h"
70
71#if defined(FEAT_TERMINAL) || defined(PROTO)
72
73#ifndef MIN
74# define MIN(x,y) ((x) < (y) ? (x) : (y))
75#endif
76#ifndef MAX
77# define MAX(x,y) ((x) > (y) ? (x) : (y))
78#endif
79
80#include "libvterm/include/vterm.h"
81
82/* This is VTermScreenCell without the characters, thus much smaller. */
83typedef struct {
84 VTermScreenCellAttrs attrs;
85 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010086 VTermColor fg;
87 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020088} cellattr_T;
89
90typedef struct sb_line_S {
91 int sb_cols; /* can differ per line */
92 cellattr_T *sb_cells; /* allocated */
93 cellattr_T sb_fill_attr; /* for short line */
94} sb_line_T;
95
96/* typedef term_T in structs.h */
97struct terminal_S {
98 term_T *tl_next;
99
100 VTerm *tl_vterm;
101 job_T *tl_job;
102 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100103#if defined(FEAT_GUI)
104 int tl_system; /* when non-zero used for :!cmd output */
105 int tl_toprow; /* row with first line of system terminal */
106#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200107
108 /* Set when setting the size of a vterm, reset after redrawing. */
109 int tl_vterm_size_changed;
110
111 /* used when tl_job is NULL and only a pty was created */
112 int tl_tty_fd;
113 char_u *tl_tty_in;
114 char_u *tl_tty_out;
115
116 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
117 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100118 int tl_finish;
119#define TL_FINISH_UNSET NUL
120#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
121#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
122#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200123 char_u *tl_opencmd;
124 char_u *tl_eof_chars;
125
126#ifdef WIN3264
127 void *tl_winpty_config;
128 void *tl_winpty;
129#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100130#if defined(FEAT_SESSION)
131 char_u *tl_command;
132#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100133 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200134
135 /* last known vterm size */
136 int tl_rows;
137 int tl_cols;
138 /* vterm size does not follow window size */
139 int tl_rows_fixed;
140 int tl_cols_fixed;
141
142 char_u *tl_title; /* NULL or allocated */
143 char_u *tl_status_text; /* NULL or allocated */
144
145 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200146 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 int tl_dirty_row_end; /* row below last one to update */
148
149 garray_T tl_scrollback;
150 int tl_scrollback_scrolled;
151 cellattr_T tl_default_color;
152
Bram Moolenaard96ff162018-02-18 22:13:29 +0100153 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
154 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
176#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
177#define KEY_BUF_LEN 200
178
179/*
180 * Functions with separate implementation for MS-Windows and Unix-like systems.
181 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100182static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200183static int create_pty_only(term_T *term, jobopt_T *opt);
184static void term_report_winsize(term_T *term, int rows, int cols);
185static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100186#ifdef FEAT_GUI
187static void update_system_term(term_T *term);
188#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100190/* The character that we know (or assume) that the terminal expects for the
191 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200192static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100194/* "Terminal" highlight group colors. */
195static int term_default_cterm_fg = -1;
196static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197
Bram Moolenaard317b382018-02-08 22:33:31 +0100198/* Store the last set and the desired cursor properties, so that we only update
199 * them when needed. Doing it unnecessary may result in flicker. */
200static char_u *last_set_cursor_color = (char_u *)"";
201static char_u *desired_cursor_color = (char_u *)"";
202static int last_set_cursor_shape = -1;
203static int desired_cursor_shape = -1;
204static int last_set_cursor_blink = -1;
205static int desired_cursor_blink = -1;
206
207
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200208/**************************************
209 * 1. Generic code for all systems.
210 */
211
212/*
213 * Determine the terminal size from 'termsize' and the current window.
214 * Assumes term->tl_rows and term->tl_cols are zero.
215 */
216 static void
217set_term_and_win_size(term_T *term)
218{
Bram Moolenaar13568252018-03-16 20:46:58 +0100219#ifdef FEAT_GUI
220 if (term->tl_system)
221 {
222 /* Use the whole screen for the system command. However, it will start
223 * at the command line and scroll up as needed, using tl_toprow. */
224 term->tl_rows = Rows;
225 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200226 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100227 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100228#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200229 if (*curwin->w_p_tms != NUL)
230 {
231 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
232
233 term->tl_rows = atoi((char *)curwin->w_p_tms);
234 term->tl_cols = atoi((char *)p);
235 }
236 if (term->tl_rows == 0)
237 term->tl_rows = curwin->w_height;
238 else
239 {
240 win_setheight_win(term->tl_rows, curwin);
241 term->tl_rows_fixed = TRUE;
242 }
243 if (term->tl_cols == 0)
244 term->tl_cols = curwin->w_width;
245 else
246 {
247 win_setwidth_win(term->tl_cols, curwin);
248 term->tl_cols_fixed = TRUE;
249 }
250}
251
252/*
253 * Initialize job options for a terminal job.
254 * Caller may overrule some of them.
255 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100256 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200257init_job_options(jobopt_T *opt)
258{
259 clear_job_options(opt);
260
261 opt->jo_mode = MODE_RAW;
262 opt->jo_out_mode = MODE_RAW;
263 opt->jo_err_mode = MODE_RAW;
264 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
265}
266
267/*
268 * Set job options mandatory for a terminal job.
269 */
270 static void
271setup_job_options(jobopt_T *opt, int rows, int cols)
272{
273 if (!(opt->jo_set & JO_OUT_IO))
274 {
275 /* Connect stdout to the terminal. */
276 opt->jo_io[PART_OUT] = JIO_BUFFER;
277 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
278 opt->jo_modifiable[PART_OUT] = 0;
279 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
280 }
281
282 if (!(opt->jo_set & JO_ERR_IO))
283 {
284 /* Connect stderr to the terminal. */
285 opt->jo_io[PART_ERR] = JIO_BUFFER;
286 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
287 opt->jo_modifiable[PART_ERR] = 0;
288 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
289 }
290
291 opt->jo_pty = TRUE;
292 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
293 opt->jo_term_rows = rows;
294 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
295 opt->jo_term_cols = cols;
296}
297
298/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100299 * Close a terminal buffer (and its window). Used when creating the terminal
300 * fails.
301 */
302 static void
303term_close_buffer(buf_T *buf, buf_T *old_curbuf)
304{
305 free_terminal(buf);
306 if (old_curbuf != NULL)
307 {
308 --curbuf->b_nwindows;
309 curbuf = old_curbuf;
310 curwin->w_buffer = curbuf;
311 ++curbuf->b_nwindows;
312 }
313
314 /* Wiping out the buffer will also close the window and call
315 * free_terminal(). */
316 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
317}
318
319/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200320 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100321 * Use either "argvar" or "argv", the other must be NULL.
322 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
323 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200324 * Returns NULL when failed.
325 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100326 buf_T *
327term_start(
328 typval_T *argvar,
329 char **argv,
330 jobopt_T *opt,
331 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332{
333 exarg_T split_ea;
334 win_T *old_curwin = curwin;
335 term_T *term;
336 buf_T *old_curbuf = NULL;
337 int res;
338 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100339 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200340
341 if (check_restricted() || check_secure())
342 return NULL;
343
344 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
345 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
346 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
347 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
348 {
349 EMSG(_(e_invarg));
350 return NULL;
351 }
352
353 term = (term_T *)alloc_clear(sizeof(term_T));
354 if (term == NULL)
355 return NULL;
356 term->tl_dirty_row_end = MAX_ROW;
357 term->tl_cursor_visible = TRUE;
358 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
359 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100360#ifdef FEAT_GUI
361 term->tl_system = (flags & TERM_START_SYSTEM);
362#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200363 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
364
365 vim_memset(&split_ea, 0, sizeof(split_ea));
366 if (opt->jo_curwin)
367 {
368 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100369 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200370 {
371 no_write_message();
372 vim_free(term);
373 return NULL;
374 }
375 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100376 ECMD_HIDE
377 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
378 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200379 {
380 vim_free(term);
381 return NULL;
382 }
383 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100384 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200385 {
386 buf_T *buf;
387
388 /* Create a new buffer without a window. Make it the current buffer for
389 * a moment to be able to do the initialisations. */
390 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
391 BLN_NEW | BLN_LISTED);
392 if (buf == NULL || ml_open(buf) == FAIL)
393 {
394 vim_free(term);
395 return NULL;
396 }
397 old_curbuf = curbuf;
398 --curbuf->b_nwindows;
399 curbuf = buf;
400 curwin->w_buffer = buf;
401 ++curbuf->b_nwindows;
402 }
403 else
404 {
405 /* Open a new window or tab. */
406 split_ea.cmdidx = CMD_new;
407 split_ea.cmd = (char_u *)"new";
408 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100409 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410 {
411 split_ea.line2 = opt->jo_term_rows;
412 split_ea.addr_count = 1;
413 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100414 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200415 {
416 split_ea.line2 = opt->jo_term_cols;
417 split_ea.addr_count = 1;
418 }
419
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100420 if (vertical)
421 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200422 ex_splitview(&split_ea);
423 if (curwin == old_curwin)
424 {
425 /* split failed */
426 vim_free(term);
427 return NULL;
428 }
429 }
430 term->tl_buffer = curbuf;
431 curbuf->b_term = term;
432
433 if (!opt->jo_hidden)
434 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100435 /* Only one size was taken care of with :new, do the other one. With
436 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100439 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200440 win_setwidth(opt->jo_term_cols);
441 }
442
443 /* Link the new terminal in the list of active terminals. */
444 term->tl_next = first_term;
445 first_term = term;
446
447 if (opt->jo_term_name != NULL)
448 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100449 else if (argv != NULL)
450 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200451 else
452 {
453 int i;
454 size_t len;
455 char_u *cmd, *p;
456
457 if (argvar->v_type == VAR_STRING)
458 {
459 cmd = argvar->vval.v_string;
460 if (cmd == NULL)
461 cmd = (char_u *)"";
462 else if (STRCMP(cmd, "NONE") == 0)
463 cmd = (char_u *)"pty";
464 }
465 else if (argvar->v_type != VAR_LIST
466 || argvar->vval.v_list == NULL
467 || argvar->vval.v_list->lv_len < 1
468 || (cmd = get_tv_string_chk(
469 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
470 cmd = (char_u*)"";
471
472 len = STRLEN(cmd) + 10;
473 p = alloc((int)len);
474
475 for (i = 0; p != NULL; ++i)
476 {
477 /* Prepend a ! to the command name to avoid the buffer name equals
478 * the executable, otherwise ":w!" would overwrite it. */
479 if (i == 0)
480 vim_snprintf((char *)p, len, "!%s", cmd);
481 else
482 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
483 if (buflist_findname(p) == NULL)
484 {
485 vim_free(curbuf->b_ffname);
486 curbuf->b_ffname = p;
487 break;
488 }
489 }
490 }
491 curbuf->b_fname = curbuf->b_ffname;
492
493 if (opt->jo_term_opencmd != NULL)
494 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
495
496 if (opt->jo_eof_chars != NULL)
497 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
498
499 set_string_option_direct((char_u *)"buftype", -1,
500 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
501
502 /* Mark the buffer as not modifiable. It can only be made modifiable after
503 * the job finished. */
504 curbuf->b_p_ma = FALSE;
505
506 set_term_and_win_size(term);
507 setup_job_options(opt, term->tl_rows, term->tl_cols);
508
Bram Moolenaar13568252018-03-16 20:46:58 +0100509 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100510 return curbuf;
511
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100512#if defined(FEAT_SESSION)
513 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100514 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100515 {
516 term->tl_command = vim_strsave((char_u *)"NONE");
517 }
518 else if (argvar->v_type == VAR_STRING)
519 {
520 char_u *cmd = argvar->vval.v_string;
521
522 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
523 term->tl_command = vim_strsave(cmd);
524 }
525 else if (argvar->v_type == VAR_LIST
526 && argvar->vval.v_list != NULL
527 && argvar->vval.v_list->lv_len > 0)
528 {
529 garray_T ga;
530 listitem_T *item;
531
532 ga_init2(&ga, 1, 100);
533 for (item = argvar->vval.v_list->lv_first;
534 item != NULL; item = item->li_next)
535 {
536 char_u *s = get_tv_string_chk(&item->li_tv);
537 char_u *p;
538
539 if (s == NULL)
540 break;
541 p = vim_strsave_fnameescape(s, FALSE);
542 if (p == NULL)
543 break;
544 ga_concat(&ga, p);
545 vim_free(p);
546 ga_append(&ga, ' ');
547 }
548 if (item == NULL)
549 {
550 ga_append(&ga, NUL);
551 term->tl_command = ga.ga_data;
552 }
553 else
554 ga_clear(&ga);
555 }
556#endif
557
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100558 if (opt->jo_term_kill != NULL)
559 {
560 char_u *p = skiptowhite(opt->jo_term_kill);
561
562 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
563 }
564
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200565 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100566 if (argv == NULL
567 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200568 && argvar->vval.v_string != NULL
569 && STRCMP(argvar->vval.v_string, "NONE") == 0)
570 res = create_pty_only(term, opt);
571 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100572 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200573
574 newbuf = curbuf;
575 if (res == OK)
576 {
577 /* Get and remember the size we ended up with. Update the pty. */
578 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
579 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100580#ifdef FEAT_GUI
581 if (term->tl_system)
582 {
583 /* display first line below typed command */
584 term->tl_toprow = msg_row + 1;
585 term->tl_dirty_row_end = 0;
586 }
587#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200588
589 /* Make sure we don't get stuck on sending keys to the job, it leads to
590 * a deadlock if the job is waiting for Vim to read. */
591 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
592
Bram Moolenaar13568252018-03-16 20:46:58 +0100593 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100594 {
595 ++curbuf->b_locked;
596 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
597 --curbuf->b_locked;
598 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100599 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200600 {
601 --curbuf->b_nwindows;
602 curbuf = old_curbuf;
603 curwin->w_buffer = curbuf;
604 ++curbuf->b_nwindows;
605 }
606 }
607 else
608 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100609 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200610 return NULL;
611 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100612
Bram Moolenaar13568252018-03-16 20:46:58 +0100613 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200614 return newbuf;
615}
616
617/*
618 * ":terminal": open a terminal window and execute a job in it.
619 */
620 void
621ex_terminal(exarg_T *eap)
622{
623 typval_T argvar[2];
624 jobopt_T opt;
625 char_u *cmd;
626 char_u *tofree = NULL;
627
628 init_job_options(&opt);
629
630 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100631 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200632 {
633 char_u *p, *ep;
634
635 cmd += 2;
636 p = skiptowhite(cmd);
637 ep = vim_strchr(cmd, '=');
638 if (ep != NULL && ep < p)
639 p = ep;
640
641 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
642 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100643 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
644 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200645 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
646 opt.jo_term_finish = 'o';
647 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
648 opt.jo_curwin = 1;
649 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
650 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100651 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
652 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100653 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
654 && ep != NULL)
655 {
656 opt.jo_set2 |= JO2_TERM_KILL;
657 opt.jo_term_kill = ep + 1;
658 p = skiptowhite(cmd);
659 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200660 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
661 && ep != NULL && isdigit(ep[1]))
662 {
663 opt.jo_set2 |= JO2_TERM_ROWS;
664 opt.jo_term_rows = atoi((char *)ep + 1);
665 p = skiptowhite(cmd);
666 }
667 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
668 && ep != NULL && isdigit(ep[1]))
669 {
670 opt.jo_set2 |= JO2_TERM_COLS;
671 opt.jo_term_cols = atoi((char *)ep + 1);
672 p = skiptowhite(cmd);
673 }
674 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
675 && ep != NULL)
676 {
677 char_u *buf = NULL;
678 char_u *keys;
679
680 p = skiptowhite(cmd);
681 *p = NUL;
682 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
683 opt.jo_set2 |= JO2_EOF_CHARS;
684 opt.jo_eof_chars = vim_strsave(keys);
685 vim_free(buf);
686 *p = ' ';
687 }
688 else
689 {
690 if (*p)
691 *p = NUL;
692 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100693 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200694 }
695 cmd = skipwhite(p);
696 }
697 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100698 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200699 /* Make a copy of 'shell', an autocommand may change the option. */
700 tofree = cmd = vim_strsave(p_sh);
701
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100702 /* default to close when the shell exits */
703 if (opt.jo_term_finish == NUL)
704 opt.jo_term_finish = 'c';
705 }
706
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 if (eap->addr_count > 0)
708 {
709 /* Write lines from current buffer to the job. */
710 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
711 opt.jo_io[PART_IN] = JIO_BUFFER;
712 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
713 opt.jo_in_top = eap->line1;
714 opt.jo_in_bot = eap->line2;
715 }
716
717 argvar[0].v_type = VAR_STRING;
718 argvar[0].vval.v_string = cmd;
719 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100720 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200721 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100722
723theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 vim_free(opt.jo_eof_chars);
725}
726
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100727#if defined(FEAT_SESSION) || defined(PROTO)
728/*
729 * Write a :terminal command to the session file to restore the terminal in
730 * window "wp".
731 * Return FAIL if writing fails.
732 */
733 int
734term_write_session(FILE *fd, win_T *wp)
735{
736 term_T *term = wp->w_buffer->b_term;
737
738 /* Create the terminal and run the command. This is not without
739 * risk, but let's assume the user only creates a session when this
740 * will be OK. */
741 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
742 term->tl_cols, term->tl_rows) < 0)
743 return FAIL;
744 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
745 return FAIL;
746
747 return put_eol(fd);
748}
749
750/*
751 * Return TRUE if "buf" has a terminal that should be restored.
752 */
753 int
754term_should_restore(buf_T *buf)
755{
756 term_T *term = buf->b_term;
757
758 return term != NULL && (term->tl_command == NULL
759 || STRCMP(term->tl_command, "NONE") != 0);
760}
761#endif
762
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200763/*
764 * Free the scrollback buffer for "term".
765 */
766 static void
767free_scrollback(term_T *term)
768{
769 int i;
770
771 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
772 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
773 ga_clear(&term->tl_scrollback);
774}
775
776/*
777 * Free a terminal and everything it refers to.
778 * Kills the job if there is one.
779 * Called when wiping out a buffer.
780 */
781 void
782free_terminal(buf_T *buf)
783{
784 term_T *term = buf->b_term;
785 term_T *tp;
786
787 if (term == NULL)
788 return;
789 if (first_term == term)
790 first_term = term->tl_next;
791 else
792 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
793 if (tp->tl_next == term)
794 {
795 tp->tl_next = term->tl_next;
796 break;
797 }
798
799 if (term->tl_job != NULL)
800 {
801 if (term->tl_job->jv_status != JOB_ENDED
802 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100803 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 job_stop(term->tl_job, NULL, "kill");
805 job_unref(term->tl_job);
806 }
807
808 free_scrollback(term);
809
810 term_free_vterm(term);
811 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100812#ifdef FEAT_SESSION
813 vim_free(term->tl_command);
814#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100815 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 vim_free(term->tl_status_text);
817 vim_free(term->tl_opencmd);
818 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100819 if (desired_cursor_color == term->tl_cursor_color)
820 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 vim_free(term->tl_cursor_color);
822 vim_free(term);
823 buf->b_term = NULL;
824 if (in_terminal_loop == term)
825 in_terminal_loop = NULL;
826}
827
828/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100829 * Get the part that is connected to the tty. Normally this is PART_IN, but
830 * when writing buffer lines to the job it can be another. This makes it
831 * possible to do "1,5term vim -".
832 */
833 static ch_part_T
834get_tty_part(term_T *term)
835{
836#ifdef UNIX
837 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
838 int i;
839
840 for (i = 0; i < 3; ++i)
841 {
842 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
843
844 if (isatty(fd))
845 return parts[i];
846 }
847#endif
848 return PART_IN;
849}
850
851/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200852 * Write job output "msg[len]" to the vterm.
853 */
854 static void
855term_write_job_output(term_T *term, char_u *msg, size_t len)
856{
857 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100858 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100860 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200861
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100862 /* flush vterm buffer when vterm responded to control sequence */
863 if (prevlen != vterm_output_get_buffer_current(vterm))
864 {
865 char buf[KEY_BUF_LEN];
866 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
867
868 if (curlen > 0)
869 channel_send(term->tl_job->jv_channel, get_tty_part(term),
870 (char_u *)buf, (int)curlen, NULL);
871 }
872
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873 /* this invokes the damage callbacks */
874 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
875}
876
877 static void
878update_cursor(term_T *term, int redraw)
879{
880 if (term->tl_normal_mode)
881 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100882#ifdef FEAT_GUI
883 if (term->tl_system)
884 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
885 term->tl_cursor_pos.col);
886 else
887#endif
888 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889 if (redraw)
890 {
891 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
892 cursor_on();
893 out_flush();
894#ifdef FEAT_GUI
895 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100896 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200897 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100898 gui_mch_flush();
899 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200900#endif
901 }
902}
903
904/*
905 * Invoked when "msg" output from a job was received. Write it to the terminal
906 * of "buffer".
907 */
908 void
909write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
910{
911 size_t len = STRLEN(msg);
912 term_T *term = buffer->b_term;
913
914 if (term->tl_vterm == NULL)
915 {
916 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
917 return;
918 }
919 ch_log(channel, "writing %d bytes to terminal", (int)len);
920 term_write_job_output(term, msg, len);
921
Bram Moolenaar13568252018-03-16 20:46:58 +0100922#ifdef FEAT_GUI
923 if (term->tl_system)
924 {
925 /* show system output, scrolling up the screen as needed */
926 update_system_term(term);
927 update_cursor(term, TRUE);
928 }
929 else
930#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200931 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
932 * contents, thus no screen update is needed. */
933 if (!term->tl_normal_mode)
934 {
935 /* TODO: only update once in a while. */
936 ch_log(term->tl_job->jv_channel, "updating screen");
937 if (buffer == curbuf)
938 {
939 update_screen(0);
940 update_cursor(term, TRUE);
941 }
942 else
943 redraw_after_callback(TRUE);
944 }
945}
946
947/*
948 * Send a mouse position and click to the vterm
949 */
950 static int
951term_send_mouse(VTerm *vterm, int button, int pressed)
952{
953 VTermModifier mod = VTERM_MOD_NONE;
954
955 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200956 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100957 if (button != 0)
958 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200959 return TRUE;
960}
961
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100962static int enter_mouse_col = -1;
963static int enter_mouse_row = -1;
964
965/*
966 * Handle a mouse click, drag or release.
967 * Return TRUE when a mouse event is sent to the terminal.
968 */
969 static int
970term_mouse_click(VTerm *vterm, int key)
971{
972#if defined(FEAT_CLIPBOARD)
973 /* For modeless selection mouse drag and release events are ignored, unless
974 * they are preceded with a mouse down event */
975 static int ignore_drag_release = TRUE;
976 VTermMouseState mouse_state;
977
978 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
979 if (mouse_state.flags == 0)
980 {
981 /* Terminal is not using the mouse, use modeless selection. */
982 switch (key)
983 {
984 case K_LEFTDRAG:
985 case K_LEFTRELEASE:
986 case K_RIGHTDRAG:
987 case K_RIGHTRELEASE:
988 /* Ignore drag and release events when the button-down wasn't
989 * seen before. */
990 if (ignore_drag_release)
991 {
992 int save_mouse_col, save_mouse_row;
993
994 if (enter_mouse_col < 0)
995 break;
996
997 /* mouse click in the window gave us focus, handle that
998 * click now */
999 save_mouse_col = mouse_col;
1000 save_mouse_row = mouse_row;
1001 mouse_col = enter_mouse_col;
1002 mouse_row = enter_mouse_row;
1003 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1004 mouse_col = save_mouse_col;
1005 mouse_row = save_mouse_row;
1006 }
1007 /* FALLTHROUGH */
1008 case K_LEFTMOUSE:
1009 case K_RIGHTMOUSE:
1010 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1011 ignore_drag_release = TRUE;
1012 else
1013 ignore_drag_release = FALSE;
1014 /* Should we call mouse_has() here? */
1015 if (clip_star.available)
1016 {
1017 int button, is_click, is_drag;
1018
1019 button = get_mouse_button(KEY2TERMCAP1(key),
1020 &is_click, &is_drag);
1021 if (mouse_model_popup() && button == MOUSE_LEFT
1022 && (mod_mask & MOD_MASK_SHIFT))
1023 {
1024 /* Translate shift-left to right button. */
1025 button = MOUSE_RIGHT;
1026 mod_mask &= ~MOD_MASK_SHIFT;
1027 }
1028 clip_modeless(button, is_click, is_drag);
1029 }
1030 break;
1031
1032 case K_MIDDLEMOUSE:
1033 if (clip_star.available)
1034 insert_reg('*', TRUE);
1035 break;
1036 }
1037 enter_mouse_col = -1;
1038 return FALSE;
1039 }
1040#endif
1041 enter_mouse_col = -1;
1042
1043 switch (key)
1044 {
1045 case K_LEFTMOUSE:
1046 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1047 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1048 case K_LEFTRELEASE:
1049 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1050 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1051 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1052 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1053 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1054 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1055 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1056 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1057 }
1058 return TRUE;
1059}
1060
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001061/*
1062 * Convert typed key "c" into bytes to send to the job.
1063 * Return the number of bytes in "buf".
1064 */
1065 static int
1066term_convert_key(term_T *term, int c, char *buf)
1067{
1068 VTerm *vterm = term->tl_vterm;
1069 VTermKey key = VTERM_KEY_NONE;
1070 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001071 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001072
1073 switch (c)
1074 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001075 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1076
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001077 /* don't use VTERM_KEY_BACKSPACE, it always
1078 * becomes 0x7f DEL */
1079 case K_BS: c = term_backspace_char; break;
1080
1081 case ESC: key = VTERM_KEY_ESCAPE; break;
1082 case K_DEL: key = VTERM_KEY_DEL; break;
1083 case K_DOWN: key = VTERM_KEY_DOWN; break;
1084 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1085 key = VTERM_KEY_DOWN; break;
1086 case K_END: key = VTERM_KEY_END; break;
1087 case K_S_END: mod = VTERM_MOD_SHIFT;
1088 key = VTERM_KEY_END; break;
1089 case K_C_END: mod = VTERM_MOD_CTRL;
1090 key = VTERM_KEY_END; break;
1091 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1092 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1093 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1094 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1095 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1096 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1097 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1098 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1099 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1100 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1101 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1102 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1103 case K_HOME: key = VTERM_KEY_HOME; break;
1104 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1105 key = VTERM_KEY_HOME; break;
1106 case K_C_HOME: mod = VTERM_MOD_CTRL;
1107 key = VTERM_KEY_HOME; break;
1108 case K_INS: key = VTERM_KEY_INS; break;
1109 case K_K0: key = VTERM_KEY_KP_0; break;
1110 case K_K1: key = VTERM_KEY_KP_1; break;
1111 case K_K2: key = VTERM_KEY_KP_2; break;
1112 case K_K3: key = VTERM_KEY_KP_3; break;
1113 case K_K4: key = VTERM_KEY_KP_4; break;
1114 case K_K5: key = VTERM_KEY_KP_5; break;
1115 case K_K6: key = VTERM_KEY_KP_6; break;
1116 case K_K7: key = VTERM_KEY_KP_7; break;
1117 case K_K8: key = VTERM_KEY_KP_8; break;
1118 case K_K9: key = VTERM_KEY_KP_9; break;
1119 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1120 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1121 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1122 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1123 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1124 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1125 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1126 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1127 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1128 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1129 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1130 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1131 case K_LEFT: key = VTERM_KEY_LEFT; break;
1132 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1133 key = VTERM_KEY_LEFT; break;
1134 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1135 key = VTERM_KEY_LEFT; break;
1136 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1137 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1138 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1139 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1140 key = VTERM_KEY_RIGHT; break;
1141 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1142 key = VTERM_KEY_RIGHT; break;
1143 case K_UP: key = VTERM_KEY_UP; break;
1144 case K_S_UP: mod = VTERM_MOD_SHIFT;
1145 key = VTERM_KEY_UP; break;
1146 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001147 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1148 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001149
Bram Moolenaara42ad572017-11-16 13:08:04 +01001150 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1151 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001152 case K_MOUSELEFT: /* TODO */ return 0;
1153 case K_MOUSERIGHT: /* TODO */ return 0;
1154
1155 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001156 case K_LEFTMOUSE_NM:
1157 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001158 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001159 case K_LEFTRELEASE_NM:
1160 case K_MOUSEMOVE:
1161 case K_MIDDLEMOUSE:
1162 case K_MIDDLEDRAG:
1163 case K_MIDDLERELEASE:
1164 case K_RIGHTMOUSE:
1165 case K_RIGHTDRAG:
1166 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1167 return 0;
1168 other = TRUE;
1169 break;
1170
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001171 case K_X1MOUSE: /* TODO */ return 0;
1172 case K_X1DRAG: /* TODO */ return 0;
1173 case K_X1RELEASE: /* TODO */ return 0;
1174 case K_X2MOUSE: /* TODO */ return 0;
1175 case K_X2DRAG: /* TODO */ return 0;
1176 case K_X2RELEASE: /* TODO */ return 0;
1177
1178 case K_IGNORE: return 0;
1179 case K_NOP: return 0;
1180 case K_UNDO: return 0;
1181 case K_HELP: return 0;
1182 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1183 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1184 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1185 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1186 case K_SELECT: return 0;
1187#ifdef FEAT_GUI
1188 case K_VER_SCROLLBAR: return 0;
1189 case K_HOR_SCROLLBAR: return 0;
1190#endif
1191#ifdef FEAT_GUI_TABLINE
1192 case K_TABLINE: return 0;
1193 case K_TABMENU: return 0;
1194#endif
1195#ifdef FEAT_NETBEANS_INTG
1196 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1197#endif
1198#ifdef FEAT_DND
1199 case K_DROP: return 0;
1200#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001201 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001202 case K_PS: vterm_keyboard_start_paste(vterm);
1203 other = TRUE;
1204 break;
1205 case K_PE: vterm_keyboard_end_paste(vterm);
1206 other = TRUE;
1207 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001208 }
1209
1210 /*
1211 * Convert special keys to vterm keys:
1212 * - Write keys to vterm: vterm_keyboard_key()
1213 * - Write output to channel.
1214 * TODO: use mod_mask
1215 */
1216 if (key != VTERM_KEY_NONE)
1217 /* Special key, let vterm convert it. */
1218 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001219 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001220 /* Normal character, let vterm convert it. */
1221 vterm_keyboard_unichar(vterm, c, mod);
1222
1223 /* Read back the converted escape sequence. */
1224 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1225}
1226
1227/*
1228 * Return TRUE if the job for "term" is still running.
1229 */
1230 int
1231term_job_running(term_T *term)
1232{
1233 /* Also consider the job finished when the channel is closed, to avoid a
1234 * race condition when updating the title. */
1235 return term != NULL
1236 && term->tl_job != NULL
1237 && channel_is_open(term->tl_job->jv_channel)
1238 && (term->tl_job->jv_status == JOB_STARTED
1239 || term->tl_job->jv_channel->ch_keep_open);
1240}
1241
1242/*
1243 * Return TRUE if "term" has an active channel and used ":term NONE".
1244 */
1245 int
1246term_none_open(term_T *term)
1247{
1248 /* Also consider the job finished when the channel is closed, to avoid a
1249 * race condition when updating the title. */
1250 return term != NULL
1251 && term->tl_job != NULL
1252 && channel_is_open(term->tl_job->jv_channel)
1253 && term->tl_job->jv_channel->ch_keep_open;
1254}
1255
1256/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001257 * Used when exiting: kill the job in "buf" if so desired.
1258 * Return OK when the job finished.
1259 * Return FAIL when the job is still running.
1260 */
1261 int
1262term_try_stop_job(buf_T *buf)
1263{
1264 int count;
1265 char *how = (char *)buf->b_term->tl_kill;
1266
1267#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1268 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1269 {
1270 char_u buff[DIALOG_MSG_SIZE];
1271 int ret;
1272
1273 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1274 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1275 if (ret == VIM_YES)
1276 how = "kill";
1277 else if (ret == VIM_CANCEL)
1278 return FAIL;
1279 }
1280#endif
1281 if (how == NULL || *how == NUL)
1282 return FAIL;
1283
1284 job_stop(buf->b_term->tl_job, NULL, how);
1285
1286 /* wait for up to a second for the job to die */
1287 for (count = 0; count < 100; ++count)
1288 {
1289 /* buffer, terminal and job may be cleaned up while waiting */
1290 if (!buf_valid(buf)
1291 || buf->b_term == NULL
1292 || buf->b_term->tl_job == NULL)
1293 return OK;
1294
1295 /* call job_status() to update jv_status */
1296 job_status(buf->b_term->tl_job);
1297 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1298 return OK;
1299 ui_delay(10L, FALSE);
1300 mch_check_messages();
1301 parse_queued_messages();
1302 }
1303 return FAIL;
1304}
1305
1306/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001307 * Add the last line of the scrollback buffer to the buffer in the window.
1308 */
1309 static void
1310add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1311{
1312 buf_T *buf = term->tl_buffer;
1313 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1314 linenr_T lnum = buf->b_ml.ml_line_count;
1315
1316#ifdef WIN3264
1317 if (!enc_utf8 && enc_codepage > 0)
1318 {
1319 WCHAR *ret = NULL;
1320 int length = 0;
1321
1322 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1323 &ret, &length);
1324 if (ret != NULL)
1325 {
1326 WideCharToMultiByte_alloc(enc_codepage, 0,
1327 ret, length, (char **)&text, &len, 0, 0);
1328 vim_free(ret);
1329 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1330 vim_free(text);
1331 }
1332 }
1333 else
1334#endif
1335 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1336 if (empty)
1337 {
1338 /* Delete the empty line that was in the empty buffer. */
1339 curbuf = buf;
1340 ml_delete(1, FALSE);
1341 curbuf = curwin->w_buffer;
1342 }
1343}
1344
1345 static void
1346cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1347{
1348 attr->width = cell->width;
1349 attr->attrs = cell->attrs;
1350 attr->fg = cell->fg;
1351 attr->bg = cell->bg;
1352}
1353
1354 static int
1355equal_celattr(cellattr_T *a, cellattr_T *b)
1356{
1357 /* Comparing the colors should be sufficient. */
1358 return a->fg.red == b->fg.red
1359 && a->fg.green == b->fg.green
1360 && a->fg.blue == b->fg.blue
1361 && a->bg.red == b->bg.red
1362 && a->bg.green == b->bg.green
1363 && a->bg.blue == b->bg.blue;
1364}
1365
Bram Moolenaard96ff162018-02-18 22:13:29 +01001366/*
1367 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1368 * line at this position. Otherwise at the end.
1369 */
1370 static int
1371add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1372{
1373 if (ga_grow(&term->tl_scrollback, 1) == OK)
1374 {
1375 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1376 + term->tl_scrollback.ga_len;
1377
1378 if (lnum > 0)
1379 {
1380 int i;
1381
1382 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1383 {
1384 *line = *(line - 1);
1385 --line;
1386 }
1387 }
1388 line->sb_cols = 0;
1389 line->sb_cells = NULL;
1390 line->sb_fill_attr = *fill_attr;
1391 ++term->tl_scrollback.ga_len;
1392 return OK;
1393 }
1394 return FALSE;
1395}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001396
1397/*
1398 * Add the current lines of the terminal to scrollback and to the buffer.
1399 * Called after the job has ended and when switching to Terminal-Normal mode.
1400 */
1401 static void
1402move_terminal_to_buffer(term_T *term)
1403{
1404 win_T *wp;
1405 int len;
1406 int lines_skipped = 0;
1407 VTermPos pos;
1408 VTermScreenCell cell;
1409 cellattr_T fill_attr, new_fill_attr;
1410 cellattr_T *p;
1411 VTermScreen *screen;
1412
1413 if (term->tl_vterm == NULL)
1414 return;
1415 screen = vterm_obtain_screen(term->tl_vterm);
1416 fill_attr = new_fill_attr = term->tl_default_color;
1417
1418 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1419 {
1420 len = 0;
1421 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1422 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1423 && cell.chars[0] != NUL)
1424 {
1425 len = pos.col + 1;
1426 new_fill_attr = term->tl_default_color;
1427 }
1428 else
1429 /* Assume the last attr is the filler attr. */
1430 cell2cellattr(&cell, &new_fill_attr);
1431
1432 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1433 ++lines_skipped;
1434 else
1435 {
1436 while (lines_skipped > 0)
1437 {
1438 /* Line was skipped, add an empty line. */
1439 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001440 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001442 }
1443
1444 if (len == 0)
1445 p = NULL;
1446 else
1447 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1448 if ((p != NULL || len == 0)
1449 && ga_grow(&term->tl_scrollback, 1) == OK)
1450 {
1451 garray_T ga;
1452 int width;
1453 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1454 + term->tl_scrollback.ga_len;
1455
1456 ga_init2(&ga, 1, 100);
1457 for (pos.col = 0; pos.col < len; pos.col += width)
1458 {
1459 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1460 {
1461 width = 1;
1462 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1463 if (ga_grow(&ga, 1) == OK)
1464 ga.ga_len += utf_char2bytes(' ',
1465 (char_u *)ga.ga_data + ga.ga_len);
1466 }
1467 else
1468 {
1469 width = cell.width;
1470
1471 cell2cellattr(&cell, &p[pos.col]);
1472
1473 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1474 {
1475 int i;
1476 int c;
1477
1478 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1479 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1480 (char_u *)ga.ga_data + ga.ga_len);
1481 }
1482 }
1483 }
1484 line->sb_cols = len;
1485 line->sb_cells = p;
1486 line->sb_fill_attr = new_fill_attr;
1487 fill_attr = new_fill_attr;
1488 ++term->tl_scrollback.ga_len;
1489
1490 if (ga_grow(&ga, 1) == FAIL)
1491 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1492 else
1493 {
1494 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1495 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1496 }
1497 ga_clear(&ga);
1498 }
1499 else
1500 vim_free(p);
1501 }
1502 }
1503
1504 /* Obtain the current background color. */
1505 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1506 &term->tl_default_color.fg, &term->tl_default_color.bg);
1507
1508 FOR_ALL_WINDOWS(wp)
1509 {
1510 if (wp->w_buffer == term->tl_buffer)
1511 {
1512 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1513 wp->w_cursor.col = 0;
1514 wp->w_valid = 0;
1515 if (wp->w_cursor.lnum >= wp->w_height)
1516 {
1517 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1518
1519 if (wp->w_topline < min_topline)
1520 wp->w_topline = min_topline;
1521 }
1522 redraw_win_later(wp, NOT_VALID);
1523 }
1524 }
1525}
1526
1527 static void
1528set_terminal_mode(term_T *term, int normal_mode)
1529{
1530 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001531 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001532 if (term->tl_buffer == curbuf)
1533 maketitle();
1534}
1535
1536/*
1537 * Called after the job if finished and Terminal mode is not active:
1538 * Move the vterm contents into the scrollback buffer and free the vterm.
1539 */
1540 static void
1541cleanup_vterm(term_T *term)
1542{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001543 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001544 move_terminal_to_buffer(term);
1545 term_free_vterm(term);
1546 set_terminal_mode(term, FALSE);
1547}
1548
1549/*
1550 * Switch from Terminal-Job mode to Terminal-Normal mode.
1551 * Suspends updating the terminal window.
1552 */
1553 static void
1554term_enter_normal_mode(void)
1555{
1556 term_T *term = curbuf->b_term;
1557
1558 /* Append the current terminal contents to the buffer. */
1559 move_terminal_to_buffer(term);
1560
1561 set_terminal_mode(term, TRUE);
1562
1563 /* Move the window cursor to the position of the cursor in the
1564 * terminal. */
1565 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1566 + term->tl_cursor_pos.row + 1;
1567 check_cursor();
1568 coladvance(term->tl_cursor_pos.col);
1569
1570 /* Display the same lines as in the terminal. */
1571 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1572}
1573
1574/*
1575 * Returns TRUE if the current window contains a terminal and we are in
1576 * Terminal-Normal mode.
1577 */
1578 int
1579term_in_normal_mode(void)
1580{
1581 term_T *term = curbuf->b_term;
1582
1583 return term != NULL && term->tl_normal_mode;
1584}
1585
1586/*
1587 * Switch from Terminal-Normal mode to Terminal-Job mode.
1588 * Restores updating the terminal window.
1589 */
1590 void
1591term_enter_job_mode()
1592{
1593 term_T *term = curbuf->b_term;
1594 sb_line_T *line;
1595 garray_T *gap;
1596
1597 /* Remove the terminal contents from the scrollback and the buffer. */
1598 gap = &term->tl_scrollback;
1599 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1600 && gap->ga_len > 0)
1601 {
1602 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1603 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1604 vim_free(line->sb_cells);
1605 --gap->ga_len;
1606 }
1607 check_cursor();
1608
1609 set_terminal_mode(term, FALSE);
1610
1611 if (term->tl_channel_closed)
1612 cleanup_vterm(term);
1613 redraw_buf_and_status_later(curbuf, NOT_VALID);
1614}
1615
1616/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001617 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001618 * Note: while waiting a terminal may be closed and freed if the channel is
1619 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001620 */
1621 static int
1622term_vgetc()
1623{
1624 int c;
1625 int save_State = State;
1626
1627 State = TERMINAL;
1628 got_int = FALSE;
1629#ifdef WIN3264
1630 ctrl_break_was_pressed = FALSE;
1631#endif
1632 c = vgetc();
1633 got_int = FALSE;
1634 State = save_State;
1635 return c;
1636}
1637
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001638static int mouse_was_outside = FALSE;
1639
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001641 * Send keys to terminal.
1642 * Return FAIL when the key needs to be handled in Normal mode.
1643 * Return OK when the key was dropped or sent to the terminal.
1644 */
1645 int
1646send_keys_to_term(term_T *term, int c, int typed)
1647{
1648 char msg[KEY_BUF_LEN];
1649 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 int dragging_outside = FALSE;
1651
1652 /* Catch keys that need to be handled as in Normal mode. */
1653 switch (c)
1654 {
1655 case NUL:
1656 case K_ZERO:
1657 if (typed)
1658 stuffcharReadbuff(c);
1659 return FAIL;
1660
1661 case K_IGNORE:
1662 return FAIL;
1663
1664 case K_LEFTDRAG:
1665 case K_MIDDLEDRAG:
1666 case K_RIGHTDRAG:
1667 case K_X1DRAG:
1668 case K_X2DRAG:
1669 dragging_outside = mouse_was_outside;
1670 /* FALLTHROUGH */
1671 case K_LEFTMOUSE:
1672 case K_LEFTMOUSE_NM:
1673 case K_LEFTRELEASE:
1674 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001675 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 case K_MIDDLEMOUSE:
1677 case K_MIDDLERELEASE:
1678 case K_RIGHTMOUSE:
1679 case K_RIGHTRELEASE:
1680 case K_X1MOUSE:
1681 case K_X1RELEASE:
1682 case K_X2MOUSE:
1683 case K_X2RELEASE:
1684
1685 case K_MOUSEUP:
1686 case K_MOUSEDOWN:
1687 case K_MOUSELEFT:
1688 case K_MOUSERIGHT:
1689 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001690 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001691 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001692 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693 || dragging_outside)
1694 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001695 /* click or scroll outside the current window or on status line
1696 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697 if (typed)
1698 {
1699 stuffcharReadbuff(c);
1700 mouse_was_outside = TRUE;
1701 }
1702 return FAIL;
1703 }
1704 }
1705 if (typed)
1706 mouse_was_outside = FALSE;
1707
1708 /* Convert the typed key to a sequence of bytes for the job. */
1709 len = term_convert_key(term, c, msg);
1710 if (len > 0)
1711 /* TODO: if FAIL is returned, stop? */
1712 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1713 (char_u *)msg, (int)len, NULL);
1714
1715 return OK;
1716}
1717
1718 static void
1719position_cursor(win_T *wp, VTermPos *pos)
1720{
1721 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1722 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1723 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1724}
1725
1726/*
1727 * Handle CTRL-W "": send register contents to the job.
1728 */
1729 static void
1730term_paste_register(int prev_c UNUSED)
1731{
1732 int c;
1733 list_T *l;
1734 listitem_T *item;
1735 long reglen = 0;
1736 int type;
1737
1738#ifdef FEAT_CMDL_INFO
1739 if (add_to_showcmd(prev_c))
1740 if (add_to_showcmd('"'))
1741 out_flush();
1742#endif
1743 c = term_vgetc();
1744#ifdef FEAT_CMDL_INFO
1745 clear_showcmd();
1746#endif
1747 if (!term_use_loop())
1748 /* job finished while waiting for a character */
1749 return;
1750
1751 /* CTRL-W "= prompt for expression to evaluate. */
1752 if (c == '=' && get_expr_register() != '=')
1753 return;
1754 if (!term_use_loop())
1755 /* job finished while waiting for a character */
1756 return;
1757
1758 l = (list_T *)get_reg_contents(c, GREG_LIST);
1759 if (l != NULL)
1760 {
1761 type = get_reg_type(c, &reglen);
1762 for (item = l->lv_first; item != NULL; item = item->li_next)
1763 {
1764 char_u *s = get_tv_string(&item->li_tv);
1765#ifdef WIN3264
1766 char_u *tmp = s;
1767
1768 if (!enc_utf8 && enc_codepage > 0)
1769 {
1770 WCHAR *ret = NULL;
1771 int length = 0;
1772
1773 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1774 (int)STRLEN(s), &ret, &length);
1775 if (ret != NULL)
1776 {
1777 WideCharToMultiByte_alloc(CP_UTF8, 0,
1778 ret, length, (char **)&s, &length, 0, 0);
1779 vim_free(ret);
1780 }
1781 }
1782#endif
1783 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1784 s, (int)STRLEN(s), NULL);
1785#ifdef WIN3264
1786 if (tmp != s)
1787 vim_free(s);
1788#endif
1789
1790 if (item->li_next != NULL || type == MLINE)
1791 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1792 (char_u *)"\r", 1, NULL);
1793 }
1794 list_free(l);
1795 }
1796}
1797
1798#if defined(FEAT_GUI) || defined(PROTO)
1799/*
1800 * Return TRUE when the cursor of the terminal should be displayed.
1801 */
1802 int
1803terminal_is_active()
1804{
1805 return in_terminal_loop != NULL;
1806}
1807
1808 cursorentry_T *
1809term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1810{
1811 term_T *term = in_terminal_loop;
1812 static cursorentry_T entry;
1813
1814 vim_memset(&entry, 0, sizeof(entry));
1815 entry.shape = entry.mshape =
1816 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1817 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1818 SHAPE_BLOCK;
1819 entry.percentage = 20;
1820 if (term->tl_cursor_blink)
1821 {
1822 entry.blinkwait = 700;
1823 entry.blinkon = 400;
1824 entry.blinkoff = 250;
1825 }
1826 *fg = gui.back_pixel;
1827 if (term->tl_cursor_color == NULL)
1828 *bg = gui.norm_pixel;
1829 else
1830 *bg = color_name2handle(term->tl_cursor_color);
1831 entry.name = "n";
1832 entry.used_for = SHAPE_CURSOR;
1833
1834 return &entry;
1835}
1836#endif
1837
Bram Moolenaard317b382018-02-08 22:33:31 +01001838 static void
1839may_output_cursor_props(void)
1840{
1841 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1842 || last_set_cursor_shape != desired_cursor_shape
1843 || last_set_cursor_blink != desired_cursor_blink)
1844 {
1845 last_set_cursor_color = desired_cursor_color;
1846 last_set_cursor_shape = desired_cursor_shape;
1847 last_set_cursor_blink = desired_cursor_blink;
1848 term_cursor_color(desired_cursor_color);
1849 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1850 /* this will restore the initial cursor style, if possible */
1851 ui_cursor_shape_forced(TRUE);
1852 else
1853 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1854 }
1855}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001856
Bram Moolenaard317b382018-02-08 22:33:31 +01001857/*
1858 * Set the cursor color and shape, if not last set to these.
1859 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 static void
1861may_set_cursor_props(term_T *term)
1862{
1863#ifdef FEAT_GUI
1864 /* For the GUI the cursor properties are obtained with
1865 * term_get_cursor_shape(). */
1866 if (gui.in_use)
1867 return;
1868#endif
1869 if (in_terminal_loop == term)
1870 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001871 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001872 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001874 desired_cursor_color = (char_u *)"";
1875 desired_cursor_shape = term->tl_cursor_shape;
1876 desired_cursor_blink = term->tl_cursor_blink;
1877 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001878 }
1879}
1880
Bram Moolenaard317b382018-02-08 22:33:31 +01001881/*
1882 * Reset the desired cursor properties and restore them when needed.
1883 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001885prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886{
1887#ifdef FEAT_GUI
1888 if (gui.in_use)
1889 return;
1890#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001891 desired_cursor_color = (char_u *)"";
1892 desired_cursor_shape = -1;
1893 desired_cursor_blink = -1;
1894 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001895}
1896
1897/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001898 * Called when entering a window with the mouse. If this is a terminal window
1899 * we may want to change state.
1900 */
1901 void
1902term_win_entered()
1903{
1904 term_T *term = curbuf->b_term;
1905
1906 if (term != NULL)
1907 {
1908 if (term_use_loop())
1909 {
1910 reset_VIsual_and_resel();
1911 if (State & INSERT)
1912 stop_insert_mode = TRUE;
1913 }
1914 mouse_was_outside = FALSE;
1915 enter_mouse_col = mouse_col;
1916 enter_mouse_row = mouse_row;
1917 }
1918}
1919
1920/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921 * Returns TRUE if the current window contains a terminal and we are sending
1922 * keys to the job.
1923 */
1924 int
1925term_use_loop(void)
1926{
1927 term_T *term = curbuf->b_term;
1928
1929 return term != NULL
1930 && !term->tl_normal_mode
1931 && term->tl_vterm != NULL
1932 && term_job_running(term);
1933}
1934
1935/*
1936 * Wait for input and send it to the job.
1937 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1938 * when there is no more typahead.
1939 * Return when the start of a CTRL-W command is typed or anything else that
1940 * should be handled as a Normal mode command.
1941 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1942 * the terminal was closed.
1943 */
1944 int
1945terminal_loop(int blocking)
1946{
1947 int c;
1948 int termkey = 0;
1949 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001950#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001951 int tty_fd = curbuf->b_term->tl_job->jv_channel
1952 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001953#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001954 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001955
1956 /* Remember the terminal we are sending keys to. However, the terminal
1957 * might be closed while waiting for a character, e.g. typing "exit" in a
1958 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1959 * stored reference. */
1960 in_terminal_loop = curbuf->b_term;
1961
1962 if (*curwin->w_p_tk != NUL)
1963 termkey = string_to_key(curwin->w_p_tk, TRUE);
1964 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1965 may_set_cursor_props(curbuf->b_term);
1966
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001967 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001968 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001969#ifdef FEAT_GUI
1970 if (!curbuf->b_term->tl_system)
1971#endif
1972 /* TODO: skip screen update when handling a sequence of keys. */
1973 /* Repeat redrawing in case a message is received while redrawing.
1974 */
1975 while (must_redraw != 0)
1976 if (update_screen(0) == FAIL)
1977 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001978 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001979 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001980
1981 c = term_vgetc();
1982 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001983 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001984 /* Job finished while waiting for a character. Push back the
1985 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001986 if (c != K_IGNORE)
1987 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001988 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001989 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001990 if (c == K_IGNORE)
1991 continue;
1992
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001993#ifdef UNIX
1994 /*
1995 * The shell or another program may change the tty settings. Getting
1996 * them for every typed character is a bit of overhead, but it's needed
1997 * for the first character typed, e.g. when Vim starts in a shell.
1998 */
1999 if (isatty(tty_fd))
2000 {
2001 ttyinfo_T info;
2002
2003 /* Get the current backspace character of the pty. */
2004 if (get_tty_info(tty_fd, &info) == OK)
2005 term_backspace_char = info.backspace;
2006 }
2007#endif
2008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002009#ifdef WIN3264
2010 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2011 * Use CTRL-BREAK to kill the job. */
2012 if (ctrl_break_was_pressed)
2013 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2014#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002015 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2016 * Not in a system terminal. */
2017 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2018#ifdef FEAT_GUI
2019 && !curbuf->b_term->tl_system
2020#endif
2021 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002022 {
2023 int prev_c = c;
2024
2025#ifdef FEAT_CMDL_INFO
2026 if (add_to_showcmd(c))
2027 out_flush();
2028#endif
2029 c = term_vgetc();
2030#ifdef FEAT_CMDL_INFO
2031 clear_showcmd();
2032#endif
2033 if (!term_use_loop())
2034 /* job finished while waiting for a character */
2035 break;
2036
2037 if (prev_c == Ctrl_BSL)
2038 {
2039 if (c == Ctrl_N)
2040 {
2041 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2042 term_enter_normal_mode();
2043 ret = FAIL;
2044 goto theend;
2045 }
2046 /* Send both keys to the terminal. */
2047 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2048 }
2049 else if (c == Ctrl_C)
2050 {
2051 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2052 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2053 }
2054 else if (termkey == 0 && c == '.')
2055 {
2056 /* "CTRL-W .": send CTRL-W to the job */
2057 c = Ctrl_W;
2058 }
2059 else if (c == 'N')
2060 {
2061 /* CTRL-W N : go to Terminal-Normal mode. */
2062 term_enter_normal_mode();
2063 ret = FAIL;
2064 goto theend;
2065 }
2066 else if (c == '"')
2067 {
2068 term_paste_register(prev_c);
2069 continue;
2070 }
2071 else if (termkey == 0 || c != termkey)
2072 {
2073 stuffcharReadbuff(Ctrl_W);
2074 stuffcharReadbuff(c);
2075 ret = OK;
2076 goto theend;
2077 }
2078 }
2079# ifdef WIN3264
2080 if (!enc_utf8 && has_mbyte && c >= 0x80)
2081 {
2082 WCHAR wc;
2083 char_u mb[3];
2084
2085 mb[0] = (unsigned)c >> 8;
2086 mb[1] = c;
2087 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2088 c = wc;
2089 }
2090# endif
2091 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2092 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002093 if (c == K_MOUSEMOVE)
2094 /* We are sure to come back here, don't reset the cursor color
2095 * and shape to avoid flickering. */
2096 restore_cursor = FALSE;
2097
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002098 ret = OK;
2099 goto theend;
2100 }
2101 }
2102 ret = FAIL;
2103
2104theend:
2105 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002106 if (restore_cursor)
2107 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002108 return ret;
2109}
2110
2111/*
2112 * Called when a job has finished.
2113 * This updates the title and status, but does not close the vterm, because
2114 * there might still be pending output in the channel.
2115 */
2116 void
2117term_job_ended(job_T *job)
2118{
2119 term_T *term;
2120 int did_one = FALSE;
2121
2122 for (term = first_term; term != NULL; term = term->tl_next)
2123 if (term->tl_job == job)
2124 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002125 VIM_CLEAR(term->tl_title);
2126 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002127 redraw_buf_and_status_later(term->tl_buffer, VALID);
2128 did_one = TRUE;
2129 }
2130 if (did_one)
2131 redraw_statuslines();
2132 if (curbuf->b_term != NULL)
2133 {
2134 if (curbuf->b_term->tl_job == job)
2135 maketitle();
2136 update_cursor(curbuf->b_term, TRUE);
2137 }
2138}
2139
2140 static void
2141may_toggle_cursor(term_T *term)
2142{
2143 if (in_terminal_loop == term)
2144 {
2145 if (term->tl_cursor_visible)
2146 cursor_on();
2147 else
2148 cursor_off();
2149 }
2150}
2151
2152/*
2153 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002154 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002155 */
2156 static int
2157color2index(VTermColor *color, int fg, int *boldp)
2158{
2159 int red = color->red;
2160 int blue = color->blue;
2161 int green = color->green;
2162
Bram Moolenaar46359e12017-11-29 22:33:38 +01002163 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002165 /* First 16 colors and default: use the ANSI index, because these
2166 * colors can be redefined. */
2167 if (t_colors >= 16)
2168 return color->ansi_index;
2169 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002170 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002171 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002172 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002173 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2174 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2175 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
2176 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
2177 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2178 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2179 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2180 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2181 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2182 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2183 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2184 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2185 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2186 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2187 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002188 }
2189 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002190
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002191 if (t_colors >= 256)
2192 {
2193 if (red == blue && red == green)
2194 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002195 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002196 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002197 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2198 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2199 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 int i;
2201
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002202 if (red < 5)
2203 return 17; /* 00/00/00 */
2204 if (red > 245) /* ff/ff/ff */
2205 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002206 for (i = 0; i < 23; ++i)
2207 if (red < cutoff[i])
2208 return i + 233;
2209 return 256;
2210 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002211 {
2212 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2213 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002214
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002215 /* 216-color cube */
2216 for (ri = 0; ri < 5; ++ri)
2217 if (red < cutoff[ri])
2218 break;
2219 for (gi = 0; gi < 5; ++gi)
2220 if (green < cutoff[gi])
2221 break;
2222 for (bi = 0; bi < 5; ++bi)
2223 if (blue < cutoff[bi])
2224 break;
2225 return 17 + ri * 36 + gi * 6 + bi;
2226 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002227 }
2228 return 0;
2229}
2230
2231/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002232 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002233 */
2234 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002235vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236{
2237 int attr = 0;
2238
2239 if (cellattrs.bold)
2240 attr |= HL_BOLD;
2241 if (cellattrs.underline)
2242 attr |= HL_UNDERLINE;
2243 if (cellattrs.italic)
2244 attr |= HL_ITALIC;
2245 if (cellattrs.strike)
2246 attr |= HL_STRIKETHROUGH;
2247 if (cellattrs.reverse)
2248 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002249 return attr;
2250}
2251
2252/*
2253 * Store Vterm attributes in "cell" from highlight flags.
2254 */
2255 static void
2256hl2vtermAttr(int attr, cellattr_T *cell)
2257{
2258 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2259 if (attr & HL_BOLD)
2260 cell->attrs.bold = 1;
2261 if (attr & HL_UNDERLINE)
2262 cell->attrs.underline = 1;
2263 if (attr & HL_ITALIC)
2264 cell->attrs.italic = 1;
2265 if (attr & HL_STRIKETHROUGH)
2266 cell->attrs.strike = 1;
2267 if (attr & HL_INVERSE)
2268 cell->attrs.reverse = 1;
2269}
2270
2271/*
2272 * Convert the attributes of a vterm cell into an attribute index.
2273 */
2274 static int
2275cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2276{
2277 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278
2279#ifdef FEAT_GUI
2280 if (gui.in_use)
2281 {
2282 guicolor_T fg, bg;
2283
2284 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2285 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2286 return get_gui_attr_idx(attr, fg, bg);
2287 }
2288 else
2289#endif
2290#ifdef FEAT_TERMGUICOLORS
2291 if (p_tgc)
2292 {
2293 guicolor_T fg, bg;
2294
2295 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2296 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2297
2298 return get_tgc_attr_idx(attr, fg, bg);
2299 }
2300 else
2301#endif
2302 {
2303 int bold = MAYBE;
2304 int fg = color2index(&cellfg, TRUE, &bold);
2305 int bg = color2index(&cellbg, FALSE, &bold);
2306
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002307 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002308 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002309 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002310 if (fg == 0 && term_default_cterm_fg >= 0)
2311 fg = term_default_cterm_fg + 1;
2312 if (bg == 0 && term_default_cterm_bg >= 0)
2313 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002314 }
2315
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002316 /* with 8 colors set the bold attribute to get a bright foreground */
2317 if (bold == TRUE)
2318 attr |= HL_BOLD;
2319 return get_cterm_attr_idx(attr, fg, bg);
2320 }
2321 return 0;
2322}
2323
2324 static int
2325handle_damage(VTermRect rect, void *user)
2326{
2327 term_T *term = (term_T *)user;
2328
2329 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2330 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2331 redraw_buf_later(term->tl_buffer, NOT_VALID);
2332 return 1;
2333}
2334
2335 static int
2336handle_moverect(VTermRect dest, VTermRect src, void *user)
2337{
2338 term_T *term = (term_T *)user;
2339
2340 /* Scrolling up is done much more efficiently by deleting lines instead of
2341 * redrawing the text. */
2342 if (dest.start_col == src.start_col
2343 && dest.end_col == src.end_col
2344 && dest.start_row < src.start_row)
2345 {
2346 win_T *wp;
2347 VTermColor fg, bg;
2348 VTermScreenCellAttrs attr;
2349 int clear_attr;
2350
2351 /* Set the color to clear lines with. */
2352 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2353 &fg, &bg);
2354 vim_memset(&attr, 0, sizeof(attr));
2355 clear_attr = cell2attr(attr, fg, bg);
2356
2357 FOR_ALL_WINDOWS(wp)
2358 {
2359 if (wp->w_buffer == term->tl_buffer)
2360 win_del_lines(wp, dest.start_row,
2361 src.start_row - dest.start_row, FALSE, FALSE,
2362 clear_attr);
2363 }
2364 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002365
2366 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2367 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2368
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 redraw_buf_later(term->tl_buffer, NOT_VALID);
2370 return 1;
2371}
2372
2373 static int
2374handle_movecursor(
2375 VTermPos pos,
2376 VTermPos oldpos UNUSED,
2377 int visible,
2378 void *user)
2379{
2380 term_T *term = (term_T *)user;
2381 win_T *wp;
2382
2383 term->tl_cursor_pos = pos;
2384 term->tl_cursor_visible = visible;
2385
2386 FOR_ALL_WINDOWS(wp)
2387 {
2388 if (wp->w_buffer == term->tl_buffer)
2389 position_cursor(wp, &pos);
2390 }
2391 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2392 {
2393 may_toggle_cursor(term);
2394 update_cursor(term, term->tl_cursor_visible);
2395 }
2396
2397 return 1;
2398}
2399
2400 static int
2401handle_settermprop(
2402 VTermProp prop,
2403 VTermValue *value,
2404 void *user)
2405{
2406 term_T *term = (term_T *)user;
2407
2408 switch (prop)
2409 {
2410 case VTERM_PROP_TITLE:
2411 vim_free(term->tl_title);
2412 /* a blank title isn't useful, make it empty, so that "running" is
2413 * displayed */
2414 if (*skipwhite((char_u *)value->string) == NUL)
2415 term->tl_title = NULL;
2416#ifdef WIN3264
2417 else if (!enc_utf8 && enc_codepage > 0)
2418 {
2419 WCHAR *ret = NULL;
2420 int length = 0;
2421
2422 MultiByteToWideChar_alloc(CP_UTF8, 0,
2423 (char*)value->string, (int)STRLEN(value->string),
2424 &ret, &length);
2425 if (ret != NULL)
2426 {
2427 WideCharToMultiByte_alloc(enc_codepage, 0,
2428 ret, length, (char**)&term->tl_title,
2429 &length, 0, 0);
2430 vim_free(ret);
2431 }
2432 }
2433#endif
2434 else
2435 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002436 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002437 if (term == curbuf->b_term)
2438 maketitle();
2439 break;
2440
2441 case VTERM_PROP_CURSORVISIBLE:
2442 term->tl_cursor_visible = value->boolean;
2443 may_toggle_cursor(term);
2444 out_flush();
2445 break;
2446
2447 case VTERM_PROP_CURSORBLINK:
2448 term->tl_cursor_blink = value->boolean;
2449 may_set_cursor_props(term);
2450 break;
2451
2452 case VTERM_PROP_CURSORSHAPE:
2453 term->tl_cursor_shape = value->number;
2454 may_set_cursor_props(term);
2455 break;
2456
2457 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002458 if (desired_cursor_color == term->tl_cursor_color)
2459 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002460 vim_free(term->tl_cursor_color);
2461 if (*value->string == NUL)
2462 term->tl_cursor_color = NULL;
2463 else
2464 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2465 may_set_cursor_props(term);
2466 break;
2467
2468 case VTERM_PROP_ALTSCREEN:
2469 /* TODO: do anything else? */
2470 term->tl_using_altscreen = value->boolean;
2471 break;
2472
2473 default:
2474 break;
2475 }
2476 /* Always return 1, otherwise vterm doesn't store the value internally. */
2477 return 1;
2478}
2479
2480/*
2481 * The job running in the terminal resized the terminal.
2482 */
2483 static int
2484handle_resize(int rows, int cols, void *user)
2485{
2486 term_T *term = (term_T *)user;
2487 win_T *wp;
2488
2489 term->tl_rows = rows;
2490 term->tl_cols = cols;
2491 if (term->tl_vterm_size_changed)
2492 /* Size was set by vterm_set_size(), don't set the window size. */
2493 term->tl_vterm_size_changed = FALSE;
2494 else
2495 {
2496 FOR_ALL_WINDOWS(wp)
2497 {
2498 if (wp->w_buffer == term->tl_buffer)
2499 {
2500 win_setheight_win(rows, wp);
2501 win_setwidth_win(cols, wp);
2502 }
2503 }
2504 redraw_buf_later(term->tl_buffer, NOT_VALID);
2505 }
2506 return 1;
2507}
2508
2509/*
2510 * Handle a line that is pushed off the top of the screen.
2511 */
2512 static int
2513handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2514{
2515 term_T *term = (term_T *)user;
2516
2517 /* TODO: Limit the number of lines that are stored. */
2518 if (ga_grow(&term->tl_scrollback, 1) == OK)
2519 {
2520 cellattr_T *p = NULL;
2521 int len = 0;
2522 int i;
2523 int c;
2524 int col;
2525 sb_line_T *line;
2526 garray_T ga;
2527 cellattr_T fill_attr = term->tl_default_color;
2528
2529 /* do not store empty cells at the end */
2530 for (i = 0; i < cols; ++i)
2531 if (cells[i].chars[0] != 0)
2532 len = i + 1;
2533 else
2534 cell2cellattr(&cells[i], &fill_attr);
2535
2536 ga_init2(&ga, 1, 100);
2537 if (len > 0)
2538 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2539 if (p != NULL)
2540 {
2541 for (col = 0; col < len; col += cells[col].width)
2542 {
2543 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2544 {
2545 ga.ga_len = 0;
2546 break;
2547 }
2548 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2549 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2550 (char_u *)ga.ga_data + ga.ga_len);
2551 cell2cellattr(&cells[col], &p[col]);
2552 }
2553 }
2554 if (ga_grow(&ga, 1) == FAIL)
2555 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2556 else
2557 {
2558 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2559 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2560 }
2561 ga_clear(&ga);
2562
2563 line = (sb_line_T *)term->tl_scrollback.ga_data
2564 + term->tl_scrollback.ga_len;
2565 line->sb_cols = len;
2566 line->sb_cells = p;
2567 line->sb_fill_attr = fill_attr;
2568 ++term->tl_scrollback.ga_len;
2569 ++term->tl_scrollback_scrolled;
2570 }
2571 return 0; /* ignored */
2572}
2573
2574static VTermScreenCallbacks screen_callbacks = {
2575 handle_damage, /* damage */
2576 handle_moverect, /* moverect */
2577 handle_movecursor, /* movecursor */
2578 handle_settermprop, /* settermprop */
2579 NULL, /* bell */
2580 handle_resize, /* resize */
2581 handle_pushline, /* sb_pushline */
2582 NULL /* sb_popline */
2583};
2584
2585/*
2586 * Called when a channel has been closed.
2587 * If this was a channel for a terminal window then finish it up.
2588 */
2589 void
2590term_channel_closed(channel_T *ch)
2591{
2592 term_T *term;
2593 int did_one = FALSE;
2594
2595 for (term = first_term; term != NULL; term = term->tl_next)
2596 if (term->tl_job == ch->ch_job)
2597 {
2598 term->tl_channel_closed = TRUE;
2599 did_one = TRUE;
2600
Bram Moolenaard23a8232018-02-10 18:45:26 +01002601 VIM_CLEAR(term->tl_title);
2602 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002603
2604 /* Unless in Terminal-Normal mode: clear the vterm. */
2605 if (!term->tl_normal_mode)
2606 {
2607 int fnum = term->tl_buffer->b_fnum;
2608
2609 cleanup_vterm(term);
2610
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002611 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002612 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002613 aco_save_T aco;
2614
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002615 /* ++close or term_finish == "close" */
2616 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002617 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002619 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002620 break;
2621 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002622 if (term->tl_finish == TL_FINISH_OPEN
2623 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 {
2625 char buf[50];
2626
2627 /* TODO: use term_opencmd */
2628 ch_log(NULL, "terminal job finished, opening window");
2629 vim_snprintf(buf, sizeof(buf),
2630 term->tl_opencmd == NULL
2631 ? "botright sbuf %d"
2632 : (char *)term->tl_opencmd, fnum);
2633 do_cmdline_cmd((char_u *)buf);
2634 }
2635 else
2636 ch_log(NULL, "terminal job finished");
2637 }
2638
2639 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2640 }
2641 if (did_one)
2642 {
2643 redraw_statuslines();
2644
2645 /* Need to break out of vgetc(). */
2646 ins_char_typebuf(K_IGNORE);
2647 typebuf_was_filled = TRUE;
2648
2649 term = curbuf->b_term;
2650 if (term != NULL)
2651 {
2652 if (term->tl_job == ch->ch_job)
2653 maketitle();
2654 update_cursor(term, term->tl_cursor_visible);
2655 }
2656 }
2657}
2658
2659/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002660 * Fill one screen line from a line of the terminal.
2661 * Advances "pos" to past the last column.
2662 */
2663 static void
2664term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2665{
2666 int off = screen_get_current_line_off();
2667
2668 for (pos->col = 0; pos->col < max_col; )
2669 {
2670 VTermScreenCell cell;
2671 int c;
2672
2673 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2674 vim_memset(&cell, 0, sizeof(cell));
2675
2676 c = cell.chars[0];
2677 if (c == NUL)
2678 {
2679 ScreenLines[off] = ' ';
2680 if (enc_utf8)
2681 ScreenLinesUC[off] = NUL;
2682 }
2683 else
2684 {
2685 if (enc_utf8)
2686 {
2687 int i;
2688
2689 /* composing chars */
2690 for (i = 0; i < Screen_mco
2691 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2692 {
2693 ScreenLinesC[i][off] = cell.chars[i + 1];
2694 if (cell.chars[i + 1] == 0)
2695 break;
2696 }
2697 if (c >= 0x80 || (Screen_mco > 0
2698 && ScreenLinesC[0][off] != 0))
2699 {
2700 ScreenLines[off] = ' ';
2701 ScreenLinesUC[off] = c;
2702 }
2703 else
2704 {
2705 ScreenLines[off] = c;
2706 ScreenLinesUC[off] = NUL;
2707 }
2708 }
2709#ifdef WIN3264
2710 else if (has_mbyte && c >= 0x80)
2711 {
2712 char_u mb[MB_MAXBYTES+1];
2713 WCHAR wc = c;
2714
2715 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2716 (char*)mb, 2, 0, 0) > 1)
2717 {
2718 ScreenLines[off] = mb[0];
2719 ScreenLines[off + 1] = mb[1];
2720 cell.width = mb_ptr2cells(mb);
2721 }
2722 else
2723 ScreenLines[off] = c;
2724 }
2725#endif
2726 else
2727 ScreenLines[off] = c;
2728 }
2729 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2730
2731 ++pos->col;
2732 ++off;
2733 if (cell.width == 2)
2734 {
2735 if (enc_utf8)
2736 ScreenLinesUC[off] = NUL;
2737
2738 /* don't set the second byte to NUL for a DBCS encoding, it
2739 * has been set above */
2740 if (enc_utf8 || !has_mbyte)
2741 ScreenLines[off] = NUL;
2742
2743 ++pos->col;
2744 ++off;
2745 }
2746 }
2747}
2748
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002749#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002750 static void
2751update_system_term(term_T *term)
2752{
2753 VTermPos pos;
2754 VTermScreen *screen;
2755
2756 if (term->tl_vterm == NULL)
2757 return;
2758 screen = vterm_obtain_screen(term->tl_vterm);
2759
2760 /* Scroll up to make more room for terminal lines if needed. */
2761 while (term->tl_toprow > 0
2762 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2763 {
2764 int save_p_more = p_more;
2765
2766 p_more = FALSE;
2767 msg_row = Rows - 1;
2768 msg_puts((char_u *)"\n");
2769 p_more = save_p_more;
2770 --term->tl_toprow;
2771 }
2772
2773 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2774 && pos.row < Rows; ++pos.row)
2775 {
2776 if (pos.row < term->tl_rows)
2777 {
2778 int max_col = MIN(Columns, term->tl_cols);
2779
2780 term_line2screenline(screen, &pos, max_col);
2781 }
2782 else
2783 pos.col = 0;
2784
2785 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2786 }
2787
2788 term->tl_dirty_row_start = MAX_ROW;
2789 term->tl_dirty_row_end = 0;
2790 update_cursor(term, TRUE);
2791}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002792#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002793
2794/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002795 * Called to update a window that contains an active terminal.
2796 * Returns FAIL when there is no terminal running in this window or in
2797 * Terminal-Normal mode.
2798 */
2799 int
2800term_update_window(win_T *wp)
2801{
2802 term_T *term = wp->w_buffer->b_term;
2803 VTerm *vterm;
2804 VTermScreen *screen;
2805 VTermState *state;
2806 VTermPos pos;
2807
2808 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2809 return FAIL;
2810
2811 vterm = term->tl_vterm;
2812 screen = vterm_obtain_screen(vterm);
2813 state = vterm_obtain_state(vterm);
2814
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002815 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002816 {
2817 term->tl_dirty_row_start = 0;
2818 term->tl_dirty_row_end = MAX_ROW;
2819 }
2820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002821 /*
2822 * If the window was resized a redraw will be triggered and we get here.
2823 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2824 */
2825 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2826 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2827 {
2828 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2829 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2830 win_T *twp;
2831
2832 FOR_ALL_WINDOWS(twp)
2833 {
2834 /* When more than one window shows the same terminal, use the
2835 * smallest size. */
2836 if (twp->w_buffer == term->tl_buffer)
2837 {
2838 if (!term->tl_rows_fixed && rows > twp->w_height)
2839 rows = twp->w_height;
2840 if (!term->tl_cols_fixed && cols > twp->w_width)
2841 cols = twp->w_width;
2842 }
2843 }
2844
2845 term->tl_vterm_size_changed = TRUE;
2846 vterm_set_size(vterm, rows, cols);
2847 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2848 rows);
2849 term_report_winsize(term, rows, cols);
2850 }
2851
2852 /* The cursor may have been moved when resizing. */
2853 vterm_state_get_cursorpos(state, &pos);
2854 position_cursor(wp, &pos);
2855
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002856 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2857 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002858 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002859 if (pos.row < term->tl_rows)
2860 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002861 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862
Bram Moolenaar13568252018-03-16 20:46:58 +01002863 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002864 }
2865 else
2866 pos.col = 0;
2867
Bram Moolenaarf118d482018-03-13 13:14:00 +01002868 screen_line(wp->w_winrow + pos.row
2869#ifdef FEAT_MENU
2870 + winbar_height(wp)
2871#endif
2872 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002873 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002874 term->tl_dirty_row_start = MAX_ROW;
2875 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876
2877 return OK;
2878}
2879
2880/*
2881 * Return TRUE if "wp" is a terminal window where the job has finished.
2882 */
2883 int
2884term_is_finished(buf_T *buf)
2885{
2886 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2887}
2888
2889/*
2890 * Return TRUE if "wp" is a terminal window where the job has finished or we
2891 * are in Terminal-Normal mode, thus we show the buffer contents.
2892 */
2893 int
2894term_show_buffer(buf_T *buf)
2895{
2896 term_T *term = buf->b_term;
2897
2898 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2899}
2900
2901/*
2902 * The current buffer is going to be changed. If there is terminal
2903 * highlighting remove it now.
2904 */
2905 void
2906term_change_in_curbuf(void)
2907{
2908 term_T *term = curbuf->b_term;
2909
2910 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2911 {
2912 free_scrollback(term);
2913 redraw_buf_later(term->tl_buffer, NOT_VALID);
2914
2915 /* The buffer is now like a normal buffer, it cannot be easily
2916 * abandoned when changed. */
2917 set_string_option_direct((char_u *)"buftype", -1,
2918 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2919 }
2920}
2921
2922/*
2923 * Get the screen attribute for a position in the buffer.
2924 * Use a negative "col" to get the filler background color.
2925 */
2926 int
2927term_get_attr(buf_T *buf, linenr_T lnum, int col)
2928{
2929 term_T *term = buf->b_term;
2930 sb_line_T *line;
2931 cellattr_T *cellattr;
2932
2933 if (lnum > term->tl_scrollback.ga_len)
2934 cellattr = &term->tl_default_color;
2935 else
2936 {
2937 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2938 if (col < 0 || col >= line->sb_cols)
2939 cellattr = &line->sb_fill_attr;
2940 else
2941 cellattr = line->sb_cells + col;
2942 }
2943 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2944}
2945
2946static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002947 { 0, 0, 0, 1}, /* black */
2948 {224, 0, 0, 2}, /* dark red */
2949 { 0, 224, 0, 3}, /* dark green */
2950 {224, 224, 0, 4}, /* dark yellow / brown */
2951 { 0, 0, 224, 5}, /* dark blue */
2952 {224, 0, 224, 6}, /* dark magenta */
2953 { 0, 224, 224, 7}, /* dark cyan */
2954 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002955
Bram Moolenaar46359e12017-11-29 22:33:38 +01002956 {128, 128, 128, 9}, /* dark grey */
2957 {255, 64, 64, 10}, /* light red */
2958 { 64, 255, 64, 11}, /* light green */
2959 {255, 255, 64, 12}, /* yellow */
2960 { 64, 64, 255, 13}, /* light blue */
2961 {255, 64, 255, 14}, /* light magenta */
2962 { 64, 255, 255, 15}, /* light cyan */
2963 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002964};
2965
2966static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002967 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968};
2969
2970static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002971 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2972 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002973};
2974
2975/*
2976 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002977 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 */
2979 static void
2980cterm_color2rgb(int nr, VTermColor *rgb)
2981{
2982 int idx;
2983
2984 if (nr < 16)
2985 {
2986 *rgb = ansi_table[nr];
2987 }
2988 else if (nr < 232)
2989 {
2990 /* 216 color cube */
2991 idx = nr - 16;
2992 rgb->blue = cube_value[idx % 6];
2993 rgb->green = cube_value[idx / 6 % 6];
2994 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002995 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002996 }
2997 else if (nr < 256)
2998 {
2999 /* 24 grey scale ramp */
3000 idx = nr - 232;
3001 rgb->blue = grey_ramp[idx];
3002 rgb->green = grey_ramp[idx];
3003 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003004 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003005 }
3006}
3007
3008/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003009 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 */
3011 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003012init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 VTermColor *fg, *bg;
3015 int fgval, bgval;
3016 int id;
3017
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3019 term->tl_default_color.width = 1;
3020 fg = &term->tl_default_color.fg;
3021 bg = &term->tl_default_color.bg;
3022
3023 /* Vterm uses a default black background. Set it to white when
3024 * 'background' is "light". */
3025 if (*p_bg == 'l')
3026 {
3027 fgval = 0;
3028 bgval = 255;
3029 }
3030 else
3031 {
3032 fgval = 255;
3033 bgval = 0;
3034 }
3035 fg->red = fg->green = fg->blue = fgval;
3036 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003037 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003038
3039 /* The "Terminal" highlight group overrules the defaults. */
3040 id = syn_name2id((char_u *)"Terminal");
3041
Bram Moolenaar46359e12017-11-29 22:33:38 +01003042 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003043#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3044 if (0
3045# ifdef FEAT_GUI
3046 || gui.in_use
3047# endif
3048# ifdef FEAT_TERMGUICOLORS
3049 || p_tgc
3050# endif
3051 )
3052 {
3053 guicolor_T fg_rgb = INVALCOLOR;
3054 guicolor_T bg_rgb = INVALCOLOR;
3055
3056 if (id != 0)
3057 syn_id2colors(id, &fg_rgb, &bg_rgb);
3058
3059# ifdef FEAT_GUI
3060 if (gui.in_use)
3061 {
3062 if (fg_rgb == INVALCOLOR)
3063 fg_rgb = gui.norm_pixel;
3064 if (bg_rgb == INVALCOLOR)
3065 bg_rgb = gui.back_pixel;
3066 }
3067# ifdef FEAT_TERMGUICOLORS
3068 else
3069# endif
3070# endif
3071# ifdef FEAT_TERMGUICOLORS
3072 {
3073 if (fg_rgb == INVALCOLOR)
3074 fg_rgb = cterm_normal_fg_gui_color;
3075 if (bg_rgb == INVALCOLOR)
3076 bg_rgb = cterm_normal_bg_gui_color;
3077 }
3078# endif
3079 if (fg_rgb != INVALCOLOR)
3080 {
3081 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3082
3083 fg->red = (unsigned)(rgb >> 16);
3084 fg->green = (unsigned)(rgb >> 8) & 255;
3085 fg->blue = (unsigned)rgb & 255;
3086 }
3087 if (bg_rgb != INVALCOLOR)
3088 {
3089 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3090
3091 bg->red = (unsigned)(rgb >> 16);
3092 bg->green = (unsigned)(rgb >> 8) & 255;
3093 bg->blue = (unsigned)rgb & 255;
3094 }
3095 }
3096 else
3097#endif
3098 if (id != 0 && t_colors >= 16)
3099 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003100 if (term_default_cterm_fg >= 0)
3101 cterm_color2rgb(term_default_cterm_fg, fg);
3102 if (term_default_cterm_bg >= 0)
3103 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003104 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003105 else
3106 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003107#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003109#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110
3111 /* In an MS-Windows console we know the normal colors. */
3112 if (cterm_normal_fg_color > 0)
3113 {
3114 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003115# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116 tmp = fg->red;
3117 fg->red = fg->blue;
3118 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003119# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003121# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003122 else
3123 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003124# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003125
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003126 if (cterm_normal_bg_color > 0)
3127 {
3128 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003129# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 tmp = bg->red;
3131 bg->red = bg->blue;
3132 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003133# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003135# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003136 else
3137 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003138# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003140}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003141
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003142#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3143/*
3144 * Set the 16 ANSI colors from array of RGB values
3145 */
3146 static void
3147set_vterm_palette(VTerm *vterm, long_u *rgb)
3148{
3149 int index = 0;
3150 VTermState *state = vterm_obtain_state(vterm);
3151 for (; index < 16; index++)
3152 {
3153 VTermColor color;
3154 color.red = (unsigned)(rgb[index] >> 16);
3155 color.green = (unsigned)(rgb[index] >> 8) & 255;
3156 color.blue = (unsigned)rgb[index] & 255;
3157 vterm_state_set_palette_color(state, index, &color);
3158 }
3159}
3160
3161/*
3162 * Set the ANSI color palette from a list of colors
3163 */
3164 static int
3165set_ansi_colors_list(VTerm *vterm, list_T *list)
3166{
3167 int n = 0;
3168 long_u rgb[16];
3169 listitem_T *li = list->lv_first;
3170
3171 for (; li != NULL && n < 16; li = li->li_next, n++)
3172 {
3173 char_u *color_name;
3174 guicolor_T guicolor;
3175
3176 color_name = get_tv_string_chk(&li->li_tv);
3177 if (color_name == NULL)
3178 return FAIL;
3179
3180 guicolor = GUI_GET_COLOR(color_name);
3181 if (guicolor == INVALCOLOR)
3182 return FAIL;
3183
3184 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3185 }
3186
3187 if (n != 16 || li != NULL)
3188 return FAIL;
3189
3190 set_vterm_palette(vterm, rgb);
3191
3192 return OK;
3193}
3194
3195/*
3196 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3197 */
3198 static void
3199init_vterm_ansi_colors(VTerm *vterm)
3200{
3201 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3202
3203 if (var != NULL
3204 && (var->di_tv.v_type != VAR_LIST
3205 || var->di_tv.vval.v_list == NULL
3206 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3207 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3208}
3209#endif
3210
Bram Moolenaar52acb112018-03-18 19:20:22 +01003211/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003212 * Handles a "drop" command from the job in the terminal.
3213 * "item" is the file name, "item->li_next" may have options.
3214 */
3215 static void
3216handle_drop_command(listitem_T *item)
3217{
3218 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003219 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003220 int bufnr;
3221 win_T *wp;
3222 tabpage_T *tp;
3223 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003224 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003225
3226 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3227 FOR_ALL_TAB_WINDOWS(tp, wp)
3228 {
3229 if (wp->w_buffer->b_fnum == bufnr)
3230 {
3231 /* buffer is in a window already, go there */
3232 goto_tabpage_win(tp, wp);
3233 return;
3234 }
3235 }
3236
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003237 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003238
3239 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3240 && opt_item->li_tv.vval.v_dict != NULL)
3241 {
3242 dict_T *dict = opt_item->li_tv.vval.v_dict;
3243 char_u *p;
3244
3245 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3246 if (p == NULL)
3247 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3248 if (p != NULL)
3249 {
3250 if (check_ff_value(p) == FAIL)
3251 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3252 else
3253 ea.force_ff = *p;
3254 }
3255 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3256 if (p == NULL)
3257 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3258 if (p != NULL)
3259 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003260 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003261 if (ea.cmd != NULL)
3262 {
3263 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3264 ea.force_enc = 11;
3265 tofree = ea.cmd;
3266 }
3267 }
3268
3269 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3270 if (p != NULL)
3271 get_bad_opt(p, &ea);
3272
3273 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3274 ea.force_bin = FORCE_BIN;
3275 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3276 ea.force_bin = FORCE_BIN;
3277 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3278 ea.force_bin = FORCE_NOBIN;
3279 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3280 ea.force_bin = FORCE_NOBIN;
3281 }
3282
3283 /* open in new window, like ":split fname" */
3284 if (ea.cmd == NULL)
3285 ea.cmd = (char_u *)"split";
3286 ea.arg = fname;
3287 ea.cmdidx = CMD_split;
3288 ex_splitview(&ea);
3289
3290 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003291}
3292
3293/*
3294 * Handles a function call from the job running in a terminal.
3295 * "item" is the function name, "item->li_next" has the arguments.
3296 */
3297 static void
3298handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3299{
3300 char_u *func;
3301 typval_T argvars[2];
3302 typval_T rettv;
3303 int doesrange;
3304
3305 if (item->li_next == NULL)
3306 {
3307 ch_log(channel, "Missing function arguments for call");
3308 return;
3309 }
3310 func = get_tv_string(&item->li_tv);
3311
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003312 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003313 {
3314 ch_log(channel, "Invalid function name: %s", func);
3315 return;
3316 }
3317
3318 argvars[0].v_type = VAR_NUMBER;
3319 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3320 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003321 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003322 2, argvars, /* argv_func */ NULL,
3323 /* firstline */ 1, /* lastline */ 1,
3324 &doesrange, /* evaluate */ TRUE,
3325 /* partial */ NULL, /* selfdict */ NULL) == OK)
3326 {
3327 clear_tv(&rettv);
3328 ch_log(channel, "Function %s called", func);
3329 }
3330 else
3331 ch_log(channel, "Calling function %s failed", func);
3332}
3333
3334/*
3335 * Called by libvterm when it cannot recognize an OSC sequence.
3336 * We recognize a terminal API command.
3337 */
3338 static int
3339parse_osc(const char *command, size_t cmdlen, void *user)
3340{
3341 term_T *term = (term_T *)user;
3342 js_read_T reader;
3343 typval_T tv;
3344 channel_T *channel = term->tl_job == NULL ? NULL
3345 : term->tl_job->jv_channel;
3346
3347 /* We recognize only OSC 5 1 ; {command} */
3348 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3349 return 0; /* not handled */
3350
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003351 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003352 if (reader.js_buf == NULL)
3353 return 1;
3354 reader.js_fill = NULL;
3355 reader.js_used = 0;
3356 if (json_decode(&reader, &tv, 0) == OK
3357 && tv.v_type == VAR_LIST
3358 && tv.vval.v_list != NULL)
3359 {
3360 listitem_T *item = tv.vval.v_list->lv_first;
3361
3362 if (item == NULL)
3363 ch_log(channel, "Missing command");
3364 else
3365 {
3366 char_u *cmd = get_tv_string(&item->li_tv);
3367
3368 item = item->li_next;
3369 if (item == NULL)
3370 ch_log(channel, "Missing argument for %s", cmd);
3371 else if (STRCMP(cmd, "drop") == 0)
3372 handle_drop_command(item);
3373 else if (STRCMP(cmd, "call") == 0)
3374 handle_call_command(term, channel, item);
3375 else
3376 ch_log(channel, "Invalid command received: %s", cmd);
3377 }
3378 }
3379 else
3380 ch_log(channel, "Invalid JSON received");
3381
3382 vim_free(reader.js_buf);
3383 clear_tv(&tv);
3384 return 1;
3385}
3386
3387static VTermParserCallbacks parser_fallbacks = {
3388 NULL, /* text */
3389 NULL, /* control */
3390 NULL, /* escape */
3391 NULL, /* csi */
3392 parse_osc, /* osc */
3393 NULL, /* dcs */
3394 NULL /* resize */
3395};
3396
3397/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003398 * Use Vim's allocation functions for vterm so profiling works.
3399 */
3400 static void *
3401vterm_malloc(size_t size, void *data UNUSED)
3402{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003403 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003404}
3405
3406 static void
3407vterm_memfree(void *ptr, void *data UNUSED)
3408{
3409 vim_free(ptr);
3410}
3411
3412static VTermAllocatorFunctions vterm_allocator = {
3413 &vterm_malloc,
3414 &vterm_memfree
3415};
3416
3417/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003418 * Create a new vterm and initialize it.
3419 */
3420 static void
3421create_vterm(term_T *term, int rows, int cols)
3422{
3423 VTerm *vterm;
3424 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003425 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003426 VTermValue value;
3427
Bram Moolenaar756ef112018-04-10 12:04:27 +02003428 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003429 term->tl_vterm = vterm;
3430 screen = vterm_obtain_screen(vterm);
3431 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3432 /* TODO: depends on 'encoding'. */
3433 vterm_set_utf8(vterm, 1);
3434
3435 init_default_colors(term);
3436
3437 vterm_state_set_default_colors(
3438 vterm_obtain_state(vterm),
3439 &term->tl_default_color.fg,
3440 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003441
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003442 if (t_colors >= 16)
3443 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3444
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003445 /* Required to initialize most things. */
3446 vterm_screen_reset(screen, 1 /* hard */);
3447
3448 /* Allow using alternate screen. */
3449 vterm_screen_enable_altscreen(screen, 1);
3450
3451 /* For unix do not use a blinking cursor. In an xterm this causes the
3452 * cursor to blink if it's blinking in the xterm.
3453 * For Windows we respect the system wide setting. */
3454#ifdef WIN3264
3455 if (GetCaretBlinkTime() == INFINITE)
3456 value.boolean = 0;
3457 else
3458 value.boolean = 1;
3459#else
3460 value.boolean = 0;
3461#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003462 state = vterm_obtain_state(vterm);
3463 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3464 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003465}
3466
3467/*
3468 * Return the text to show for the buffer name and status.
3469 */
3470 char_u *
3471term_get_status_text(term_T *term)
3472{
3473 if (term->tl_status_text == NULL)
3474 {
3475 char_u *txt;
3476 size_t len;
3477
3478 if (term->tl_normal_mode)
3479 {
3480 if (term_job_running(term))
3481 txt = (char_u *)_("Terminal");
3482 else
3483 txt = (char_u *)_("Terminal-finished");
3484 }
3485 else if (term->tl_title != NULL)
3486 txt = term->tl_title;
3487 else if (term_none_open(term))
3488 txt = (char_u *)_("active");
3489 else if (term_job_running(term))
3490 txt = (char_u *)_("running");
3491 else
3492 txt = (char_u *)_("finished");
3493 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3494 term->tl_status_text = alloc((int)len);
3495 if (term->tl_status_text != NULL)
3496 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3497 term->tl_buffer->b_fname, txt);
3498 }
3499 return term->tl_status_text;
3500}
3501
3502/*
3503 * Mark references in jobs of terminals.
3504 */
3505 int
3506set_ref_in_term(int copyID)
3507{
3508 int abort = FALSE;
3509 term_T *term;
3510 typval_T tv;
3511
3512 for (term = first_term; term != NULL; term = term->tl_next)
3513 if (term->tl_job != NULL)
3514 {
3515 tv.v_type = VAR_JOB;
3516 tv.vval.v_job = term->tl_job;
3517 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3518 }
3519 return abort;
3520}
3521
3522/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003523 * Cache "Terminal" highlight group colors.
3524 */
3525 void
3526set_terminal_default_colors(int cterm_fg, int cterm_bg)
3527{
3528 term_default_cterm_fg = cterm_fg - 1;
3529 term_default_cterm_bg = cterm_bg - 1;
3530}
3531
3532/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003534 * Returns NULL when the buffer is not for a terminal window and logs a message
3535 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003536 */
3537 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003538term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003539{
3540 buf_T *buf;
3541
3542 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3543 ++emsg_off;
3544 buf = get_buf_tv(&argvars[0], FALSE);
3545 --emsg_off;
3546 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003547 {
3548 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003549 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003550 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003551 return buf;
3552}
3553
Bram Moolenaard96ff162018-02-18 22:13:29 +01003554 static int
3555same_color(VTermColor *a, VTermColor *b)
3556{
3557 return a->red == b->red
3558 && a->green == b->green
3559 && a->blue == b->blue
3560 && a->ansi_index == b->ansi_index;
3561}
3562
3563 static void
3564dump_term_color(FILE *fd, VTermColor *color)
3565{
3566 fprintf(fd, "%02x%02x%02x%d",
3567 (int)color->red, (int)color->green, (int)color->blue,
3568 (int)color->ansi_index);
3569}
3570
3571/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003572 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003573 *
3574 * Each screen cell in full is:
3575 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3576 * {characters} is a space for an empty cell
3577 * For a double-width character "+" is changed to "*" and the next cell is
3578 * skipped.
3579 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3580 * when "&" use the same as the previous cell.
3581 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3582 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3583 * {color-idx} is a number from 0 to 255
3584 *
3585 * Screen cell with same width, attributes and color as the previous one:
3586 * |{characters}
3587 *
3588 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3589 *
3590 * Repeating the previous screen cell:
3591 * @{count}
3592 */
3593 void
3594f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3595{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003596 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003597 term_T *term;
3598 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003599 int max_height = 0;
3600 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003601 stat_T st;
3602 FILE *fd;
3603 VTermPos pos;
3604 VTermScreen *screen;
3605 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003606 VTermState *state;
3607 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003608
3609 if (check_restricted() || check_secure())
3610 return;
3611 if (buf == NULL)
3612 return;
3613 term = buf->b_term;
3614
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003615 if (argvars[2].v_type != VAR_UNKNOWN)
3616 {
3617 dict_T *d;
3618
3619 if (argvars[2].v_type != VAR_DICT)
3620 {
3621 EMSG(_(e_dictreq));
3622 return;
3623 }
3624 d = argvars[2].vval.v_dict;
3625 if (d != NULL)
3626 {
3627 max_height = get_dict_number(d, (char_u *)"rows");
3628 max_width = get_dict_number(d, (char_u *)"columns");
3629 }
3630 }
3631
Bram Moolenaard96ff162018-02-18 22:13:29 +01003632 fname = get_tv_string_chk(&argvars[1]);
3633 if (fname == NULL)
3634 return;
3635 if (mch_stat((char *)fname, &st) >= 0)
3636 {
3637 EMSG2(_("E953: File exists: %s"), fname);
3638 return;
3639 }
3640
Bram Moolenaard96ff162018-02-18 22:13:29 +01003641 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3642 {
3643 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3644 return;
3645 }
3646
3647 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3648
3649 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003650 state = vterm_obtain_state(term->tl_vterm);
3651 vterm_state_get_cursorpos(state, &cursor_pos);
3652
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003653 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3654 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003655 {
3656 int repeat = 0;
3657
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003658 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3659 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003660 {
3661 VTermScreenCell cell;
3662 int same_attr;
3663 int same_chars = TRUE;
3664 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003665 int is_cursor_pos = (pos.col == cursor_pos.col
3666 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003667
3668 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3669 vim_memset(&cell, 0, sizeof(cell));
3670
3671 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3672 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003673 int c = cell.chars[i];
3674 int pc = prev_cell.chars[i];
3675
3676 /* For the first character NUL is the same as space. */
3677 if (i == 0)
3678 {
3679 c = (c == NUL) ? ' ' : c;
3680 pc = (pc == NUL) ? ' ' : pc;
3681 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003682 if (cell.chars[i] != prev_cell.chars[i])
3683 same_chars = FALSE;
3684 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3685 break;
3686 }
3687 same_attr = vtermAttr2hl(cell.attrs)
3688 == vtermAttr2hl(prev_cell.attrs)
3689 && same_color(&cell.fg, &prev_cell.fg)
3690 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003691 if (same_chars && cell.width == prev_cell.width && same_attr
3692 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003693 {
3694 ++repeat;
3695 }
3696 else
3697 {
3698 if (repeat > 0)
3699 {
3700 fprintf(fd, "@%d", repeat);
3701 repeat = 0;
3702 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003703 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003704
3705 if (cell.chars[0] == NUL)
3706 fputs(" ", fd);
3707 else
3708 {
3709 char_u charbuf[10];
3710 int len;
3711
3712 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3713 && cell.chars[i] != NUL; ++i)
3714 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003715 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003716 fwrite(charbuf, len, 1, fd);
3717 }
3718 }
3719
3720 /* When only the characters differ we don't write anything, the
3721 * following "|", "@" or NL will indicate using the same
3722 * attributes. */
3723 if (cell.width != prev_cell.width || !same_attr)
3724 {
3725 if (cell.width == 2)
3726 {
3727 fputs("*", fd);
3728 ++pos.col;
3729 }
3730 else
3731 fputs("+", fd);
3732
3733 if (same_attr)
3734 {
3735 fputs("&", fd);
3736 }
3737 else
3738 {
3739 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3740 if (same_color(&cell.fg, &prev_cell.fg))
3741 fputs("&", fd);
3742 else
3743 {
3744 fputs("#", fd);
3745 dump_term_color(fd, &cell.fg);
3746 }
3747 if (same_color(&cell.bg, &prev_cell.bg))
3748 fputs("&", fd);
3749 else
3750 {
3751 fputs("#", fd);
3752 dump_term_color(fd, &cell.bg);
3753 }
3754 }
3755 }
3756
3757 prev_cell = cell;
3758 }
3759 }
3760 if (repeat > 0)
3761 fprintf(fd, "@%d", repeat);
3762 fputs("\n", fd);
3763 }
3764
3765 fclose(fd);
3766}
3767
3768/*
3769 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3770 */
3771 static void
3772dump_is_corrupt(garray_T *gap)
3773{
3774 ga_concat(gap, (char_u *)"CORRUPT");
3775}
3776
3777 static void
3778append_cell(garray_T *gap, cellattr_T *cell)
3779{
3780 if (ga_grow(gap, 1) == OK)
3781 {
3782 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3783 ++gap->ga_len;
3784 }
3785}
3786
3787/*
3788 * Read the dump file from "fd" and append lines to the current buffer.
3789 * Return the cell width of the longest line.
3790 */
3791 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003792read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003793{
3794 int c;
3795 garray_T ga_text;
3796 garray_T ga_cell;
3797 char_u *prev_char = NULL;
3798 int attr = 0;
3799 cellattr_T cell;
3800 term_T *term = curbuf->b_term;
3801 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003802 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003803
3804 ga_init2(&ga_text, 1, 90);
3805 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3806 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003807 cursor_pos->row = -1;
3808 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003809
3810 c = fgetc(fd);
3811 for (;;)
3812 {
3813 if (c == EOF)
3814 break;
3815 if (c == '\n')
3816 {
3817 /* End of a line: append it to the buffer. */
3818 if (ga_text.ga_data == NULL)
3819 dump_is_corrupt(&ga_text);
3820 if (ga_grow(&term->tl_scrollback, 1) == OK)
3821 {
3822 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3823 + term->tl_scrollback.ga_len;
3824
3825 if (max_cells < ga_cell.ga_len)
3826 max_cells = ga_cell.ga_len;
3827 line->sb_cols = ga_cell.ga_len;
3828 line->sb_cells = ga_cell.ga_data;
3829 line->sb_fill_attr = term->tl_default_color;
3830 ++term->tl_scrollback.ga_len;
3831 ga_init(&ga_cell);
3832
3833 ga_append(&ga_text, NUL);
3834 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3835 ga_text.ga_len, FALSE);
3836 }
3837 else
3838 ga_clear(&ga_cell);
3839 ga_text.ga_len = 0;
3840
3841 c = fgetc(fd);
3842 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003843 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003844 {
3845 int prev_len = ga_text.ga_len;
3846
Bram Moolenaar9271d052018-02-25 21:39:46 +01003847 if (c == '>')
3848 {
3849 if (cursor_pos->row != -1)
3850 dump_is_corrupt(&ga_text); /* duplicate cursor */
3851 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3852 cursor_pos->col = ga_cell.ga_len;
3853 }
3854
Bram Moolenaard96ff162018-02-18 22:13:29 +01003855 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3856 c = fgetc(fd);
3857 if (c != EOF)
3858 ga_append(&ga_text, c);
3859 for (;;)
3860 {
3861 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003862 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003863 || c == EOF || c == '\n')
3864 break;
3865 ga_append(&ga_text, c);
3866 }
3867
3868 /* save the character for repeating it */
3869 vim_free(prev_char);
3870 if (ga_text.ga_data != NULL)
3871 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3872 ga_text.ga_len - prev_len);
3873
Bram Moolenaar9271d052018-02-25 21:39:46 +01003874 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003875 {
3876 /* use all attributes from previous cell */
3877 }
3878 else if (c == '+' || c == '*')
3879 {
3880 int is_bg;
3881
3882 cell.width = c == '+' ? 1 : 2;
3883
3884 c = fgetc(fd);
3885 if (c == '&')
3886 {
3887 /* use same attr as previous cell */
3888 c = fgetc(fd);
3889 }
3890 else if (isdigit(c))
3891 {
3892 /* get the decimal attribute */
3893 attr = 0;
3894 while (isdigit(c))
3895 {
3896 attr = attr * 10 + (c - '0');
3897 c = fgetc(fd);
3898 }
3899 hl2vtermAttr(attr, &cell);
3900 }
3901 else
3902 dump_is_corrupt(&ga_text);
3903
3904 /* is_bg == 0: fg, is_bg == 1: bg */
3905 for (is_bg = 0; is_bg <= 1; ++is_bg)
3906 {
3907 if (c == '&')
3908 {
3909 /* use same color as previous cell */
3910 c = fgetc(fd);
3911 }
3912 else if (c == '#')
3913 {
3914 int red, green, blue, index = 0;
3915
3916 c = fgetc(fd);
3917 red = hex2nr(c);
3918 c = fgetc(fd);
3919 red = (red << 4) + hex2nr(c);
3920 c = fgetc(fd);
3921 green = hex2nr(c);
3922 c = fgetc(fd);
3923 green = (green << 4) + hex2nr(c);
3924 c = fgetc(fd);
3925 blue = hex2nr(c);
3926 c = fgetc(fd);
3927 blue = (blue << 4) + hex2nr(c);
3928 c = fgetc(fd);
3929 if (!isdigit(c))
3930 dump_is_corrupt(&ga_text);
3931 while (isdigit(c))
3932 {
3933 index = index * 10 + (c - '0');
3934 c = fgetc(fd);
3935 }
3936
3937 if (is_bg)
3938 {
3939 cell.bg.red = red;
3940 cell.bg.green = green;
3941 cell.bg.blue = blue;
3942 cell.bg.ansi_index = index;
3943 }
3944 else
3945 {
3946 cell.fg.red = red;
3947 cell.fg.green = green;
3948 cell.fg.blue = blue;
3949 cell.fg.ansi_index = index;
3950 }
3951 }
3952 else
3953 dump_is_corrupt(&ga_text);
3954 }
3955 }
3956 else
3957 dump_is_corrupt(&ga_text);
3958
3959 append_cell(&ga_cell, &cell);
3960 }
3961 else if (c == '@')
3962 {
3963 if (prev_char == NULL)
3964 dump_is_corrupt(&ga_text);
3965 else
3966 {
3967 int count = 0;
3968
3969 /* repeat previous character, get the count */
3970 for (;;)
3971 {
3972 c = fgetc(fd);
3973 if (!isdigit(c))
3974 break;
3975 count = count * 10 + (c - '0');
3976 }
3977
3978 while (count-- > 0)
3979 {
3980 ga_concat(&ga_text, prev_char);
3981 append_cell(&ga_cell, &cell);
3982 }
3983 }
3984 }
3985 else
3986 {
3987 dump_is_corrupt(&ga_text);
3988 c = fgetc(fd);
3989 }
3990 }
3991
3992 if (ga_text.ga_len > 0)
3993 {
3994 /* trailing characters after last NL */
3995 dump_is_corrupt(&ga_text);
3996 ga_append(&ga_text, NUL);
3997 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3998 ga_text.ga_len, FALSE);
3999 }
4000
4001 ga_clear(&ga_text);
4002 vim_free(prev_char);
4003
4004 return max_cells;
4005}
4006
4007/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004008 * Return an allocated string with at least "text_width" "=" characters and
4009 * "fname" inserted in the middle.
4010 */
4011 static char_u *
4012get_separator(int text_width, char_u *fname)
4013{
4014 int width = MAX(text_width, curwin->w_width);
4015 char_u *textline;
4016 int fname_size;
4017 char_u *p = fname;
4018 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004019 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004020
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004021 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004022 if (textline == NULL)
4023 return NULL;
4024
4025 fname_size = vim_strsize(fname);
4026 if (fname_size < width - 8)
4027 {
4028 /* enough room, don't use the full window width */
4029 width = MAX(text_width, fname_size + 8);
4030 }
4031 else if (fname_size > width - 8)
4032 {
4033 /* full name doesn't fit, use only the tail */
4034 p = gettail(fname);
4035 fname_size = vim_strsize(p);
4036 }
4037 /* skip characters until the name fits */
4038 while (fname_size > width - 8)
4039 {
4040 p += (*mb_ptr2len)(p);
4041 fname_size = vim_strsize(p);
4042 }
4043
4044 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4045 textline[i] = '=';
4046 textline[i++] = ' ';
4047
4048 STRCPY(textline + i, p);
4049 off = STRLEN(textline);
4050 textline[off] = ' ';
4051 for (i = 1; i < (width - fname_size) / 2; ++i)
4052 textline[off + i] = '=';
4053 textline[off + i] = NUL;
4054
4055 return textline;
4056}
4057
4058/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004059 * Common for "term_dumpdiff()" and "term_dumpload()".
4060 */
4061 static void
4062term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4063{
4064 jobopt_T opt;
4065 buf_T *buf;
4066 char_u buf1[NUMBUFLEN];
4067 char_u buf2[NUMBUFLEN];
4068 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004069 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004070 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004071 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004072 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004073 char_u *textline = NULL;
4074
4075 /* First open the files. If this fails bail out. */
4076 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4077 if (do_diff)
4078 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4079 if (fname1 == NULL || (do_diff && fname2 == NULL))
4080 {
4081 EMSG(_(e_invarg));
4082 return;
4083 }
4084 fd1 = mch_fopen((char *)fname1, READBIN);
4085 if (fd1 == NULL)
4086 {
4087 EMSG2(_(e_notread), fname1);
4088 return;
4089 }
4090 if (do_diff)
4091 {
4092 fd2 = mch_fopen((char *)fname2, READBIN);
4093 if (fd2 == NULL)
4094 {
4095 fclose(fd1);
4096 EMSG2(_(e_notread), fname2);
4097 return;
4098 }
4099 }
4100
4101 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004102 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4103 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4104 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4105 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4106 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004107
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004108 if (opt.jo_term_name == NULL)
4109 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004110 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004111
Bram Moolenaarb571c632018-03-21 22:27:59 +01004112 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004113 if (fname_tofree != NULL)
4114 {
4115 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4116 opt.jo_term_name = fname_tofree;
4117 }
4118 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004119
Bram Moolenaar13568252018-03-16 20:46:58 +01004120 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004121 if (buf != NULL && buf->b_term != NULL)
4122 {
4123 int i;
4124 linenr_T bot_lnum;
4125 linenr_T lnum;
4126 term_T *term = buf->b_term;
4127 int width;
4128 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004129 VTermPos cursor_pos1;
4130 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004131
Bram Moolenaar52acb112018-03-18 19:20:22 +01004132 init_default_colors(term);
4133
Bram Moolenaard96ff162018-02-18 22:13:29 +01004134 rettv->vval.v_number = buf->b_fnum;
4135
4136 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004137 width = read_dump_file(fd1, &cursor_pos1);
4138
4139 /* position the cursor */
4140 if (cursor_pos1.row >= 0)
4141 {
4142 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4143 coladvance(cursor_pos1.col);
4144 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004145
4146 /* Delete the empty line that was in the empty buffer. */
4147 ml_delete(1, FALSE);
4148
4149 /* For term_dumpload() we are done here. */
4150 if (!do_diff)
4151 goto theend;
4152
4153 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4154
Bram Moolenaar4a696342018-04-05 18:45:26 +02004155 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004156 if (textline == NULL)
4157 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004158 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4159 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4160 vim_free(textline);
4161
4162 textline = get_separator(width, fname2);
4163 if (textline == NULL)
4164 goto theend;
4165 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4166 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004167 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004168
4169 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004170 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004171 if (width2 > width)
4172 {
4173 vim_free(textline);
4174 textline = alloc(width2 + 1);
4175 if (textline == NULL)
4176 goto theend;
4177 width = width2;
4178 textline[width] = NUL;
4179 }
4180 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4181
4182 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4183 {
4184 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4185 {
4186 /* bottom part has fewer rows, fill with "-" */
4187 for (i = 0; i < width; ++i)
4188 textline[i] = '-';
4189 }
4190 else
4191 {
4192 char_u *line1;
4193 char_u *line2;
4194 char_u *p1;
4195 char_u *p2;
4196 int col;
4197 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4198 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4199 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4200 ->sb_cells;
4201
4202 /* Make a copy, getting the second line will invalidate it. */
4203 line1 = vim_strsave(ml_get(lnum));
4204 if (line1 == NULL)
4205 break;
4206 p1 = line1;
4207
4208 line2 = ml_get(lnum + bot_lnum);
4209 p2 = line2;
4210 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4211 {
4212 int len1 = utfc_ptr2len(p1);
4213 int len2 = utfc_ptr2len(p2);
4214
4215 textline[col] = ' ';
4216 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004217 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004218 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004219 else if (lnum == cursor_pos1.row + 1
4220 && col == cursor_pos1.col
4221 && (cursor_pos1.row != cursor_pos2.row
4222 || cursor_pos1.col != cursor_pos2.col))
4223 /* cursor in first but not in second */
4224 textline[col] = '>';
4225 else if (lnum == cursor_pos2.row + 1
4226 && col == cursor_pos2.col
4227 && (cursor_pos1.row != cursor_pos2.row
4228 || cursor_pos1.col != cursor_pos2.col))
4229 /* cursor in second but not in first */
4230 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004231 else if (cellattr1 != NULL && cellattr2 != NULL)
4232 {
4233 if ((cellattr1 + col)->width
4234 != (cellattr2 + col)->width)
4235 textline[col] = 'w';
4236 else if (!same_color(&(cellattr1 + col)->fg,
4237 &(cellattr2 + col)->fg))
4238 textline[col] = 'f';
4239 else if (!same_color(&(cellattr1 + col)->bg,
4240 &(cellattr2 + col)->bg))
4241 textline[col] = 'b';
4242 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4243 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4244 textline[col] = 'a';
4245 }
4246 p1 += len1;
4247 p2 += len2;
4248 /* TODO: handle different width */
4249 }
4250 vim_free(line1);
4251
4252 while (col < width)
4253 {
4254 if (*p1 == NUL && *p2 == NUL)
4255 textline[col] = '?';
4256 else if (*p1 == NUL)
4257 {
4258 textline[col] = '+';
4259 p2 += utfc_ptr2len(p2);
4260 }
4261 else
4262 {
4263 textline[col] = '-';
4264 p1 += utfc_ptr2len(p1);
4265 }
4266 ++col;
4267 }
4268 }
4269 if (add_empty_scrollback(term, &term->tl_default_color,
4270 term->tl_top_diff_rows) == OK)
4271 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4272 ++bot_lnum;
4273 }
4274
4275 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4276 {
4277 /* bottom part has more rows, fill with "+" */
4278 for (i = 0; i < width; ++i)
4279 textline[i] = '+';
4280 if (add_empty_scrollback(term, &term->tl_default_color,
4281 term->tl_top_diff_rows) == OK)
4282 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4283 ++lnum;
4284 ++bot_lnum;
4285 }
4286
4287 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004288
4289 /* looks better without wrapping */
4290 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004291 }
4292
4293theend:
4294 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004295 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004296 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004297 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004298 fclose(fd2);
4299}
4300
4301/*
4302 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4303 * bottom files.
4304 * Return FAIL when this is not possible.
4305 */
4306 int
4307term_swap_diff()
4308{
4309 term_T *term = curbuf->b_term;
4310 linenr_T line_count;
4311 linenr_T top_rows;
4312 linenr_T bot_rows;
4313 linenr_T bot_start;
4314 linenr_T lnum;
4315 char_u *p;
4316 sb_line_T *sb_line;
4317
4318 if (term == NULL
4319 || !term_is_finished(curbuf)
4320 || term->tl_top_diff_rows == 0
4321 || term->tl_scrollback.ga_len == 0)
4322 return FAIL;
4323
4324 line_count = curbuf->b_ml.ml_line_count;
4325 top_rows = term->tl_top_diff_rows;
4326 bot_rows = term->tl_bot_diff_rows;
4327 bot_start = line_count - bot_rows;
4328 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4329
4330 /* move lines from top to above the bottom part */
4331 for (lnum = 1; lnum <= top_rows; ++lnum)
4332 {
4333 p = vim_strsave(ml_get(1));
4334 if (p == NULL)
4335 return OK;
4336 ml_append(bot_start, p, 0, FALSE);
4337 ml_delete(1, FALSE);
4338 vim_free(p);
4339 }
4340
4341 /* move lines from bottom to the top */
4342 for (lnum = 1; lnum <= bot_rows; ++lnum)
4343 {
4344 p = vim_strsave(ml_get(bot_start + lnum));
4345 if (p == NULL)
4346 return OK;
4347 ml_delete(bot_start + lnum, FALSE);
4348 ml_append(lnum - 1, p, 0, FALSE);
4349 vim_free(p);
4350 }
4351
4352 if (top_rows == bot_rows)
4353 {
4354 /* rows counts are equal, can swap cell properties */
4355 for (lnum = 0; lnum < top_rows; ++lnum)
4356 {
4357 sb_line_T temp;
4358
4359 temp = *(sb_line + lnum);
4360 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4361 *(sb_line + bot_start + lnum) = temp;
4362 }
4363 }
4364 else
4365 {
4366 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4367 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4368
4369 /* need to copy cell properties into temp memory */
4370 if (temp != NULL)
4371 {
4372 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4373 mch_memmove(term->tl_scrollback.ga_data,
4374 temp + bot_start,
4375 sizeof(sb_line_T) * bot_rows);
4376 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4377 temp + top_rows,
4378 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4379 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4380 + line_count - top_rows,
4381 temp,
4382 sizeof(sb_line_T) * top_rows);
4383 vim_free(temp);
4384 }
4385 }
4386
4387 term->tl_top_diff_rows = bot_rows;
4388 term->tl_bot_diff_rows = top_rows;
4389
4390 update_screen(NOT_VALID);
4391 return OK;
4392}
4393
4394/*
4395 * "term_dumpdiff(filename, filename, options)" function
4396 */
4397 void
4398f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4399{
4400 term_load_dump(argvars, rettv, TRUE);
4401}
4402
4403/*
4404 * "term_dumpload(filename, options)" function
4405 */
4406 void
4407f_term_dumpload(typval_T *argvars, typval_T *rettv)
4408{
4409 term_load_dump(argvars, rettv, FALSE);
4410}
4411
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004412/*
4413 * "term_getaltscreen(buf)" function
4414 */
4415 void
4416f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4417{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004418 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004419
4420 if (buf == NULL)
4421 return;
4422 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4423}
4424
4425/*
4426 * "term_getattr(attr, name)" function
4427 */
4428 void
4429f_term_getattr(typval_T *argvars, typval_T *rettv)
4430{
4431 int attr;
4432 size_t i;
4433 char_u *name;
4434
4435 static struct {
4436 char *name;
4437 int attr;
4438 } attrs[] = {
4439 {"bold", HL_BOLD},
4440 {"italic", HL_ITALIC},
4441 {"underline", HL_UNDERLINE},
4442 {"strike", HL_STRIKETHROUGH},
4443 {"reverse", HL_INVERSE},
4444 };
4445
4446 attr = get_tv_number(&argvars[0]);
4447 name = get_tv_string_chk(&argvars[1]);
4448 if (name == NULL)
4449 return;
4450
4451 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4452 if (STRCMP(name, attrs[i].name) == 0)
4453 {
4454 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4455 break;
4456 }
4457}
4458
4459/*
4460 * "term_getcursor(buf)" function
4461 */
4462 void
4463f_term_getcursor(typval_T *argvars, typval_T *rettv)
4464{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004465 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004466 term_T *term;
4467 list_T *l;
4468 dict_T *d;
4469
4470 if (rettv_list_alloc(rettv) == FAIL)
4471 return;
4472 if (buf == NULL)
4473 return;
4474 term = buf->b_term;
4475
4476 l = rettv->vval.v_list;
4477 list_append_number(l, term->tl_cursor_pos.row + 1);
4478 list_append_number(l, term->tl_cursor_pos.col + 1);
4479
4480 d = dict_alloc();
4481 if (d != NULL)
4482 {
4483 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4484 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4485 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4486 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4487 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4488 ? (char_u *)"" : term->tl_cursor_color);
4489 list_append_dict(l, d);
4490 }
4491}
4492
4493/*
4494 * "term_getjob(buf)" function
4495 */
4496 void
4497f_term_getjob(typval_T *argvars, typval_T *rettv)
4498{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004499 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004500
4501 rettv->v_type = VAR_JOB;
4502 rettv->vval.v_job = NULL;
4503 if (buf == NULL)
4504 return;
4505
4506 rettv->vval.v_job = buf->b_term->tl_job;
4507 if (rettv->vval.v_job != NULL)
4508 ++rettv->vval.v_job->jv_refcount;
4509}
4510
4511 static int
4512get_row_number(typval_T *tv, term_T *term)
4513{
4514 if (tv->v_type == VAR_STRING
4515 && tv->vval.v_string != NULL
4516 && STRCMP(tv->vval.v_string, ".") == 0)
4517 return term->tl_cursor_pos.row;
4518 return (int)get_tv_number(tv) - 1;
4519}
4520
4521/*
4522 * "term_getline(buf, row)" function
4523 */
4524 void
4525f_term_getline(typval_T *argvars, typval_T *rettv)
4526{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004527 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004528 term_T *term;
4529 int row;
4530
4531 rettv->v_type = VAR_STRING;
4532 if (buf == NULL)
4533 return;
4534 term = buf->b_term;
4535 row = get_row_number(&argvars[1], term);
4536
4537 if (term->tl_vterm == NULL)
4538 {
4539 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4540
4541 /* vterm is finished, get the text from the buffer */
4542 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4543 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4544 }
4545 else
4546 {
4547 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4548 VTermRect rect;
4549 int len;
4550 char_u *p;
4551
4552 if (row < 0 || row >= term->tl_rows)
4553 return;
4554 len = term->tl_cols * MB_MAXBYTES + 1;
4555 p = alloc(len);
4556 if (p == NULL)
4557 return;
4558 rettv->vval.v_string = p;
4559
4560 rect.start_col = 0;
4561 rect.end_col = term->tl_cols;
4562 rect.start_row = row;
4563 rect.end_row = row + 1;
4564 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4565 }
4566}
4567
4568/*
4569 * "term_getscrolled(buf)" function
4570 */
4571 void
4572f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4573{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004574 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004575
4576 if (buf == NULL)
4577 return;
4578 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4579}
4580
4581/*
4582 * "term_getsize(buf)" function
4583 */
4584 void
4585f_term_getsize(typval_T *argvars, typval_T *rettv)
4586{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004587 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004588 list_T *l;
4589
4590 if (rettv_list_alloc(rettv) == FAIL)
4591 return;
4592 if (buf == NULL)
4593 return;
4594
4595 l = rettv->vval.v_list;
4596 list_append_number(l, buf->b_term->tl_rows);
4597 list_append_number(l, buf->b_term->tl_cols);
4598}
4599
4600/*
4601 * "term_getstatus(buf)" function
4602 */
4603 void
4604f_term_getstatus(typval_T *argvars, typval_T *rettv)
4605{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004606 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004607 term_T *term;
4608 char_u val[100];
4609
4610 rettv->v_type = VAR_STRING;
4611 if (buf == NULL)
4612 return;
4613 term = buf->b_term;
4614
4615 if (term_job_running(term))
4616 STRCPY(val, "running");
4617 else
4618 STRCPY(val, "finished");
4619 if (term->tl_normal_mode)
4620 STRCAT(val, ",normal");
4621 rettv->vval.v_string = vim_strsave(val);
4622}
4623
4624/*
4625 * "term_gettitle(buf)" function
4626 */
4627 void
4628f_term_gettitle(typval_T *argvars, typval_T *rettv)
4629{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004630 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004631
4632 rettv->v_type = VAR_STRING;
4633 if (buf == NULL)
4634 return;
4635
4636 if (buf->b_term->tl_title != NULL)
4637 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4638}
4639
4640/*
4641 * "term_gettty(buf)" function
4642 */
4643 void
4644f_term_gettty(typval_T *argvars, typval_T *rettv)
4645{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004646 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004647 char_u *p;
4648 int num = 0;
4649
4650 rettv->v_type = VAR_STRING;
4651 if (buf == NULL)
4652 return;
4653 if (argvars[1].v_type != VAR_UNKNOWN)
4654 num = get_tv_number(&argvars[1]);
4655
4656 switch (num)
4657 {
4658 case 0:
4659 if (buf->b_term->tl_job != NULL)
4660 p = buf->b_term->tl_job->jv_tty_out;
4661 else
4662 p = buf->b_term->tl_tty_out;
4663 break;
4664 case 1:
4665 if (buf->b_term->tl_job != NULL)
4666 p = buf->b_term->tl_job->jv_tty_in;
4667 else
4668 p = buf->b_term->tl_tty_in;
4669 break;
4670 default:
4671 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4672 return;
4673 }
4674 if (p != NULL)
4675 rettv->vval.v_string = vim_strsave(p);
4676}
4677
4678/*
4679 * "term_list()" function
4680 */
4681 void
4682f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4683{
4684 term_T *tp;
4685 list_T *l;
4686
4687 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4688 return;
4689
4690 l = rettv->vval.v_list;
4691 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4692 if (tp != NULL && tp->tl_buffer != NULL)
4693 if (list_append_number(l,
4694 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4695 return;
4696}
4697
4698/*
4699 * "term_scrape(buf, row)" function
4700 */
4701 void
4702f_term_scrape(typval_T *argvars, typval_T *rettv)
4703{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004704 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004705 VTermScreen *screen = NULL;
4706 VTermPos pos;
4707 list_T *l;
4708 term_T *term;
4709 char_u *p;
4710 sb_line_T *line;
4711
4712 if (rettv_list_alloc(rettv) == FAIL)
4713 return;
4714 if (buf == NULL)
4715 return;
4716 term = buf->b_term;
4717
4718 l = rettv->vval.v_list;
4719 pos.row = get_row_number(&argvars[1], term);
4720
4721 if (term->tl_vterm != NULL)
4722 {
4723 screen = vterm_obtain_screen(term->tl_vterm);
4724 p = NULL;
4725 line = NULL;
4726 }
4727 else
4728 {
4729 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4730
4731 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4732 return;
4733 p = ml_get_buf(buf, lnum + 1, FALSE);
4734 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4735 }
4736
4737 for (pos.col = 0; pos.col < term->tl_cols; )
4738 {
4739 dict_T *dcell;
4740 int width;
4741 VTermScreenCellAttrs attrs;
4742 VTermColor fg, bg;
4743 char_u rgb[8];
4744 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4745 int off = 0;
4746 int i;
4747
4748 if (screen == NULL)
4749 {
4750 cellattr_T *cellattr;
4751 int len;
4752
4753 /* vterm has finished, get the cell from scrollback */
4754 if (pos.col >= line->sb_cols)
4755 break;
4756 cellattr = line->sb_cells + pos.col;
4757 width = cellattr->width;
4758 attrs = cellattr->attrs;
4759 fg = cellattr->fg;
4760 bg = cellattr->bg;
4761 len = MB_PTR2LEN(p);
4762 mch_memmove(mbs, p, len);
4763 mbs[len] = NUL;
4764 p += len;
4765 }
4766 else
4767 {
4768 VTermScreenCell cell;
4769 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4770 break;
4771 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4772 {
4773 if (cell.chars[i] == 0)
4774 break;
4775 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4776 }
4777 mbs[off] = NUL;
4778 width = cell.width;
4779 attrs = cell.attrs;
4780 fg = cell.fg;
4781 bg = cell.bg;
4782 }
4783 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004784 if (dcell == NULL)
4785 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004786 list_append_dict(l, dcell);
4787
4788 dict_add_nr_str(dcell, "chars", 0, mbs);
4789
4790 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4791 fg.red, fg.green, fg.blue);
4792 dict_add_nr_str(dcell, "fg", 0, rgb);
4793 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4794 bg.red, bg.green, bg.blue);
4795 dict_add_nr_str(dcell, "bg", 0, rgb);
4796
4797 dict_add_nr_str(dcell, "attr",
4798 cell2attr(attrs, fg, bg), NULL);
4799 dict_add_nr_str(dcell, "width", width, NULL);
4800
4801 ++pos.col;
4802 if (width == 2)
4803 ++pos.col;
4804 }
4805}
4806
4807/*
4808 * "term_sendkeys(buf, keys)" function
4809 */
4810 void
4811f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4812{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004813 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004814 char_u *msg;
4815 term_T *term;
4816
4817 rettv->v_type = VAR_UNKNOWN;
4818 if (buf == NULL)
4819 return;
4820
4821 msg = get_tv_string_chk(&argvars[1]);
4822 if (msg == NULL)
4823 return;
4824 term = buf->b_term;
4825 if (term->tl_vterm == NULL)
4826 return;
4827
4828 while (*msg != NUL)
4829 {
4830 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004831 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004832 }
4833}
4834
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004835#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4836/*
4837 * "term_getansicolors(buf)" function
4838 */
4839 void
4840f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4841{
4842 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4843 term_T *term;
4844 VTermState *state;
4845 VTermColor color;
4846 char_u hexbuf[10];
4847 int index;
4848 list_T *list;
4849
4850 if (rettv_list_alloc(rettv) == FAIL)
4851 return;
4852
4853 if (buf == NULL)
4854 return;
4855 term = buf->b_term;
4856 if (term->tl_vterm == NULL)
4857 return;
4858
4859 list = rettv->vval.v_list;
4860 state = vterm_obtain_state(term->tl_vterm);
4861 for (index = 0; index < 16; index++)
4862 {
4863 vterm_state_get_palette_color(state, index, &color);
4864 sprintf((char *)hexbuf, "#%02x%02x%02x",
4865 color.red, color.green, color.blue);
4866 if (list_append_string(list, hexbuf, 7) == FAIL)
4867 return;
4868 }
4869}
4870
4871/*
4872 * "term_setansicolors(buf, list)" function
4873 */
4874 void
4875f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4876{
4877 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4878 term_T *term;
4879
4880 if (buf == NULL)
4881 return;
4882 term = buf->b_term;
4883 if (term->tl_vterm == NULL)
4884 return;
4885
4886 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4887 {
4888 EMSG(_(e_listreq));
4889 return;
4890 }
4891
4892 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4893 EMSG(_(e_invarg));
4894}
4895#endif
4896
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004897/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004898 * "term_setrestore(buf, command)" function
4899 */
4900 void
4901f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4902{
4903#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004904 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004905 term_T *term;
4906 char_u *cmd;
4907
4908 if (buf == NULL)
4909 return;
4910 term = buf->b_term;
4911 vim_free(term->tl_command);
4912 cmd = get_tv_string_chk(&argvars[1]);
4913 if (cmd != NULL)
4914 term->tl_command = vim_strsave(cmd);
4915 else
4916 term->tl_command = NULL;
4917#endif
4918}
4919
4920/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004921 * "term_setkill(buf, how)" function
4922 */
4923 void
4924f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4925{
4926 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4927 term_T *term;
4928 char_u *how;
4929
4930 if (buf == NULL)
4931 return;
4932 term = buf->b_term;
4933 vim_free(term->tl_kill);
4934 how = get_tv_string_chk(&argvars[1]);
4935 if (how != NULL)
4936 term->tl_kill = vim_strsave(how);
4937 else
4938 term->tl_kill = NULL;
4939}
4940
4941/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942 * "term_start(command, options)" function
4943 */
4944 void
4945f_term_start(typval_T *argvars, typval_T *rettv)
4946{
4947 jobopt_T opt;
4948 buf_T *buf;
4949
4950 init_job_options(&opt);
4951 if (argvars[1].v_type != VAR_UNKNOWN
4952 && get_job_options(&argvars[1], &opt,
4953 JO_TIMEOUT_ALL + JO_STOPONEXIT
4954 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4955 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4956 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4957 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004958 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004959 + JO2_NORESTORE + JO2_TERM_KILL
4960 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004961 return;
4962
Bram Moolenaar13568252018-03-16 20:46:58 +01004963 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004964
4965 if (buf != NULL && buf->b_term != NULL)
4966 rettv->vval.v_number = buf->b_fnum;
4967}
4968
4969/*
4970 * "term_wait" function
4971 */
4972 void
4973f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4974{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004975 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004976
4977 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004978 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004979 if (buf->b_term->tl_job == NULL)
4980 {
4981 ch_log(NULL, "term_wait(): no job to wait for");
4982 return;
4983 }
4984 if (buf->b_term->tl_job->jv_channel == NULL)
4985 /* channel is closed, nothing to do */
4986 return;
4987
4988 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004989 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004990 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4991 {
4992 /* The job is dead, keep reading channel I/O until the channel is
4993 * closed. buf->b_term may become NULL if the terminal was closed while
4994 * waiting. */
4995 ch_log(NULL, "term_wait(): waiting for channel to close");
4996 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4997 {
4998 mch_check_messages();
4999 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005000 if (!buf_valid(buf))
5001 /* If the terminal is closed when the channel is closed the
5002 * buffer disappears. */
5003 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005004 ui_delay(10L, FALSE);
5005 }
5006 mch_check_messages();
5007 parse_queued_messages();
5008 }
5009 else
5010 {
5011 long wait = 10L;
5012
5013 mch_check_messages();
5014 parse_queued_messages();
5015
5016 /* Wait for some time for any channel I/O. */
5017 if (argvars[1].v_type != VAR_UNKNOWN)
5018 wait = get_tv_number(&argvars[1]);
5019 ui_delay(wait, TRUE);
5020 mch_check_messages();
5021
5022 /* Flushing messages on channels is hopefully sufficient.
5023 * TODO: is there a better way? */
5024 parse_queued_messages();
5025 }
5026}
5027
5028/*
5029 * Called when a channel has sent all the lines to a terminal.
5030 * Send a CTRL-D to mark the end of the text.
5031 */
5032 void
5033term_send_eof(channel_T *ch)
5034{
5035 term_T *term;
5036
5037 for (term = first_term; term != NULL; term = term->tl_next)
5038 if (term->tl_job == ch->ch_job)
5039 {
5040 if (term->tl_eof_chars != NULL)
5041 {
5042 channel_send(ch, PART_IN, term->tl_eof_chars,
5043 (int)STRLEN(term->tl_eof_chars), NULL);
5044 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5045 }
5046# ifdef WIN3264
5047 else
5048 /* Default: CTRL-D */
5049 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5050# endif
5051 }
5052}
5053
5054# if defined(WIN3264) || defined(PROTO)
5055
5056/**************************************
5057 * 2. MS-Windows implementation.
5058 */
5059
5060# ifndef PROTO
5061
5062#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5063#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005064#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005065
5066void* (*winpty_config_new)(UINT64, void*);
5067void* (*winpty_open)(void*, void*);
5068void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5069BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5070void (*winpty_config_set_mouse_mode)(void*, int);
5071void (*winpty_config_set_initial_size)(void*, int, int);
5072LPCWSTR (*winpty_conin_name)(void*);
5073LPCWSTR (*winpty_conout_name)(void*);
5074LPCWSTR (*winpty_conerr_name)(void*);
5075void (*winpty_free)(void*);
5076void (*winpty_config_free)(void*);
5077void (*winpty_spawn_config_free)(void*);
5078void (*winpty_error_free)(void*);
5079LPCWSTR (*winpty_error_msg)(void*);
5080BOOL (*winpty_set_size)(void*, int, int, void*);
5081HANDLE (*winpty_agent_process)(void*);
5082
5083#define WINPTY_DLL "winpty.dll"
5084
5085static HINSTANCE hWinPtyDLL = NULL;
5086# endif
5087
5088 static int
5089dyn_winpty_init(int verbose)
5090{
5091 int i;
5092 static struct
5093 {
5094 char *name;
5095 FARPROC *ptr;
5096 } winpty_entry[] =
5097 {
5098 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5099 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5100 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5101 {"winpty_config_set_mouse_mode",
5102 (FARPROC*)&winpty_config_set_mouse_mode},
5103 {"winpty_config_set_initial_size",
5104 (FARPROC*)&winpty_config_set_initial_size},
5105 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5106 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5107 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5108 {"winpty_free", (FARPROC*)&winpty_free},
5109 {"winpty_open", (FARPROC*)&winpty_open},
5110 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5111 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5112 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5113 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5114 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5115 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5116 {NULL, NULL}
5117 };
5118
5119 /* No need to initialize twice. */
5120 if (hWinPtyDLL)
5121 return OK;
5122 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5123 * winpty.dll. */
5124 if (*p_winptydll != NUL)
5125 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5126 if (!hWinPtyDLL)
5127 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5128 if (!hWinPtyDLL)
5129 {
5130 if (verbose)
5131 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5132 : (char_u *)WINPTY_DLL);
5133 return FAIL;
5134 }
5135 for (i = 0; winpty_entry[i].name != NULL
5136 && winpty_entry[i].ptr != NULL; ++i)
5137 {
5138 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5139 winpty_entry[i].name)) == NULL)
5140 {
5141 if (verbose)
5142 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5143 return FAIL;
5144 }
5145 }
5146
5147 return OK;
5148}
5149
5150/*
5151 * Create a new terminal of "rows" by "cols" cells.
5152 * Store a reference in "term".
5153 * Return OK or FAIL.
5154 */
5155 static int
5156term_and_job_init(
5157 term_T *term,
5158 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005159 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005160 jobopt_T *opt)
5161{
5162 WCHAR *cmd_wchar = NULL;
5163 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005164 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005165 channel_T *channel = NULL;
5166 job_T *job = NULL;
5167 DWORD error;
5168 HANDLE jo = NULL;
5169 HANDLE child_process_handle;
5170 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005171 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005172 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005173 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005174 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005175
5176 if (dyn_winpty_init(TRUE) == FAIL)
5177 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005178 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5179 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005180
5181 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005182 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005183 cmd = argvar->vval.v_string;
5184 }
5185 else if (argvar->v_type == VAR_LIST)
5186 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005187 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005188 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005189 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005190 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005191 if (cmd == NULL || *cmd == NUL)
5192 {
5193 EMSG(_(e_invarg));
5194 goto failed;
5195 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005196
5197 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005198 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005199 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005200 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005201 if (opt->jo_cwd != NULL)
5202 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005203
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005204 win32_build_env(opt->jo_env, &ga_env, TRUE);
5205 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005206
5207 job = job_alloc();
5208 if (job == NULL)
5209 goto failed;
5210
5211 channel = add_channel();
5212 if (channel == NULL)
5213 goto failed;
5214
5215 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5216 if (term->tl_winpty_config == NULL)
5217 goto failed;
5218
5219 winpty_config_set_mouse_mode(term->tl_winpty_config,
5220 WINPTY_MOUSE_MODE_FORCE);
5221 winpty_config_set_initial_size(term->tl_winpty_config,
5222 term->tl_cols, term->tl_rows);
5223 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5224 if (term->tl_winpty == NULL)
5225 goto failed;
5226
5227 spawn_config = winpty_spawn_config_new(
5228 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5229 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5230 NULL,
5231 cmd_wchar,
5232 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005233 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005234 &winpty_err);
5235 if (spawn_config == NULL)
5236 goto failed;
5237
5238 channel = add_channel();
5239 if (channel == NULL)
5240 goto failed;
5241
5242 job = job_alloc();
5243 if (job == NULL)
5244 goto failed;
5245
5246 if (opt->jo_set & JO_IN_BUF)
5247 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5248
5249 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5250 &child_thread_handle, &error, &winpty_err))
5251 goto failed;
5252
5253 channel_set_pipes(channel,
5254 (sock_T)CreateFileW(
5255 winpty_conin_name(term->tl_winpty),
5256 GENERIC_WRITE, 0, NULL,
5257 OPEN_EXISTING, 0, NULL),
5258 (sock_T)CreateFileW(
5259 winpty_conout_name(term->tl_winpty),
5260 GENERIC_READ, 0, NULL,
5261 OPEN_EXISTING, 0, NULL),
5262 (sock_T)CreateFileW(
5263 winpty_conerr_name(term->tl_winpty),
5264 GENERIC_READ, 0, NULL,
5265 OPEN_EXISTING, 0, NULL));
5266
5267 /* Write lines with CR instead of NL. */
5268 channel->ch_write_text_mode = TRUE;
5269
5270 jo = CreateJobObject(NULL, NULL);
5271 if (jo == NULL)
5272 goto failed;
5273
5274 if (!AssignProcessToJobObject(jo, child_process_handle))
5275 {
5276 /* Failed, switch the way to terminate process with TerminateProcess. */
5277 CloseHandle(jo);
5278 jo = NULL;
5279 }
5280
5281 winpty_spawn_config_free(spawn_config);
5282 vim_free(cmd_wchar);
5283 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005284 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005285
5286 create_vterm(term, term->tl_rows, term->tl_cols);
5287
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005288#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5289 if (opt->jo_set2 & JO2_ANSI_COLORS)
5290 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5291 else
5292 init_vterm_ansi_colors(term->tl_vterm);
5293#endif
5294
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005295 channel_set_job(channel, job, opt);
5296 job_set_options(job, opt);
5297
5298 job->jv_channel = channel;
5299 job->jv_proc_info.hProcess = child_process_handle;
5300 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5301 job->jv_job_object = jo;
5302 job->jv_status = JOB_STARTED;
5303 job->jv_tty_in = utf16_to_enc(
5304 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5305 job->jv_tty_out = utf16_to_enc(
5306 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5307 ++job->jv_refcount;
5308 term->tl_job = job;
5309
5310 return OK;
5311
5312failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005313 ga_clear(&ga_cmd);
5314 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005315 vim_free(cmd_wchar);
5316 vim_free(cwd_wchar);
5317 if (spawn_config != NULL)
5318 winpty_spawn_config_free(spawn_config);
5319 if (channel != NULL)
5320 channel_clear(channel);
5321 if (job != NULL)
5322 {
5323 job->jv_channel = NULL;
5324 job_cleanup(job);
5325 }
5326 term->tl_job = NULL;
5327 if (jo != NULL)
5328 CloseHandle(jo);
5329 if (term->tl_winpty != NULL)
5330 winpty_free(term->tl_winpty);
5331 term->tl_winpty = NULL;
5332 if (term->tl_winpty_config != NULL)
5333 winpty_config_free(term->tl_winpty_config);
5334 term->tl_winpty_config = NULL;
5335 if (winpty_err != NULL)
5336 {
5337 char_u *msg = utf16_to_enc(
5338 (short_u *)winpty_error_msg(winpty_err), NULL);
5339
5340 EMSG(msg);
5341 winpty_error_free(winpty_err);
5342 }
5343 return FAIL;
5344}
5345
5346 static int
5347create_pty_only(term_T *term, jobopt_T *options)
5348{
5349 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5350 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5351 char in_name[80], out_name[80];
5352 channel_T *channel = NULL;
5353
5354 create_vterm(term, term->tl_rows, term->tl_cols);
5355
5356 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5357 GetCurrentProcessId(),
5358 curbuf->b_fnum);
5359 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5360 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5361 PIPE_UNLIMITED_INSTANCES,
5362 0, 0, NMPWAIT_NOWAIT, NULL);
5363 if (hPipeIn == INVALID_HANDLE_VALUE)
5364 goto failed;
5365
5366 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5367 GetCurrentProcessId(),
5368 curbuf->b_fnum);
5369 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5370 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5371 PIPE_UNLIMITED_INSTANCES,
5372 0, 0, 0, NULL);
5373 if (hPipeOut == INVALID_HANDLE_VALUE)
5374 goto failed;
5375
5376 ConnectNamedPipe(hPipeIn, NULL);
5377 ConnectNamedPipe(hPipeOut, NULL);
5378
5379 term->tl_job = job_alloc();
5380 if (term->tl_job == NULL)
5381 goto failed;
5382 ++term->tl_job->jv_refcount;
5383
5384 /* behave like the job is already finished */
5385 term->tl_job->jv_status = JOB_FINISHED;
5386
5387 channel = add_channel();
5388 if (channel == NULL)
5389 goto failed;
5390 term->tl_job->jv_channel = channel;
5391 channel->ch_keep_open = TRUE;
5392 channel->ch_named_pipe = TRUE;
5393
5394 channel_set_pipes(channel,
5395 (sock_T)hPipeIn,
5396 (sock_T)hPipeOut,
5397 (sock_T)hPipeOut);
5398 channel_set_job(channel, term->tl_job, options);
5399 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5400 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5401
5402 return OK;
5403
5404failed:
5405 if (hPipeIn != NULL)
5406 CloseHandle(hPipeIn);
5407 if (hPipeOut != NULL)
5408 CloseHandle(hPipeOut);
5409 return FAIL;
5410}
5411
5412/*
5413 * Free the terminal emulator part of "term".
5414 */
5415 static void
5416term_free_vterm(term_T *term)
5417{
5418 if (term->tl_winpty != NULL)
5419 winpty_free(term->tl_winpty);
5420 term->tl_winpty = NULL;
5421 if (term->tl_winpty_config != NULL)
5422 winpty_config_free(term->tl_winpty_config);
5423 term->tl_winpty_config = NULL;
5424 if (term->tl_vterm != NULL)
5425 vterm_free(term->tl_vterm);
5426 term->tl_vterm = NULL;
5427}
5428
5429/*
5430 * Request size to terminal.
5431 */
5432 static void
5433term_report_winsize(term_T *term, int rows, int cols)
5434{
5435 if (term->tl_winpty)
5436 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5437}
5438
5439 int
5440terminal_enabled(void)
5441{
5442 return dyn_winpty_init(FALSE) == OK;
5443}
5444
5445# else
5446
5447/**************************************
5448 * 3. Unix-like implementation.
5449 */
5450
5451/*
5452 * Create a new terminal of "rows" by "cols" cells.
5453 * Start job for "cmd".
5454 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005455 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005456 * Return OK or FAIL.
5457 */
5458 static int
5459term_and_job_init(
5460 term_T *term,
5461 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005462 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005463 jobopt_T *opt)
5464{
5465 create_vterm(term, term->tl_rows, term->tl_cols);
5466
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005467#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5468 if (opt->jo_set2 & JO2_ANSI_COLORS)
5469 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5470 else
5471 init_vterm_ansi_colors(term->tl_vterm);
5472#endif
5473
Bram Moolenaar13568252018-03-16 20:46:58 +01005474 /* This may change a string in "argvar". */
5475 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005476 if (term->tl_job != NULL)
5477 ++term->tl_job->jv_refcount;
5478
5479 return term->tl_job != NULL
5480 && term->tl_job->jv_channel != NULL
5481 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5482}
5483
5484 static int
5485create_pty_only(term_T *term, jobopt_T *opt)
5486{
5487 create_vterm(term, term->tl_rows, term->tl_cols);
5488
5489 term->tl_job = job_alloc();
5490 if (term->tl_job == NULL)
5491 return FAIL;
5492 ++term->tl_job->jv_refcount;
5493
5494 /* behave like the job is already finished */
5495 term->tl_job->jv_status = JOB_FINISHED;
5496
5497 return mch_create_pty_channel(term->tl_job, opt);
5498}
5499
5500/*
5501 * Free the terminal emulator part of "term".
5502 */
5503 static void
5504term_free_vterm(term_T *term)
5505{
5506 if (term->tl_vterm != NULL)
5507 vterm_free(term->tl_vterm);
5508 term->tl_vterm = NULL;
5509}
5510
5511/*
5512 * Request size to terminal.
5513 */
5514 static void
5515term_report_winsize(term_T *term, int rows, int cols)
5516{
5517 /* Use an ioctl() to report the new window size to the job. */
5518 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5519 {
5520 int fd = -1;
5521 int part;
5522
5523 for (part = PART_OUT; part < PART_COUNT; ++part)
5524 {
5525 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5526 if (isatty(fd))
5527 break;
5528 }
5529 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5530 mch_signal_job(term->tl_job, (char_u *)"winch");
5531 }
5532}
5533
5534# endif
5535
5536#endif /* FEAT_TERMINAL */