blob: 9a551a7844f616e4adcca48360b20ab083fcca7f [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 Moolenaar802bfb12018-04-15 17:28:13 +020043 * - Win32: Redirecting output does not work, Test_terminal_redir_file()
44 * is disabled.
Bram Moolenaar802bfb12018-04-15 17:28:13 +020045 * - When starting terminal window with shell in terminal, then using :gui to
46 * switch to GUI, shell stops working. Scrollback seems wrong, command
47 * running in shell is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020048 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar498c2562018-04-15 23:45:15 +020049 * - Copy text in the vterm to the Vim buffer once in a while, so that
50 * completion works.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020051 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020052 * - For the GUI fill termios with default values, perhaps like pangoterm:
53 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020054 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020056 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
57 * "run". Everything else works, including communication channel. Not
58 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020059 */
60
61#include "vim.h"
62
63#if defined(FEAT_TERMINAL) || defined(PROTO)
64
65#ifndef MIN
66# define MIN(x,y) ((x) < (y) ? (x) : (y))
67#endif
68#ifndef MAX
69# define MAX(x,y) ((x) > (y) ? (x) : (y))
70#endif
71
72#include "libvterm/include/vterm.h"
73
74/* This is VTermScreenCell without the characters, thus much smaller. */
75typedef struct {
76 VTermScreenCellAttrs attrs;
77 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010078 VTermColor fg;
79 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020080} cellattr_T;
81
82typedef struct sb_line_S {
83 int sb_cols; /* can differ per line */
84 cellattr_T *sb_cells; /* allocated */
85 cellattr_T sb_fill_attr; /* for short line */
86} sb_line_T;
87
88/* typedef term_T in structs.h */
89struct terminal_S {
90 term_T *tl_next;
91
92 VTerm *tl_vterm;
93 job_T *tl_job;
94 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010095#if defined(FEAT_GUI)
96 int tl_system; /* when non-zero used for :!cmd output */
97 int tl_toprow; /* row with first line of system terminal */
98#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099
100 /* Set when setting the size of a vterm, reset after redrawing. */
101 int tl_vterm_size_changed;
102
103 /* used when tl_job is NULL and only a pty was created */
104 int tl_tty_fd;
105 char_u *tl_tty_in;
106 char_u *tl_tty_out;
107
108 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
109 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100110 int tl_finish;
111#define TL_FINISH_UNSET NUL
112#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
113#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
114#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200115 char_u *tl_opencmd;
116 char_u *tl_eof_chars;
117
118#ifdef WIN3264
119 void *tl_winpty_config;
120 void *tl_winpty;
121#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100122#if defined(FEAT_SESSION)
123 char_u *tl_command;
124#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100125 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200126
127 /* last known vterm size */
128 int tl_rows;
129 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
131 char_u *tl_title; /* NULL or allocated */
132 char_u *tl_status_text; /* NULL or allocated */
133
134 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200135 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136 int tl_dirty_row_end; /* row below last one to update */
137
138 garray_T tl_scrollback;
139 int tl_scrollback_scrolled;
140 cellattr_T tl_default_color;
141
Bram Moolenaard96ff162018-02-18 22:13:29 +0100142 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
143 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
144
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200145 VTermPos tl_cursor_pos;
146 int tl_cursor_visible;
147 int tl_cursor_blink;
148 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
149 char_u *tl_cursor_color; /* NULL or allocated */
150
151 int tl_using_altscreen;
152};
153
154#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
155#define TMODE_LOOP 2 /* CTRL-W N used */
156
157/*
158 * List of all active terminals.
159 */
160static term_T *first_term = NULL;
161
162/* Terminal active in terminal_loop(). */
163static term_T *in_terminal_loop = NULL;
164
165#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
166#define KEY_BUF_LEN 200
167
168/*
169 * Functions with separate implementation for MS-Windows and Unix-like systems.
170 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100171static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200172static int create_pty_only(term_T *term, jobopt_T *opt);
173static void term_report_winsize(term_T *term, int rows, int cols);
174static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100175#ifdef FEAT_GUI
176static void update_system_term(term_T *term);
177#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200178
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100179/* The character that we know (or assume) that the terminal expects for the
180 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100183/* "Terminal" highlight group colors. */
184static int term_default_cterm_fg = -1;
185static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186
Bram Moolenaard317b382018-02-08 22:33:31 +0100187/* Store the last set and the desired cursor properties, so that we only update
188 * them when needed. Doing it unnecessary may result in flicker. */
189static char_u *last_set_cursor_color = (char_u *)"";
190static char_u *desired_cursor_color = (char_u *)"";
191static int last_set_cursor_shape = -1;
192static int desired_cursor_shape = -1;
193static int last_set_cursor_blink = -1;
194static int desired_cursor_blink = -1;
195
196
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200197/**************************************
198 * 1. Generic code for all systems.
199 */
200
201/*
Bram Moolenaar498c2562018-04-15 23:45:15 +0200202 * Parse 'termsize' and set "rows" and "cols" for the terminal size in the
203 * current window.
204 * Sets "rows" and/or "cols" to zero when it should follow the window size.
205 * Return TRUE if the size is the minimum size: "24*80".
206 */
207 static int
208parse_termsize(win_T *wp, int *rows, int *cols)
209{
210 int minsize = FALSE;
211
212 *rows = 0;
213 *cols = 0;
214
215 if (*wp->w_p_tms != NUL)
216 {
217 char_u *p = vim_strchr(wp->w_p_tms, 'x');
218
219 /* Syntax of value was already checked when it's set. */
220 if (p == NULL)
221 {
222 minsize = TRUE;
223 p = vim_strchr(wp->w_p_tms, '*');
224 }
225 *rows = atoi((char *)wp->w_p_tms);
226 *cols = atoi((char *)p + 1);
227 }
228 return minsize;
229}
230
231/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200232 * Determine the terminal size from 'termsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200233 */
234 static void
235set_term_and_win_size(term_T *term)
236{
Bram Moolenaar13568252018-03-16 20:46:58 +0100237#ifdef FEAT_GUI
238 if (term->tl_system)
239 {
240 /* Use the whole screen for the system command. However, it will start
241 * at the command line and scroll up as needed, using tl_toprow. */
242 term->tl_rows = Rows;
243 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200244 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100245 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100246#endif
Bram Moolenaar498c2562018-04-15 23:45:15 +0200247 if (parse_termsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200249 if (term->tl_rows != 0)
250 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
251 if (term->tl_cols != 0)
252 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200253 }
254 if (term->tl_rows == 0)
255 term->tl_rows = curwin->w_height;
256 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200257 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200258 if (term->tl_cols == 0)
259 term->tl_cols = curwin->w_width;
260 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200261 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200262}
263
264/*
265 * Initialize job options for a terminal job.
266 * Caller may overrule some of them.
267 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100268 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200269init_job_options(jobopt_T *opt)
270{
271 clear_job_options(opt);
272
273 opt->jo_mode = MODE_RAW;
274 opt->jo_out_mode = MODE_RAW;
275 opt->jo_err_mode = MODE_RAW;
276 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
277}
278
279/*
280 * Set job options mandatory for a terminal job.
281 */
282 static void
283setup_job_options(jobopt_T *opt, int rows, int cols)
284{
285 if (!(opt->jo_set & JO_OUT_IO))
286 {
287 /* Connect stdout to the terminal. */
288 opt->jo_io[PART_OUT] = JIO_BUFFER;
289 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
290 opt->jo_modifiable[PART_OUT] = 0;
291 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
292 }
293
294 if (!(opt->jo_set & JO_ERR_IO))
295 {
296 /* Connect stderr to the terminal. */
297 opt->jo_io[PART_ERR] = JIO_BUFFER;
298 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
299 opt->jo_modifiable[PART_ERR] = 0;
300 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
301 }
302
303 opt->jo_pty = TRUE;
304 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
305 opt->jo_term_rows = rows;
306 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
307 opt->jo_term_cols = cols;
308}
309
310/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100311 * Close a terminal buffer (and its window). Used when creating the terminal
312 * fails.
313 */
314 static void
315term_close_buffer(buf_T *buf, buf_T *old_curbuf)
316{
317 free_terminal(buf);
318 if (old_curbuf != NULL)
319 {
320 --curbuf->b_nwindows;
321 curbuf = old_curbuf;
322 curwin->w_buffer = curbuf;
323 ++curbuf->b_nwindows;
324 }
325
326 /* Wiping out the buffer will also close the window and call
327 * free_terminal(). */
328 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
329}
330
331/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200332 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100333 * Use either "argvar" or "argv", the other must be NULL.
334 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
335 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200336 * Returns NULL when failed.
337 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100338 buf_T *
339term_start(
340 typval_T *argvar,
341 char **argv,
342 jobopt_T *opt,
343 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344{
345 exarg_T split_ea;
346 win_T *old_curwin = curwin;
347 term_T *term;
348 buf_T *old_curbuf = NULL;
349 int res;
350 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100351 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200352
353 if (check_restricted() || check_secure())
354 return NULL;
355
356 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
357 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
358 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
359 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
360 {
361 EMSG(_(e_invarg));
362 return NULL;
363 }
364
365 term = (term_T *)alloc_clear(sizeof(term_T));
366 if (term == NULL)
367 return NULL;
368 term->tl_dirty_row_end = MAX_ROW;
369 term->tl_cursor_visible = TRUE;
370 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
371 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100372#ifdef FEAT_GUI
373 term->tl_system = (flags & TERM_START_SYSTEM);
374#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200375 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
376
377 vim_memset(&split_ea, 0, sizeof(split_ea));
378 if (opt->jo_curwin)
379 {
380 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100381 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200382 {
383 no_write_message();
384 vim_free(term);
385 return NULL;
386 }
387 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100388 ECMD_HIDE
389 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
390 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200391 {
392 vim_free(term);
393 return NULL;
394 }
395 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100396 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 {
398 buf_T *buf;
399
400 /* Create a new buffer without a window. Make it the current buffer for
401 * a moment to be able to do the initialisations. */
402 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
403 BLN_NEW | BLN_LISTED);
404 if (buf == NULL || ml_open(buf) == FAIL)
405 {
406 vim_free(term);
407 return NULL;
408 }
409 old_curbuf = curbuf;
410 --curbuf->b_nwindows;
411 curbuf = buf;
412 curwin->w_buffer = buf;
413 ++curbuf->b_nwindows;
414 }
415 else
416 {
417 /* Open a new window or tab. */
418 split_ea.cmdidx = CMD_new;
419 split_ea.cmd = (char_u *)"new";
420 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100421 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200422 {
423 split_ea.line2 = opt->jo_term_rows;
424 split_ea.addr_count = 1;
425 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100426 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 {
428 split_ea.line2 = opt->jo_term_cols;
429 split_ea.addr_count = 1;
430 }
431
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100432 if (vertical)
433 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200434 ex_splitview(&split_ea);
435 if (curwin == old_curwin)
436 {
437 /* split failed */
438 vim_free(term);
439 return NULL;
440 }
441 }
442 term->tl_buffer = curbuf;
443 curbuf->b_term = term;
444
445 if (!opt->jo_hidden)
446 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100447 /* Only one size was taken care of with :new, do the other one. With
448 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100449 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100451 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200452 win_setwidth(opt->jo_term_cols);
453 }
454
455 /* Link the new terminal in the list of active terminals. */
456 term->tl_next = first_term;
457 first_term = term;
458
459 if (opt->jo_term_name != NULL)
460 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100461 else if (argv != NULL)
462 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 else
464 {
465 int i;
466 size_t len;
467 char_u *cmd, *p;
468
469 if (argvar->v_type == VAR_STRING)
470 {
471 cmd = argvar->vval.v_string;
472 if (cmd == NULL)
473 cmd = (char_u *)"";
474 else if (STRCMP(cmd, "NONE") == 0)
475 cmd = (char_u *)"pty";
476 }
477 else if (argvar->v_type != VAR_LIST
478 || argvar->vval.v_list == NULL
479 || argvar->vval.v_list->lv_len < 1
480 || (cmd = get_tv_string_chk(
481 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
482 cmd = (char_u*)"";
483
484 len = STRLEN(cmd) + 10;
485 p = alloc((int)len);
486
487 for (i = 0; p != NULL; ++i)
488 {
489 /* Prepend a ! to the command name to avoid the buffer name equals
490 * the executable, otherwise ":w!" would overwrite it. */
491 if (i == 0)
492 vim_snprintf((char *)p, len, "!%s", cmd);
493 else
494 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
495 if (buflist_findname(p) == NULL)
496 {
497 vim_free(curbuf->b_ffname);
498 curbuf->b_ffname = p;
499 break;
500 }
501 }
502 }
503 curbuf->b_fname = curbuf->b_ffname;
504
505 if (opt->jo_term_opencmd != NULL)
506 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
507
508 if (opt->jo_eof_chars != NULL)
509 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
510
511 set_string_option_direct((char_u *)"buftype", -1,
512 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
513
514 /* Mark the buffer as not modifiable. It can only be made modifiable after
515 * the job finished. */
516 curbuf->b_p_ma = FALSE;
517
518 set_term_and_win_size(term);
519 setup_job_options(opt, term->tl_rows, term->tl_cols);
520
Bram Moolenaar13568252018-03-16 20:46:58 +0100521 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100522 return curbuf;
523
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100524#if defined(FEAT_SESSION)
525 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100526 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100527 {
528 term->tl_command = vim_strsave((char_u *)"NONE");
529 }
530 else if (argvar->v_type == VAR_STRING)
531 {
532 char_u *cmd = argvar->vval.v_string;
533
534 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
535 term->tl_command = vim_strsave(cmd);
536 }
537 else if (argvar->v_type == VAR_LIST
538 && argvar->vval.v_list != NULL
539 && argvar->vval.v_list->lv_len > 0)
540 {
541 garray_T ga;
542 listitem_T *item;
543
544 ga_init2(&ga, 1, 100);
545 for (item = argvar->vval.v_list->lv_first;
546 item != NULL; item = item->li_next)
547 {
548 char_u *s = get_tv_string_chk(&item->li_tv);
549 char_u *p;
550
551 if (s == NULL)
552 break;
553 p = vim_strsave_fnameescape(s, FALSE);
554 if (p == NULL)
555 break;
556 ga_concat(&ga, p);
557 vim_free(p);
558 ga_append(&ga, ' ');
559 }
560 if (item == NULL)
561 {
562 ga_append(&ga, NUL);
563 term->tl_command = ga.ga_data;
564 }
565 else
566 ga_clear(&ga);
567 }
568#endif
569
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100570 if (opt->jo_term_kill != NULL)
571 {
572 char_u *p = skiptowhite(opt->jo_term_kill);
573
574 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
575 }
576
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200577 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100578 if (argv == NULL
579 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200580 && argvar->vval.v_string != NULL
581 && STRCMP(argvar->vval.v_string, "NONE") == 0)
582 res = create_pty_only(term, opt);
583 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100584 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200585
586 newbuf = curbuf;
587 if (res == OK)
588 {
589 /* Get and remember the size we ended up with. Update the pty. */
590 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
591 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100592#ifdef FEAT_GUI
593 if (term->tl_system)
594 {
595 /* display first line below typed command */
596 term->tl_toprow = msg_row + 1;
597 term->tl_dirty_row_end = 0;
598 }
599#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200600
601 /* Make sure we don't get stuck on sending keys to the job, it leads to
602 * a deadlock if the job is waiting for Vim to read. */
603 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
604
Bram Moolenaar13568252018-03-16 20:46:58 +0100605 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100606 {
607 ++curbuf->b_locked;
608 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
609 --curbuf->b_locked;
610 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100611 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612 {
613 --curbuf->b_nwindows;
614 curbuf = old_curbuf;
615 curwin->w_buffer = curbuf;
616 ++curbuf->b_nwindows;
617 }
618 }
619 else
620 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100621 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200622 return NULL;
623 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100624
Bram Moolenaar13568252018-03-16 20:46:58 +0100625 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200626 return newbuf;
627}
628
629/*
630 * ":terminal": open a terminal window and execute a job in it.
631 */
632 void
633ex_terminal(exarg_T *eap)
634{
635 typval_T argvar[2];
636 jobopt_T opt;
637 char_u *cmd;
638 char_u *tofree = NULL;
639
640 init_job_options(&opt);
641
642 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100643 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 {
645 char_u *p, *ep;
646
647 cmd += 2;
648 p = skiptowhite(cmd);
649 ep = vim_strchr(cmd, '=');
650 if (ep != NULL && ep < p)
651 p = ep;
652
653 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
654 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100655 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
656 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
658 opt.jo_term_finish = 'o';
659 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
660 opt.jo_curwin = 1;
661 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
662 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100663 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
664 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100665 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
666 && ep != NULL)
667 {
668 opt.jo_set2 |= JO2_TERM_KILL;
669 opt.jo_term_kill = ep + 1;
670 p = skiptowhite(cmd);
671 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200672 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
673 && ep != NULL && isdigit(ep[1]))
674 {
675 opt.jo_set2 |= JO2_TERM_ROWS;
676 opt.jo_term_rows = atoi((char *)ep + 1);
677 p = skiptowhite(cmd);
678 }
679 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
680 && ep != NULL && isdigit(ep[1]))
681 {
682 opt.jo_set2 |= JO2_TERM_COLS;
683 opt.jo_term_cols = atoi((char *)ep + 1);
684 p = skiptowhite(cmd);
685 }
686 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
687 && ep != NULL)
688 {
689 char_u *buf = NULL;
690 char_u *keys;
691
692 p = skiptowhite(cmd);
693 *p = NUL;
694 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
695 opt.jo_set2 |= JO2_EOF_CHARS;
696 opt.jo_eof_chars = vim_strsave(keys);
697 vim_free(buf);
698 *p = ' ';
699 }
700 else
701 {
702 if (*p)
703 *p = NUL;
704 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100705 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200706 }
707 cmd = skipwhite(p);
708 }
709 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100710 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 /* Make a copy of 'shell', an autocommand may change the option. */
712 tofree = cmd = vim_strsave(p_sh);
713
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100714 /* default to close when the shell exits */
715 if (opt.jo_term_finish == NUL)
716 opt.jo_term_finish = 'c';
717 }
718
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 if (eap->addr_count > 0)
720 {
721 /* Write lines from current buffer to the job. */
722 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
723 opt.jo_io[PART_IN] = JIO_BUFFER;
724 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
725 opt.jo_in_top = eap->line1;
726 opt.jo_in_bot = eap->line2;
727 }
728
729 argvar[0].v_type = VAR_STRING;
730 argvar[0].vval.v_string = cmd;
731 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100732 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100734
735theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 vim_free(opt.jo_eof_chars);
737}
738
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100739#if defined(FEAT_SESSION) || defined(PROTO)
740/*
741 * Write a :terminal command to the session file to restore the terminal in
742 * window "wp".
743 * Return FAIL if writing fails.
744 */
745 int
746term_write_session(FILE *fd, win_T *wp)
747{
748 term_T *term = wp->w_buffer->b_term;
749
750 /* Create the terminal and run the command. This is not without
751 * risk, but let's assume the user only creates a session when this
752 * will be OK. */
753 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
754 term->tl_cols, term->tl_rows) < 0)
755 return FAIL;
756 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
757 return FAIL;
758
759 return put_eol(fd);
760}
761
762/*
763 * Return TRUE if "buf" has a terminal that should be restored.
764 */
765 int
766term_should_restore(buf_T *buf)
767{
768 term_T *term = buf->b_term;
769
770 return term != NULL && (term->tl_command == NULL
771 || STRCMP(term->tl_command, "NONE") != 0);
772}
773#endif
774
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200775/*
776 * Free the scrollback buffer for "term".
777 */
778 static void
779free_scrollback(term_T *term)
780{
781 int i;
782
783 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
784 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
785 ga_clear(&term->tl_scrollback);
786}
787
788/*
789 * Free a terminal and everything it refers to.
790 * Kills the job if there is one.
791 * Called when wiping out a buffer.
792 */
793 void
794free_terminal(buf_T *buf)
795{
796 term_T *term = buf->b_term;
797 term_T *tp;
798
799 if (term == NULL)
800 return;
801 if (first_term == term)
802 first_term = term->tl_next;
803 else
804 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
805 if (tp->tl_next == term)
806 {
807 tp->tl_next = term->tl_next;
808 break;
809 }
810
811 if (term->tl_job != NULL)
812 {
813 if (term->tl_job->jv_status != JOB_ENDED
814 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100815 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 job_stop(term->tl_job, NULL, "kill");
817 job_unref(term->tl_job);
818 }
819
820 free_scrollback(term);
821
822 term_free_vterm(term);
823 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100824#ifdef FEAT_SESSION
825 vim_free(term->tl_command);
826#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100827 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 vim_free(term->tl_status_text);
829 vim_free(term->tl_opencmd);
830 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100831 if (desired_cursor_color == term->tl_cursor_color)
832 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 vim_free(term->tl_cursor_color);
834 vim_free(term);
835 buf->b_term = NULL;
836 if (in_terminal_loop == term)
837 in_terminal_loop = NULL;
838}
839
840/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100841 * Get the part that is connected to the tty. Normally this is PART_IN, but
842 * when writing buffer lines to the job it can be another. This makes it
843 * possible to do "1,5term vim -".
844 */
845 static ch_part_T
846get_tty_part(term_T *term)
847{
848#ifdef UNIX
849 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
850 int i;
851
852 for (i = 0; i < 3; ++i)
853 {
854 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
855
856 if (isatty(fd))
857 return parts[i];
858 }
859#endif
860 return PART_IN;
861}
862
863/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864 * Write job output "msg[len]" to the vterm.
865 */
866 static void
867term_write_job_output(term_T *term, char_u *msg, size_t len)
868{
869 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100870 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200871
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100872 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200873
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100874 /* flush vterm buffer when vterm responded to control sequence */
875 if (prevlen != vterm_output_get_buffer_current(vterm))
876 {
877 char buf[KEY_BUF_LEN];
878 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
879
880 if (curlen > 0)
881 channel_send(term->tl_job->jv_channel, get_tty_part(term),
882 (char_u *)buf, (int)curlen, NULL);
883 }
884
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200885 /* this invokes the damage callbacks */
886 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
887}
888
889 static void
890update_cursor(term_T *term, int redraw)
891{
892 if (term->tl_normal_mode)
893 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100894#ifdef FEAT_GUI
895 if (term->tl_system)
896 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
897 term->tl_cursor_pos.col);
898 else
899#endif
900 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901 if (redraw)
902 {
903 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
904 cursor_on();
905 out_flush();
906#ifdef FEAT_GUI
907 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100908 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200909 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100910 gui_mch_flush();
911 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200912#endif
913 }
914}
915
916/*
917 * Invoked when "msg" output from a job was received. Write it to the terminal
918 * of "buffer".
919 */
920 void
921write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
922{
923 size_t len = STRLEN(msg);
924 term_T *term = buffer->b_term;
925
926 if (term->tl_vterm == NULL)
927 {
928 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
929 return;
930 }
931 ch_log(channel, "writing %d bytes to terminal", (int)len);
932 term_write_job_output(term, msg, len);
933
Bram Moolenaar13568252018-03-16 20:46:58 +0100934#ifdef FEAT_GUI
935 if (term->tl_system)
936 {
937 /* show system output, scrolling up the screen as needed */
938 update_system_term(term);
939 update_cursor(term, TRUE);
940 }
941 else
942#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200943 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
944 * contents, thus no screen update is needed. */
945 if (!term->tl_normal_mode)
946 {
947 /* TODO: only update once in a while. */
948 ch_log(term->tl_job->jv_channel, "updating screen");
949 if (buffer == curbuf)
950 {
951 update_screen(0);
952 update_cursor(term, TRUE);
953 }
954 else
955 redraw_after_callback(TRUE);
956 }
957}
958
959/*
960 * Send a mouse position and click to the vterm
961 */
962 static int
963term_send_mouse(VTerm *vterm, int button, int pressed)
964{
965 VTermModifier mod = VTERM_MOD_NONE;
966
967 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200968 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100969 if (button != 0)
970 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 return TRUE;
972}
973
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100974static int enter_mouse_col = -1;
975static int enter_mouse_row = -1;
976
977/*
978 * Handle a mouse click, drag or release.
979 * Return TRUE when a mouse event is sent to the terminal.
980 */
981 static int
982term_mouse_click(VTerm *vterm, int key)
983{
984#if defined(FEAT_CLIPBOARD)
985 /* For modeless selection mouse drag and release events are ignored, unless
986 * they are preceded with a mouse down event */
987 static int ignore_drag_release = TRUE;
988 VTermMouseState mouse_state;
989
990 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
991 if (mouse_state.flags == 0)
992 {
993 /* Terminal is not using the mouse, use modeless selection. */
994 switch (key)
995 {
996 case K_LEFTDRAG:
997 case K_LEFTRELEASE:
998 case K_RIGHTDRAG:
999 case K_RIGHTRELEASE:
1000 /* Ignore drag and release events when the button-down wasn't
1001 * seen before. */
1002 if (ignore_drag_release)
1003 {
1004 int save_mouse_col, save_mouse_row;
1005
1006 if (enter_mouse_col < 0)
1007 break;
1008
1009 /* mouse click in the window gave us focus, handle that
1010 * click now */
1011 save_mouse_col = mouse_col;
1012 save_mouse_row = mouse_row;
1013 mouse_col = enter_mouse_col;
1014 mouse_row = enter_mouse_row;
1015 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1016 mouse_col = save_mouse_col;
1017 mouse_row = save_mouse_row;
1018 }
1019 /* FALLTHROUGH */
1020 case K_LEFTMOUSE:
1021 case K_RIGHTMOUSE:
1022 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1023 ignore_drag_release = TRUE;
1024 else
1025 ignore_drag_release = FALSE;
1026 /* Should we call mouse_has() here? */
1027 if (clip_star.available)
1028 {
1029 int button, is_click, is_drag;
1030
1031 button = get_mouse_button(KEY2TERMCAP1(key),
1032 &is_click, &is_drag);
1033 if (mouse_model_popup() && button == MOUSE_LEFT
1034 && (mod_mask & MOD_MASK_SHIFT))
1035 {
1036 /* Translate shift-left to right button. */
1037 button = MOUSE_RIGHT;
1038 mod_mask &= ~MOD_MASK_SHIFT;
1039 }
1040 clip_modeless(button, is_click, is_drag);
1041 }
1042 break;
1043
1044 case K_MIDDLEMOUSE:
1045 if (clip_star.available)
1046 insert_reg('*', TRUE);
1047 break;
1048 }
1049 enter_mouse_col = -1;
1050 return FALSE;
1051 }
1052#endif
1053 enter_mouse_col = -1;
1054
1055 switch (key)
1056 {
1057 case K_LEFTMOUSE:
1058 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1059 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1060 case K_LEFTRELEASE:
1061 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1062 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1063 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1064 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1065 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1066 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1067 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1068 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1069 }
1070 return TRUE;
1071}
1072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001073/*
1074 * Convert typed key "c" into bytes to send to the job.
1075 * Return the number of bytes in "buf".
1076 */
1077 static int
1078term_convert_key(term_T *term, int c, char *buf)
1079{
1080 VTerm *vterm = term->tl_vterm;
1081 VTermKey key = VTERM_KEY_NONE;
1082 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001083 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001084
1085 switch (c)
1086 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001087 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1088
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001089 /* don't use VTERM_KEY_BACKSPACE, it always
1090 * becomes 0x7f DEL */
1091 case K_BS: c = term_backspace_char; break;
1092
1093 case ESC: key = VTERM_KEY_ESCAPE; break;
1094 case K_DEL: key = VTERM_KEY_DEL; break;
1095 case K_DOWN: key = VTERM_KEY_DOWN; break;
1096 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1097 key = VTERM_KEY_DOWN; break;
1098 case K_END: key = VTERM_KEY_END; break;
1099 case K_S_END: mod = VTERM_MOD_SHIFT;
1100 key = VTERM_KEY_END; break;
1101 case K_C_END: mod = VTERM_MOD_CTRL;
1102 key = VTERM_KEY_END; break;
1103 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1104 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1105 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1106 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1107 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1108 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1109 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1110 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1111 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1112 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1113 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1114 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1115 case K_HOME: key = VTERM_KEY_HOME; break;
1116 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1117 key = VTERM_KEY_HOME; break;
1118 case K_C_HOME: mod = VTERM_MOD_CTRL;
1119 key = VTERM_KEY_HOME; break;
1120 case K_INS: key = VTERM_KEY_INS; break;
1121 case K_K0: key = VTERM_KEY_KP_0; break;
1122 case K_K1: key = VTERM_KEY_KP_1; break;
1123 case K_K2: key = VTERM_KEY_KP_2; break;
1124 case K_K3: key = VTERM_KEY_KP_3; break;
1125 case K_K4: key = VTERM_KEY_KP_4; break;
1126 case K_K5: key = VTERM_KEY_KP_5; break;
1127 case K_K6: key = VTERM_KEY_KP_6; break;
1128 case K_K7: key = VTERM_KEY_KP_7; break;
1129 case K_K8: key = VTERM_KEY_KP_8; break;
1130 case K_K9: key = VTERM_KEY_KP_9; break;
1131 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1132 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1133 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1134 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1135 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1136 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1137 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1138 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1139 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1140 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1141 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1142 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1143 case K_LEFT: key = VTERM_KEY_LEFT; break;
1144 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1145 key = VTERM_KEY_LEFT; break;
1146 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1147 key = VTERM_KEY_LEFT; break;
1148 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1149 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1150 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1151 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1152 key = VTERM_KEY_RIGHT; break;
1153 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1154 key = VTERM_KEY_RIGHT; break;
1155 case K_UP: key = VTERM_KEY_UP; break;
1156 case K_S_UP: mod = VTERM_MOD_SHIFT;
1157 key = VTERM_KEY_UP; break;
1158 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001159 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1160 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001161
Bram Moolenaara42ad572017-11-16 13:08:04 +01001162 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1163 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001164 case K_MOUSELEFT: /* TODO */ return 0;
1165 case K_MOUSERIGHT: /* TODO */ return 0;
1166
1167 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001168 case K_LEFTMOUSE_NM:
1169 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001170 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001171 case K_LEFTRELEASE_NM:
1172 case K_MOUSEMOVE:
1173 case K_MIDDLEMOUSE:
1174 case K_MIDDLEDRAG:
1175 case K_MIDDLERELEASE:
1176 case K_RIGHTMOUSE:
1177 case K_RIGHTDRAG:
1178 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1179 return 0;
1180 other = TRUE;
1181 break;
1182
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001183 case K_X1MOUSE: /* TODO */ return 0;
1184 case K_X1DRAG: /* TODO */ return 0;
1185 case K_X1RELEASE: /* TODO */ return 0;
1186 case K_X2MOUSE: /* TODO */ return 0;
1187 case K_X2DRAG: /* TODO */ return 0;
1188 case K_X2RELEASE: /* TODO */ return 0;
1189
1190 case K_IGNORE: return 0;
1191 case K_NOP: return 0;
1192 case K_UNDO: return 0;
1193 case K_HELP: return 0;
1194 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1195 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1196 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1197 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1198 case K_SELECT: return 0;
1199#ifdef FEAT_GUI
1200 case K_VER_SCROLLBAR: return 0;
1201 case K_HOR_SCROLLBAR: return 0;
1202#endif
1203#ifdef FEAT_GUI_TABLINE
1204 case K_TABLINE: return 0;
1205 case K_TABMENU: return 0;
1206#endif
1207#ifdef FEAT_NETBEANS_INTG
1208 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1209#endif
1210#ifdef FEAT_DND
1211 case K_DROP: return 0;
1212#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001213 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001214 case K_PS: vterm_keyboard_start_paste(vterm);
1215 other = TRUE;
1216 break;
1217 case K_PE: vterm_keyboard_end_paste(vterm);
1218 other = TRUE;
1219 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001220 }
1221
1222 /*
1223 * Convert special keys to vterm keys:
1224 * - Write keys to vterm: vterm_keyboard_key()
1225 * - Write output to channel.
1226 * TODO: use mod_mask
1227 */
1228 if (key != VTERM_KEY_NONE)
1229 /* Special key, let vterm convert it. */
1230 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001231 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001232 /* Normal character, let vterm convert it. */
1233 vterm_keyboard_unichar(vterm, c, mod);
1234
1235 /* Read back the converted escape sequence. */
1236 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1237}
1238
1239/*
1240 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001241 * If "check_job_status" is TRUE update the job status.
1242 */
1243 static int
1244term_job_running_check(term_T *term, int check_job_status)
1245{
1246 /* Also consider the job finished when the channel is closed, to avoid a
1247 * race condition when updating the title. */
1248 if (term != NULL
1249 && term->tl_job != NULL
1250 && channel_is_open(term->tl_job->jv_channel))
1251 {
1252 if (check_job_status)
1253 job_status(term->tl_job);
1254 return (term->tl_job->jv_status == JOB_STARTED
1255 || term->tl_job->jv_channel->ch_keep_open);
1256 }
1257 return FALSE;
1258}
1259
1260/*
1261 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001262 */
1263 int
1264term_job_running(term_T *term)
1265{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001266 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001267}
1268
1269/*
1270 * Return TRUE if "term" has an active channel and used ":term NONE".
1271 */
1272 int
1273term_none_open(term_T *term)
1274{
1275 /* Also consider the job finished when the channel is closed, to avoid a
1276 * race condition when updating the title. */
1277 return term != NULL
1278 && term->tl_job != NULL
1279 && channel_is_open(term->tl_job->jv_channel)
1280 && term->tl_job->jv_channel->ch_keep_open;
1281}
1282
1283/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001284 * Used when exiting: kill the job in "buf" if so desired.
1285 * Return OK when the job finished.
1286 * Return FAIL when the job is still running.
1287 */
1288 int
1289term_try_stop_job(buf_T *buf)
1290{
1291 int count;
1292 char *how = (char *)buf->b_term->tl_kill;
1293
1294#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1295 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1296 {
1297 char_u buff[DIALOG_MSG_SIZE];
1298 int ret;
1299
1300 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1301 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1302 if (ret == VIM_YES)
1303 how = "kill";
1304 else if (ret == VIM_CANCEL)
1305 return FAIL;
1306 }
1307#endif
1308 if (how == NULL || *how == NUL)
1309 return FAIL;
1310
1311 job_stop(buf->b_term->tl_job, NULL, how);
1312
1313 /* wait for up to a second for the job to die */
1314 for (count = 0; count < 100; ++count)
1315 {
1316 /* buffer, terminal and job may be cleaned up while waiting */
1317 if (!buf_valid(buf)
1318 || buf->b_term == NULL
1319 || buf->b_term->tl_job == NULL)
1320 return OK;
1321
1322 /* call job_status() to update jv_status */
1323 job_status(buf->b_term->tl_job);
1324 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1325 return OK;
1326 ui_delay(10L, FALSE);
1327 mch_check_messages();
1328 parse_queued_messages();
1329 }
1330 return FAIL;
1331}
1332
1333/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001334 * Add the last line of the scrollback buffer to the buffer in the window.
1335 */
1336 static void
1337add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1338{
1339 buf_T *buf = term->tl_buffer;
1340 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1341 linenr_T lnum = buf->b_ml.ml_line_count;
1342
1343#ifdef WIN3264
1344 if (!enc_utf8 && enc_codepage > 0)
1345 {
1346 WCHAR *ret = NULL;
1347 int length = 0;
1348
1349 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1350 &ret, &length);
1351 if (ret != NULL)
1352 {
1353 WideCharToMultiByte_alloc(enc_codepage, 0,
1354 ret, length, (char **)&text, &len, 0, 0);
1355 vim_free(ret);
1356 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1357 vim_free(text);
1358 }
1359 }
1360 else
1361#endif
1362 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1363 if (empty)
1364 {
1365 /* Delete the empty line that was in the empty buffer. */
1366 curbuf = buf;
1367 ml_delete(1, FALSE);
1368 curbuf = curwin->w_buffer;
1369 }
1370}
1371
1372 static void
1373cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1374{
1375 attr->width = cell->width;
1376 attr->attrs = cell->attrs;
1377 attr->fg = cell->fg;
1378 attr->bg = cell->bg;
1379}
1380
1381 static int
1382equal_celattr(cellattr_T *a, cellattr_T *b)
1383{
1384 /* Comparing the colors should be sufficient. */
1385 return a->fg.red == b->fg.red
1386 && a->fg.green == b->fg.green
1387 && a->fg.blue == b->fg.blue
1388 && a->bg.red == b->bg.red
1389 && a->bg.green == b->bg.green
1390 && a->bg.blue == b->bg.blue;
1391}
1392
Bram Moolenaard96ff162018-02-18 22:13:29 +01001393/*
1394 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1395 * line at this position. Otherwise at the end.
1396 */
1397 static int
1398add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1399{
1400 if (ga_grow(&term->tl_scrollback, 1) == OK)
1401 {
1402 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1403 + term->tl_scrollback.ga_len;
1404
1405 if (lnum > 0)
1406 {
1407 int i;
1408
1409 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1410 {
1411 *line = *(line - 1);
1412 --line;
1413 }
1414 }
1415 line->sb_cols = 0;
1416 line->sb_cells = NULL;
1417 line->sb_fill_attr = *fill_attr;
1418 ++term->tl_scrollback.ga_len;
1419 return OK;
1420 }
1421 return FALSE;
1422}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001423
1424/*
1425 * Add the current lines of the terminal to scrollback and to the buffer.
1426 * Called after the job has ended and when switching to Terminal-Normal mode.
1427 */
1428 static void
1429move_terminal_to_buffer(term_T *term)
1430{
1431 win_T *wp;
1432 int len;
1433 int lines_skipped = 0;
1434 VTermPos pos;
1435 VTermScreenCell cell;
1436 cellattr_T fill_attr, new_fill_attr;
1437 cellattr_T *p;
1438 VTermScreen *screen;
1439
1440 if (term->tl_vterm == NULL)
1441 return;
1442 screen = vterm_obtain_screen(term->tl_vterm);
1443 fill_attr = new_fill_attr = term->tl_default_color;
1444
1445 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1446 {
1447 len = 0;
1448 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1449 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1450 && cell.chars[0] != NUL)
1451 {
1452 len = pos.col + 1;
1453 new_fill_attr = term->tl_default_color;
1454 }
1455 else
1456 /* Assume the last attr is the filler attr. */
1457 cell2cellattr(&cell, &new_fill_attr);
1458
1459 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1460 ++lines_skipped;
1461 else
1462 {
1463 while (lines_skipped > 0)
1464 {
1465 /* Line was skipped, add an empty line. */
1466 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001467 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001468 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001469 }
1470
1471 if (len == 0)
1472 p = NULL;
1473 else
1474 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1475 if ((p != NULL || len == 0)
1476 && ga_grow(&term->tl_scrollback, 1) == OK)
1477 {
1478 garray_T ga;
1479 int width;
1480 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1481 + term->tl_scrollback.ga_len;
1482
1483 ga_init2(&ga, 1, 100);
1484 for (pos.col = 0; pos.col < len; pos.col += width)
1485 {
1486 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1487 {
1488 width = 1;
1489 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1490 if (ga_grow(&ga, 1) == OK)
1491 ga.ga_len += utf_char2bytes(' ',
1492 (char_u *)ga.ga_data + ga.ga_len);
1493 }
1494 else
1495 {
1496 width = cell.width;
1497
1498 cell2cellattr(&cell, &p[pos.col]);
1499
1500 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1501 {
1502 int i;
1503 int c;
1504
1505 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1506 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1507 (char_u *)ga.ga_data + ga.ga_len);
1508 }
1509 }
1510 }
1511 line->sb_cols = len;
1512 line->sb_cells = p;
1513 line->sb_fill_attr = new_fill_attr;
1514 fill_attr = new_fill_attr;
1515 ++term->tl_scrollback.ga_len;
1516
1517 if (ga_grow(&ga, 1) == FAIL)
1518 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1519 else
1520 {
1521 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1522 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1523 }
1524 ga_clear(&ga);
1525 }
1526 else
1527 vim_free(p);
1528 }
1529 }
1530
1531 /* Obtain the current background color. */
1532 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1533 &term->tl_default_color.fg, &term->tl_default_color.bg);
1534
1535 FOR_ALL_WINDOWS(wp)
1536 {
1537 if (wp->w_buffer == term->tl_buffer)
1538 {
1539 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1540 wp->w_cursor.col = 0;
1541 wp->w_valid = 0;
1542 if (wp->w_cursor.lnum >= wp->w_height)
1543 {
1544 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1545
1546 if (wp->w_topline < min_topline)
1547 wp->w_topline = min_topline;
1548 }
1549 redraw_win_later(wp, NOT_VALID);
1550 }
1551 }
1552}
1553
1554 static void
1555set_terminal_mode(term_T *term, int normal_mode)
1556{
1557 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001558 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001559 if (term->tl_buffer == curbuf)
1560 maketitle();
1561}
1562
1563/*
1564 * Called after the job if finished and Terminal mode is not active:
1565 * Move the vterm contents into the scrollback buffer and free the vterm.
1566 */
1567 static void
1568cleanup_vterm(term_T *term)
1569{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001570 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001571 move_terminal_to_buffer(term);
1572 term_free_vterm(term);
1573 set_terminal_mode(term, FALSE);
1574}
1575
1576/*
1577 * Switch from Terminal-Job mode to Terminal-Normal mode.
1578 * Suspends updating the terminal window.
1579 */
1580 static void
1581term_enter_normal_mode(void)
1582{
1583 term_T *term = curbuf->b_term;
1584
1585 /* Append the current terminal contents to the buffer. */
1586 move_terminal_to_buffer(term);
1587
1588 set_terminal_mode(term, TRUE);
1589
1590 /* Move the window cursor to the position of the cursor in the
1591 * terminal. */
1592 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1593 + term->tl_cursor_pos.row + 1;
1594 check_cursor();
1595 coladvance(term->tl_cursor_pos.col);
1596
1597 /* Display the same lines as in the terminal. */
1598 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1599}
1600
1601/*
1602 * Returns TRUE if the current window contains a terminal and we are in
1603 * Terminal-Normal mode.
1604 */
1605 int
1606term_in_normal_mode(void)
1607{
1608 term_T *term = curbuf->b_term;
1609
1610 return term != NULL && term->tl_normal_mode;
1611}
1612
1613/*
1614 * Switch from Terminal-Normal mode to Terminal-Job mode.
1615 * Restores updating the terminal window.
1616 */
1617 void
1618term_enter_job_mode()
1619{
1620 term_T *term = curbuf->b_term;
1621 sb_line_T *line;
1622 garray_T *gap;
1623
1624 /* Remove the terminal contents from the scrollback and the buffer. */
1625 gap = &term->tl_scrollback;
1626 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1627 && gap->ga_len > 0)
1628 {
1629 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1630 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1631 vim_free(line->sb_cells);
1632 --gap->ga_len;
1633 }
1634 check_cursor();
1635
1636 set_terminal_mode(term, FALSE);
1637
1638 if (term->tl_channel_closed)
1639 cleanup_vterm(term);
1640 redraw_buf_and_status_later(curbuf, NOT_VALID);
1641}
1642
1643/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001644 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001645 * Note: while waiting a terminal may be closed and freed if the channel is
1646 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001647 */
1648 static int
1649term_vgetc()
1650{
1651 int c;
1652 int save_State = State;
1653
1654 State = TERMINAL;
1655 got_int = FALSE;
1656#ifdef WIN3264
1657 ctrl_break_was_pressed = FALSE;
1658#endif
1659 c = vgetc();
1660 got_int = FALSE;
1661 State = save_State;
1662 return c;
1663}
1664
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001665static int mouse_was_outside = FALSE;
1666
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001668 * Send keys to terminal.
1669 * Return FAIL when the key needs to be handled in Normal mode.
1670 * Return OK when the key was dropped or sent to the terminal.
1671 */
1672 int
1673send_keys_to_term(term_T *term, int c, int typed)
1674{
1675 char msg[KEY_BUF_LEN];
1676 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001677 int dragging_outside = FALSE;
1678
1679 /* Catch keys that need to be handled as in Normal mode. */
1680 switch (c)
1681 {
1682 case NUL:
1683 case K_ZERO:
1684 if (typed)
1685 stuffcharReadbuff(c);
1686 return FAIL;
1687
1688 case K_IGNORE:
1689 return FAIL;
1690
1691 case K_LEFTDRAG:
1692 case K_MIDDLEDRAG:
1693 case K_RIGHTDRAG:
1694 case K_X1DRAG:
1695 case K_X2DRAG:
1696 dragging_outside = mouse_was_outside;
1697 /* FALLTHROUGH */
1698 case K_LEFTMOUSE:
1699 case K_LEFTMOUSE_NM:
1700 case K_LEFTRELEASE:
1701 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001702 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 case K_MIDDLEMOUSE:
1704 case K_MIDDLERELEASE:
1705 case K_RIGHTMOUSE:
1706 case K_RIGHTRELEASE:
1707 case K_X1MOUSE:
1708 case K_X1RELEASE:
1709 case K_X2MOUSE:
1710 case K_X2RELEASE:
1711
1712 case K_MOUSEUP:
1713 case K_MOUSEDOWN:
1714 case K_MOUSELEFT:
1715 case K_MOUSERIGHT:
1716 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001717 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001718 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001719 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001720 || dragging_outside)
1721 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001722 /* click or scroll outside the current window or on status line
1723 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001724 if (typed)
1725 {
1726 stuffcharReadbuff(c);
1727 mouse_was_outside = TRUE;
1728 }
1729 return FAIL;
1730 }
1731 }
1732 if (typed)
1733 mouse_was_outside = FALSE;
1734
1735 /* Convert the typed key to a sequence of bytes for the job. */
1736 len = term_convert_key(term, c, msg);
1737 if (len > 0)
1738 /* TODO: if FAIL is returned, stop? */
1739 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1740 (char_u *)msg, (int)len, NULL);
1741
1742 return OK;
1743}
1744
1745 static void
1746position_cursor(win_T *wp, VTermPos *pos)
1747{
1748 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1749 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1750 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1751}
1752
1753/*
1754 * Handle CTRL-W "": send register contents to the job.
1755 */
1756 static void
1757term_paste_register(int prev_c UNUSED)
1758{
1759 int c;
1760 list_T *l;
1761 listitem_T *item;
1762 long reglen = 0;
1763 int type;
1764
1765#ifdef FEAT_CMDL_INFO
1766 if (add_to_showcmd(prev_c))
1767 if (add_to_showcmd('"'))
1768 out_flush();
1769#endif
1770 c = term_vgetc();
1771#ifdef FEAT_CMDL_INFO
1772 clear_showcmd();
1773#endif
1774 if (!term_use_loop())
1775 /* job finished while waiting for a character */
1776 return;
1777
1778 /* CTRL-W "= prompt for expression to evaluate. */
1779 if (c == '=' && get_expr_register() != '=')
1780 return;
1781 if (!term_use_loop())
1782 /* job finished while waiting for a character */
1783 return;
1784
1785 l = (list_T *)get_reg_contents(c, GREG_LIST);
1786 if (l != NULL)
1787 {
1788 type = get_reg_type(c, &reglen);
1789 for (item = l->lv_first; item != NULL; item = item->li_next)
1790 {
1791 char_u *s = get_tv_string(&item->li_tv);
1792#ifdef WIN3264
1793 char_u *tmp = s;
1794
1795 if (!enc_utf8 && enc_codepage > 0)
1796 {
1797 WCHAR *ret = NULL;
1798 int length = 0;
1799
1800 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1801 (int)STRLEN(s), &ret, &length);
1802 if (ret != NULL)
1803 {
1804 WideCharToMultiByte_alloc(CP_UTF8, 0,
1805 ret, length, (char **)&s, &length, 0, 0);
1806 vim_free(ret);
1807 }
1808 }
1809#endif
1810 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1811 s, (int)STRLEN(s), NULL);
1812#ifdef WIN3264
1813 if (tmp != s)
1814 vim_free(s);
1815#endif
1816
1817 if (item->li_next != NULL || type == MLINE)
1818 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1819 (char_u *)"\r", 1, NULL);
1820 }
1821 list_free(l);
1822 }
1823}
1824
1825#if defined(FEAT_GUI) || defined(PROTO)
1826/*
1827 * Return TRUE when the cursor of the terminal should be displayed.
1828 */
1829 int
1830terminal_is_active()
1831{
1832 return in_terminal_loop != NULL;
1833}
1834
1835 cursorentry_T *
1836term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1837{
1838 term_T *term = in_terminal_loop;
1839 static cursorentry_T entry;
1840
1841 vim_memset(&entry, 0, sizeof(entry));
1842 entry.shape = entry.mshape =
1843 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1844 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1845 SHAPE_BLOCK;
1846 entry.percentage = 20;
1847 if (term->tl_cursor_blink)
1848 {
1849 entry.blinkwait = 700;
1850 entry.blinkon = 400;
1851 entry.blinkoff = 250;
1852 }
1853 *fg = gui.back_pixel;
1854 if (term->tl_cursor_color == NULL)
1855 *bg = gui.norm_pixel;
1856 else
1857 *bg = color_name2handle(term->tl_cursor_color);
1858 entry.name = "n";
1859 entry.used_for = SHAPE_CURSOR;
1860
1861 return &entry;
1862}
1863#endif
1864
Bram Moolenaard317b382018-02-08 22:33:31 +01001865 static void
1866may_output_cursor_props(void)
1867{
1868 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1869 || last_set_cursor_shape != desired_cursor_shape
1870 || last_set_cursor_blink != desired_cursor_blink)
1871 {
1872 last_set_cursor_color = desired_cursor_color;
1873 last_set_cursor_shape = desired_cursor_shape;
1874 last_set_cursor_blink = desired_cursor_blink;
1875 term_cursor_color(desired_cursor_color);
1876 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1877 /* this will restore the initial cursor style, if possible */
1878 ui_cursor_shape_forced(TRUE);
1879 else
1880 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1881 }
1882}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883
Bram Moolenaard317b382018-02-08 22:33:31 +01001884/*
1885 * Set the cursor color and shape, if not last set to these.
1886 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887 static void
1888may_set_cursor_props(term_T *term)
1889{
1890#ifdef FEAT_GUI
1891 /* For the GUI the cursor properties are obtained with
1892 * term_get_cursor_shape(). */
1893 if (gui.in_use)
1894 return;
1895#endif
1896 if (in_terminal_loop == term)
1897 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001899 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001900 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001901 desired_cursor_color = (char_u *)"";
1902 desired_cursor_shape = term->tl_cursor_shape;
1903 desired_cursor_blink = term->tl_cursor_blink;
1904 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001905 }
1906}
1907
Bram Moolenaard317b382018-02-08 22:33:31 +01001908/*
1909 * Reset the desired cursor properties and restore them when needed.
1910 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001911 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001912prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001913{
1914#ifdef FEAT_GUI
1915 if (gui.in_use)
1916 return;
1917#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001918 desired_cursor_color = (char_u *)"";
1919 desired_cursor_shape = -1;
1920 desired_cursor_blink = -1;
1921 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001922}
1923
1924/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001925 * Returns TRUE if the current window contains a terminal and we are sending
1926 * keys to the job.
1927 * If "check_job_status" is TRUE update the job status.
1928 */
1929 static int
1930term_use_loop_check(int check_job_status)
1931{
1932 term_T *term = curbuf->b_term;
1933
1934 return term != NULL
1935 && !term->tl_normal_mode
1936 && term->tl_vterm != NULL
1937 && term_job_running_check(term, check_job_status);
1938}
1939
1940/*
1941 * Returns TRUE if the current window contains a terminal and we are sending
1942 * keys to the job.
1943 */
1944 int
1945term_use_loop(void)
1946{
1947 return term_use_loop_check(FALSE);
1948}
1949
1950/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001951 * Called when entering a window with the mouse. If this is a terminal window
1952 * we may want to change state.
1953 */
1954 void
1955term_win_entered()
1956{
1957 term_T *term = curbuf->b_term;
1958
1959 if (term != NULL)
1960 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001961 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001962 {
1963 reset_VIsual_and_resel();
1964 if (State & INSERT)
1965 stop_insert_mode = TRUE;
1966 }
1967 mouse_was_outside = FALSE;
1968 enter_mouse_col = mouse_col;
1969 enter_mouse_row = mouse_row;
1970 }
1971}
1972
1973/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001974 * Wait for input and send it to the job.
1975 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1976 * when there is no more typahead.
1977 * Return when the start of a CTRL-W command is typed or anything else that
1978 * should be handled as a Normal mode command.
1979 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1980 * the terminal was closed.
1981 */
1982 int
1983terminal_loop(int blocking)
1984{
1985 int c;
1986 int termkey = 0;
1987 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001988#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001989 int tty_fd = curbuf->b_term->tl_job->jv_channel
1990 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001991#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001992 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993
1994 /* Remember the terminal we are sending keys to. However, the terminal
1995 * might be closed while waiting for a character, e.g. typing "exit" in a
1996 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1997 * stored reference. */
1998 in_terminal_loop = curbuf->b_term;
1999
2000 if (*curwin->w_p_tk != NUL)
2001 termkey = string_to_key(curwin->w_p_tk, TRUE);
2002 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2003 may_set_cursor_props(curbuf->b_term);
2004
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002005 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002007#ifdef FEAT_GUI
2008 if (!curbuf->b_term->tl_system)
2009#endif
2010 /* TODO: skip screen update when handling a sequence of keys. */
2011 /* Repeat redrawing in case a message is received while redrawing.
2012 */
2013 while (must_redraw != 0)
2014 if (update_screen(0) == FAIL)
2015 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002017 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002018
2019 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002020 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002021 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002022 /* Job finished while waiting for a character. Push back the
2023 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002024 if (c != K_IGNORE)
2025 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002027 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 if (c == K_IGNORE)
2029 continue;
2030
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002031#ifdef UNIX
2032 /*
2033 * The shell or another program may change the tty settings. Getting
2034 * them for every typed character is a bit of overhead, but it's needed
2035 * for the first character typed, e.g. when Vim starts in a shell.
2036 */
2037 if (isatty(tty_fd))
2038 {
2039 ttyinfo_T info;
2040
2041 /* Get the current backspace character of the pty. */
2042 if (get_tty_info(tty_fd, &info) == OK)
2043 term_backspace_char = info.backspace;
2044 }
2045#endif
2046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047#ifdef WIN3264
2048 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2049 * Use CTRL-BREAK to kill the job. */
2050 if (ctrl_break_was_pressed)
2051 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2052#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002053 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2054 * Not in a system terminal. */
2055 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2056#ifdef FEAT_GUI
2057 && !curbuf->b_term->tl_system
2058#endif
2059 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002060 {
2061 int prev_c = c;
2062
2063#ifdef FEAT_CMDL_INFO
2064 if (add_to_showcmd(c))
2065 out_flush();
2066#endif
2067 c = term_vgetc();
2068#ifdef FEAT_CMDL_INFO
2069 clear_showcmd();
2070#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002071 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002072 /* job finished while waiting for a character */
2073 break;
2074
2075 if (prev_c == Ctrl_BSL)
2076 {
2077 if (c == Ctrl_N)
2078 {
2079 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2080 term_enter_normal_mode();
2081 ret = FAIL;
2082 goto theend;
2083 }
2084 /* Send both keys to the terminal. */
2085 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2086 }
2087 else if (c == Ctrl_C)
2088 {
2089 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2090 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2091 }
2092 else if (termkey == 0 && c == '.')
2093 {
2094 /* "CTRL-W .": send CTRL-W to the job */
2095 c = Ctrl_W;
2096 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002097 else if (termkey == 0 && c == Ctrl_BSL)
2098 {
2099 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2100 c = Ctrl_BSL;
2101 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 else if (c == 'N')
2103 {
2104 /* CTRL-W N : go to Terminal-Normal mode. */
2105 term_enter_normal_mode();
2106 ret = FAIL;
2107 goto theend;
2108 }
2109 else if (c == '"')
2110 {
2111 term_paste_register(prev_c);
2112 continue;
2113 }
2114 else if (termkey == 0 || c != termkey)
2115 {
2116 stuffcharReadbuff(Ctrl_W);
2117 stuffcharReadbuff(c);
2118 ret = OK;
2119 goto theend;
2120 }
2121 }
2122# ifdef WIN3264
2123 if (!enc_utf8 && has_mbyte && c >= 0x80)
2124 {
2125 WCHAR wc;
2126 char_u mb[3];
2127
2128 mb[0] = (unsigned)c >> 8;
2129 mb[1] = c;
2130 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2131 c = wc;
2132 }
2133# endif
2134 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2135 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002136 if (c == K_MOUSEMOVE)
2137 /* We are sure to come back here, don't reset the cursor color
2138 * and shape to avoid flickering. */
2139 restore_cursor = FALSE;
2140
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 ret = OK;
2142 goto theend;
2143 }
2144 }
2145 ret = FAIL;
2146
2147theend:
2148 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002149 if (restore_cursor)
2150 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002151 return ret;
2152}
2153
2154/*
2155 * Called when a job has finished.
2156 * This updates the title and status, but does not close the vterm, because
2157 * there might still be pending output in the channel.
2158 */
2159 void
2160term_job_ended(job_T *job)
2161{
2162 term_T *term;
2163 int did_one = FALSE;
2164
2165 for (term = first_term; term != NULL; term = term->tl_next)
2166 if (term->tl_job == job)
2167 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002168 VIM_CLEAR(term->tl_title);
2169 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002170 redraw_buf_and_status_later(term->tl_buffer, VALID);
2171 did_one = TRUE;
2172 }
2173 if (did_one)
2174 redraw_statuslines();
2175 if (curbuf->b_term != NULL)
2176 {
2177 if (curbuf->b_term->tl_job == job)
2178 maketitle();
2179 update_cursor(curbuf->b_term, TRUE);
2180 }
2181}
2182
2183 static void
2184may_toggle_cursor(term_T *term)
2185{
2186 if (in_terminal_loop == term)
2187 {
2188 if (term->tl_cursor_visible)
2189 cursor_on();
2190 else
2191 cursor_off();
2192 }
2193}
2194
2195/*
2196 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002197 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002198 */
2199 static int
2200color2index(VTermColor *color, int fg, int *boldp)
2201{
2202 int red = color->red;
2203 int blue = color->blue;
2204 int green = color->green;
2205
Bram Moolenaar46359e12017-11-29 22:33:38 +01002206 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002207 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002208 /* First 16 colors and default: use the ANSI index, because these
2209 * colors can be redefined. */
2210 if (t_colors >= 16)
2211 return color->ansi_index;
2212 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002213 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002214 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002215 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002216 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2217 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2218 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002219 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002220 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2221 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2222 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2223 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2224 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2225 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2226 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2227 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2228 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2229 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2230 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002231 }
2232 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002233
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234 if (t_colors >= 256)
2235 {
2236 if (red == blue && red == green)
2237 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002238 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002240 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2241 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2242 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243 int i;
2244
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002245 if (red < 5)
2246 return 17; /* 00/00/00 */
2247 if (red > 245) /* ff/ff/ff */
2248 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002249 for (i = 0; i < 23; ++i)
2250 if (red < cutoff[i])
2251 return i + 233;
2252 return 256;
2253 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002254 {
2255 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2256 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002257
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002258 /* 216-color cube */
2259 for (ri = 0; ri < 5; ++ri)
2260 if (red < cutoff[ri])
2261 break;
2262 for (gi = 0; gi < 5; ++gi)
2263 if (green < cutoff[gi])
2264 break;
2265 for (bi = 0; bi < 5; ++bi)
2266 if (blue < cutoff[bi])
2267 break;
2268 return 17 + ri * 36 + gi * 6 + bi;
2269 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 }
2271 return 0;
2272}
2273
2274/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002275 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002276 */
2277 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002278vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002279{
2280 int attr = 0;
2281
2282 if (cellattrs.bold)
2283 attr |= HL_BOLD;
2284 if (cellattrs.underline)
2285 attr |= HL_UNDERLINE;
2286 if (cellattrs.italic)
2287 attr |= HL_ITALIC;
2288 if (cellattrs.strike)
2289 attr |= HL_STRIKETHROUGH;
2290 if (cellattrs.reverse)
2291 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002292 return attr;
2293}
2294
2295/*
2296 * Store Vterm attributes in "cell" from highlight flags.
2297 */
2298 static void
2299hl2vtermAttr(int attr, cellattr_T *cell)
2300{
2301 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2302 if (attr & HL_BOLD)
2303 cell->attrs.bold = 1;
2304 if (attr & HL_UNDERLINE)
2305 cell->attrs.underline = 1;
2306 if (attr & HL_ITALIC)
2307 cell->attrs.italic = 1;
2308 if (attr & HL_STRIKETHROUGH)
2309 cell->attrs.strike = 1;
2310 if (attr & HL_INVERSE)
2311 cell->attrs.reverse = 1;
2312}
2313
2314/*
2315 * Convert the attributes of a vterm cell into an attribute index.
2316 */
2317 static int
2318cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2319{
2320 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002321
2322#ifdef FEAT_GUI
2323 if (gui.in_use)
2324 {
2325 guicolor_T fg, bg;
2326
2327 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2328 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2329 return get_gui_attr_idx(attr, fg, bg);
2330 }
2331 else
2332#endif
2333#ifdef FEAT_TERMGUICOLORS
2334 if (p_tgc)
2335 {
2336 guicolor_T fg, bg;
2337
2338 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2339 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2340
2341 return get_tgc_attr_idx(attr, fg, bg);
2342 }
2343 else
2344#endif
2345 {
2346 int bold = MAYBE;
2347 int fg = color2index(&cellfg, TRUE, &bold);
2348 int bg = color2index(&cellbg, FALSE, &bold);
2349
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002350 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002351 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002352 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002353 if (fg == 0 && term_default_cterm_fg >= 0)
2354 fg = term_default_cterm_fg + 1;
2355 if (bg == 0 && term_default_cterm_bg >= 0)
2356 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002357 }
2358
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 /* with 8 colors set the bold attribute to get a bright foreground */
2360 if (bold == TRUE)
2361 attr |= HL_BOLD;
2362 return get_cterm_attr_idx(attr, fg, bg);
2363 }
2364 return 0;
2365}
2366
2367 static int
2368handle_damage(VTermRect rect, void *user)
2369{
2370 term_T *term = (term_T *)user;
2371
2372 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2373 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2374 redraw_buf_later(term->tl_buffer, NOT_VALID);
2375 return 1;
2376}
2377
2378 static int
2379handle_moverect(VTermRect dest, VTermRect src, void *user)
2380{
2381 term_T *term = (term_T *)user;
2382
2383 /* Scrolling up is done much more efficiently by deleting lines instead of
2384 * redrawing the text. */
2385 if (dest.start_col == src.start_col
2386 && dest.end_col == src.end_col
2387 && dest.start_row < src.start_row)
2388 {
2389 win_T *wp;
2390 VTermColor fg, bg;
2391 VTermScreenCellAttrs attr;
2392 int clear_attr;
2393
2394 /* Set the color to clear lines with. */
2395 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2396 &fg, &bg);
2397 vim_memset(&attr, 0, sizeof(attr));
2398 clear_attr = cell2attr(attr, fg, bg);
2399
2400 FOR_ALL_WINDOWS(wp)
2401 {
2402 if (wp->w_buffer == term->tl_buffer)
2403 win_del_lines(wp, dest.start_row,
2404 src.start_row - dest.start_row, FALSE, FALSE,
2405 clear_attr);
2406 }
2407 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002408
2409 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2410 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2411
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002412 redraw_buf_later(term->tl_buffer, NOT_VALID);
2413 return 1;
2414}
2415
2416 static int
2417handle_movecursor(
2418 VTermPos pos,
2419 VTermPos oldpos UNUSED,
2420 int visible,
2421 void *user)
2422{
2423 term_T *term = (term_T *)user;
2424 win_T *wp;
2425
2426 term->tl_cursor_pos = pos;
2427 term->tl_cursor_visible = visible;
2428
2429 FOR_ALL_WINDOWS(wp)
2430 {
2431 if (wp->w_buffer == term->tl_buffer)
2432 position_cursor(wp, &pos);
2433 }
2434 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2435 {
2436 may_toggle_cursor(term);
2437 update_cursor(term, term->tl_cursor_visible);
2438 }
2439
2440 return 1;
2441}
2442
2443 static int
2444handle_settermprop(
2445 VTermProp prop,
2446 VTermValue *value,
2447 void *user)
2448{
2449 term_T *term = (term_T *)user;
2450
2451 switch (prop)
2452 {
2453 case VTERM_PROP_TITLE:
2454 vim_free(term->tl_title);
2455 /* a blank title isn't useful, make it empty, so that "running" is
2456 * displayed */
2457 if (*skipwhite((char_u *)value->string) == NUL)
2458 term->tl_title = NULL;
2459#ifdef WIN3264
2460 else if (!enc_utf8 && enc_codepage > 0)
2461 {
2462 WCHAR *ret = NULL;
2463 int length = 0;
2464
2465 MultiByteToWideChar_alloc(CP_UTF8, 0,
2466 (char*)value->string, (int)STRLEN(value->string),
2467 &ret, &length);
2468 if (ret != NULL)
2469 {
2470 WideCharToMultiByte_alloc(enc_codepage, 0,
2471 ret, length, (char**)&term->tl_title,
2472 &length, 0, 0);
2473 vim_free(ret);
2474 }
2475 }
2476#endif
2477 else
2478 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002479 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 if (term == curbuf->b_term)
2481 maketitle();
2482 break;
2483
2484 case VTERM_PROP_CURSORVISIBLE:
2485 term->tl_cursor_visible = value->boolean;
2486 may_toggle_cursor(term);
2487 out_flush();
2488 break;
2489
2490 case VTERM_PROP_CURSORBLINK:
2491 term->tl_cursor_blink = value->boolean;
2492 may_set_cursor_props(term);
2493 break;
2494
2495 case VTERM_PROP_CURSORSHAPE:
2496 term->tl_cursor_shape = value->number;
2497 may_set_cursor_props(term);
2498 break;
2499
2500 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002501 if (desired_cursor_color == term->tl_cursor_color)
2502 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 vim_free(term->tl_cursor_color);
2504 if (*value->string == NUL)
2505 term->tl_cursor_color = NULL;
2506 else
2507 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2508 may_set_cursor_props(term);
2509 break;
2510
2511 case VTERM_PROP_ALTSCREEN:
2512 /* TODO: do anything else? */
2513 term->tl_using_altscreen = value->boolean;
2514 break;
2515
2516 default:
2517 break;
2518 }
2519 /* Always return 1, otherwise vterm doesn't store the value internally. */
2520 return 1;
2521}
2522
2523/*
2524 * The job running in the terminal resized the terminal.
2525 */
2526 static int
2527handle_resize(int rows, int cols, void *user)
2528{
2529 term_T *term = (term_T *)user;
2530 win_T *wp;
2531
2532 term->tl_rows = rows;
2533 term->tl_cols = cols;
2534 if (term->tl_vterm_size_changed)
2535 /* Size was set by vterm_set_size(), don't set the window size. */
2536 term->tl_vterm_size_changed = FALSE;
2537 else
2538 {
2539 FOR_ALL_WINDOWS(wp)
2540 {
2541 if (wp->w_buffer == term->tl_buffer)
2542 {
2543 win_setheight_win(rows, wp);
2544 win_setwidth_win(cols, wp);
2545 }
2546 }
2547 redraw_buf_later(term->tl_buffer, NOT_VALID);
2548 }
2549 return 1;
2550}
2551
2552/*
2553 * Handle a line that is pushed off the top of the screen.
2554 */
2555 static int
2556handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2557{
2558 term_T *term = (term_T *)user;
2559
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002560 /* If the number of lines that are stored goes over 'termscrollback' then
2561 * delete the first 10%. */
Bram Moolenaar8c94a542018-04-15 12:55:13 +02002562 if (term->tl_scrollback.ga_len >= p_tlsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002563 {
2564 int todo = p_tlsl / 10;
2565 int i;
2566
2567 curbuf = term->tl_buffer;
2568 for (i = 0; i < todo; ++i)
2569 {
2570 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2571 ml_delete(1, FALSE);
2572 }
2573 curbuf = curwin->w_buffer;
2574
2575 term->tl_scrollback.ga_len -= todo;
2576 mch_memmove(term->tl_scrollback.ga_data,
2577 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2578 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2579 }
2580
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581 if (ga_grow(&term->tl_scrollback, 1) == OK)
2582 {
2583 cellattr_T *p = NULL;
2584 int len = 0;
2585 int i;
2586 int c;
2587 int col;
2588 sb_line_T *line;
2589 garray_T ga;
2590 cellattr_T fill_attr = term->tl_default_color;
2591
2592 /* do not store empty cells at the end */
2593 for (i = 0; i < cols; ++i)
2594 if (cells[i].chars[0] != 0)
2595 len = i + 1;
2596 else
2597 cell2cellattr(&cells[i], &fill_attr);
2598
2599 ga_init2(&ga, 1, 100);
2600 if (len > 0)
2601 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2602 if (p != NULL)
2603 {
2604 for (col = 0; col < len; col += cells[col].width)
2605 {
2606 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2607 {
2608 ga.ga_len = 0;
2609 break;
2610 }
2611 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2612 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2613 (char_u *)ga.ga_data + ga.ga_len);
2614 cell2cellattr(&cells[col], &p[col]);
2615 }
2616 }
2617 if (ga_grow(&ga, 1) == FAIL)
2618 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2619 else
2620 {
2621 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2622 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2623 }
2624 ga_clear(&ga);
2625
2626 line = (sb_line_T *)term->tl_scrollback.ga_data
2627 + term->tl_scrollback.ga_len;
2628 line->sb_cols = len;
2629 line->sb_cells = p;
2630 line->sb_fill_attr = fill_attr;
2631 ++term->tl_scrollback.ga_len;
2632 ++term->tl_scrollback_scrolled;
2633 }
2634 return 0; /* ignored */
2635}
2636
2637static VTermScreenCallbacks screen_callbacks = {
2638 handle_damage, /* damage */
2639 handle_moverect, /* moverect */
2640 handle_movecursor, /* movecursor */
2641 handle_settermprop, /* settermprop */
2642 NULL, /* bell */
2643 handle_resize, /* resize */
2644 handle_pushline, /* sb_pushline */
2645 NULL /* sb_popline */
2646};
2647
2648/*
2649 * Called when a channel has been closed.
2650 * If this was a channel for a terminal window then finish it up.
2651 */
2652 void
2653term_channel_closed(channel_T *ch)
2654{
2655 term_T *term;
2656 int did_one = FALSE;
2657
2658 for (term = first_term; term != NULL; term = term->tl_next)
2659 if (term->tl_job == ch->ch_job)
2660 {
2661 term->tl_channel_closed = TRUE;
2662 did_one = TRUE;
2663
Bram Moolenaard23a8232018-02-10 18:45:26 +01002664 VIM_CLEAR(term->tl_title);
2665 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002666
2667 /* Unless in Terminal-Normal mode: clear the vterm. */
2668 if (!term->tl_normal_mode)
2669 {
2670 int fnum = term->tl_buffer->b_fnum;
2671
2672 cleanup_vterm(term);
2673
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002674 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002675 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002676 aco_save_T aco;
2677
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002678 /* ++close or term_finish == "close" */
2679 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002680 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002681 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002682 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 break;
2684 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002685 if (term->tl_finish == TL_FINISH_OPEN
2686 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002687 {
2688 char buf[50];
2689
2690 /* TODO: use term_opencmd */
2691 ch_log(NULL, "terminal job finished, opening window");
2692 vim_snprintf(buf, sizeof(buf),
2693 term->tl_opencmd == NULL
2694 ? "botright sbuf %d"
2695 : (char *)term->tl_opencmd, fnum);
2696 do_cmdline_cmd((char_u *)buf);
2697 }
2698 else
2699 ch_log(NULL, "terminal job finished");
2700 }
2701
2702 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2703 }
2704 if (did_one)
2705 {
2706 redraw_statuslines();
2707
2708 /* Need to break out of vgetc(). */
2709 ins_char_typebuf(K_IGNORE);
2710 typebuf_was_filled = TRUE;
2711
2712 term = curbuf->b_term;
2713 if (term != NULL)
2714 {
2715 if (term->tl_job == ch->ch_job)
2716 maketitle();
2717 update_cursor(term, term->tl_cursor_visible);
2718 }
2719 }
2720}
2721
2722/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002723 * Fill one screen line from a line of the terminal.
2724 * Advances "pos" to past the last column.
2725 */
2726 static void
2727term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2728{
2729 int off = screen_get_current_line_off();
2730
2731 for (pos->col = 0; pos->col < max_col; )
2732 {
2733 VTermScreenCell cell;
2734 int c;
2735
2736 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2737 vim_memset(&cell, 0, sizeof(cell));
2738
2739 c = cell.chars[0];
2740 if (c == NUL)
2741 {
2742 ScreenLines[off] = ' ';
2743 if (enc_utf8)
2744 ScreenLinesUC[off] = NUL;
2745 }
2746 else
2747 {
2748 if (enc_utf8)
2749 {
2750 int i;
2751
2752 /* composing chars */
2753 for (i = 0; i < Screen_mco
2754 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2755 {
2756 ScreenLinesC[i][off] = cell.chars[i + 1];
2757 if (cell.chars[i + 1] == 0)
2758 break;
2759 }
2760 if (c >= 0x80 || (Screen_mco > 0
2761 && ScreenLinesC[0][off] != 0))
2762 {
2763 ScreenLines[off] = ' ';
2764 ScreenLinesUC[off] = c;
2765 }
2766 else
2767 {
2768 ScreenLines[off] = c;
2769 ScreenLinesUC[off] = NUL;
2770 }
2771 }
2772#ifdef WIN3264
2773 else if (has_mbyte && c >= 0x80)
2774 {
2775 char_u mb[MB_MAXBYTES+1];
2776 WCHAR wc = c;
2777
2778 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2779 (char*)mb, 2, 0, 0) > 1)
2780 {
2781 ScreenLines[off] = mb[0];
2782 ScreenLines[off + 1] = mb[1];
2783 cell.width = mb_ptr2cells(mb);
2784 }
2785 else
2786 ScreenLines[off] = c;
2787 }
2788#endif
2789 else
2790 ScreenLines[off] = c;
2791 }
2792 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2793
2794 ++pos->col;
2795 ++off;
2796 if (cell.width == 2)
2797 {
2798 if (enc_utf8)
2799 ScreenLinesUC[off] = NUL;
2800
2801 /* don't set the second byte to NUL for a DBCS encoding, it
2802 * has been set above */
2803 if (enc_utf8 || !has_mbyte)
2804 ScreenLines[off] = NUL;
2805
2806 ++pos->col;
2807 ++off;
2808 }
2809 }
2810}
2811
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002812#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002813 static void
2814update_system_term(term_T *term)
2815{
2816 VTermPos pos;
2817 VTermScreen *screen;
2818
2819 if (term->tl_vterm == NULL)
2820 return;
2821 screen = vterm_obtain_screen(term->tl_vterm);
2822
2823 /* Scroll up to make more room for terminal lines if needed. */
2824 while (term->tl_toprow > 0
2825 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2826 {
2827 int save_p_more = p_more;
2828
2829 p_more = FALSE;
2830 msg_row = Rows - 1;
2831 msg_puts((char_u *)"\n");
2832 p_more = save_p_more;
2833 --term->tl_toprow;
2834 }
2835
2836 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2837 && pos.row < Rows; ++pos.row)
2838 {
2839 if (pos.row < term->tl_rows)
2840 {
2841 int max_col = MIN(Columns, term->tl_cols);
2842
2843 term_line2screenline(screen, &pos, max_col);
2844 }
2845 else
2846 pos.col = 0;
2847
2848 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2849 }
2850
2851 term->tl_dirty_row_start = MAX_ROW;
2852 term->tl_dirty_row_end = 0;
2853 update_cursor(term, TRUE);
2854}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002855#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002856
2857/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002858 * Called to update a window that contains an active terminal.
2859 * Returns FAIL when there is no terminal running in this window or in
2860 * Terminal-Normal mode.
2861 */
2862 int
2863term_update_window(win_T *wp)
2864{
2865 term_T *term = wp->w_buffer->b_term;
2866 VTerm *vterm;
2867 VTermScreen *screen;
2868 VTermState *state;
2869 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002870 int rows, cols;
2871 int newrows, newcols;
2872 int minsize;
2873 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874
2875 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2876 return FAIL;
2877
2878 vterm = term->tl_vterm;
2879 screen = vterm_obtain_screen(vterm);
2880 state = vterm_obtain_state(vterm);
2881
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002882 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002883 {
2884 term->tl_dirty_row_start = 0;
2885 term->tl_dirty_row_end = MAX_ROW;
2886 }
2887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 /*
2889 * If the window was resized a redraw will be triggered and we get here.
2890 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2891 */
Bram Moolenaar498c2562018-04-15 23:45:15 +02002892 minsize = parse_termsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893
Bram Moolenaar498c2562018-04-15 23:45:15 +02002894 newrows = 99999;
2895 newcols = 99999;
2896 FOR_ALL_WINDOWS(twp)
2897 {
2898 /* When more than one window shows the same terminal, use the
2899 * smallest size. */
2900 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02002902 newrows = MIN(newrows, twp->w_height);
2903 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002904 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02002905 }
2906 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
2907 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
2908
2909 if (term->tl_rows != newrows || term->tl_cols != newcols)
2910 {
2911
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002912
2913 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002914 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02002916 newrows);
2917 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002918 }
2919
2920 /* The cursor may have been moved when resizing. */
2921 vterm_state_get_cursorpos(state, &pos);
2922 position_cursor(wp, &pos);
2923
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002924 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2925 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002927 if (pos.row < term->tl_rows)
2928 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002929 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002930
Bram Moolenaar13568252018-03-16 20:46:58 +01002931 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002932 }
2933 else
2934 pos.col = 0;
2935
Bram Moolenaarf118d482018-03-13 13:14:00 +01002936 screen_line(wp->w_winrow + pos.row
2937#ifdef FEAT_MENU
2938 + winbar_height(wp)
2939#endif
2940 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002941 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002942 term->tl_dirty_row_start = MAX_ROW;
2943 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002944
2945 return OK;
2946}
2947
2948/*
2949 * Return TRUE if "wp" is a terminal window where the job has finished.
2950 */
2951 int
2952term_is_finished(buf_T *buf)
2953{
2954 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2955}
2956
2957/*
2958 * Return TRUE if "wp" is a terminal window where the job has finished or we
2959 * are in Terminal-Normal mode, thus we show the buffer contents.
2960 */
2961 int
2962term_show_buffer(buf_T *buf)
2963{
2964 term_T *term = buf->b_term;
2965
2966 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2967}
2968
2969/*
2970 * The current buffer is going to be changed. If there is terminal
2971 * highlighting remove it now.
2972 */
2973 void
2974term_change_in_curbuf(void)
2975{
2976 term_T *term = curbuf->b_term;
2977
2978 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2979 {
2980 free_scrollback(term);
2981 redraw_buf_later(term->tl_buffer, NOT_VALID);
2982
2983 /* The buffer is now like a normal buffer, it cannot be easily
2984 * abandoned when changed. */
2985 set_string_option_direct((char_u *)"buftype", -1,
2986 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2987 }
2988}
2989
2990/*
2991 * Get the screen attribute for a position in the buffer.
2992 * Use a negative "col" to get the filler background color.
2993 */
2994 int
2995term_get_attr(buf_T *buf, linenr_T lnum, int col)
2996{
2997 term_T *term = buf->b_term;
2998 sb_line_T *line;
2999 cellattr_T *cellattr;
3000
3001 if (lnum > term->tl_scrollback.ga_len)
3002 cellattr = &term->tl_default_color;
3003 else
3004 {
3005 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3006 if (col < 0 || col >= line->sb_cols)
3007 cellattr = &line->sb_fill_attr;
3008 else
3009 cellattr = line->sb_cells + col;
3010 }
3011 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3012}
3013
3014static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01003015 { 0, 0, 0, 1}, /* black */
3016 {224, 0, 0, 2}, /* dark red */
3017 { 0, 224, 0, 3}, /* dark green */
3018 {224, 224, 0, 4}, /* dark yellow / brown */
3019 { 0, 0, 224, 5}, /* dark blue */
3020 {224, 0, 224, 6}, /* dark magenta */
3021 { 0, 224, 224, 7}, /* dark cyan */
3022 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003023
Bram Moolenaar46359e12017-11-29 22:33:38 +01003024 {128, 128, 128, 9}, /* dark grey */
3025 {255, 64, 64, 10}, /* light red */
3026 { 64, 255, 64, 11}, /* light green */
3027 {255, 255, 64, 12}, /* yellow */
3028 { 64, 64, 255, 13}, /* light blue */
3029 {255, 64, 255, 14}, /* light magenta */
3030 { 64, 255, 255, 15}, /* light cyan */
3031 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003032};
3033
3034static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003035 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003036};
3037
3038static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003039 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
3040 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041};
3042
3043/*
3044 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003045 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046 */
3047 static void
3048cterm_color2rgb(int nr, VTermColor *rgb)
3049{
3050 int idx;
3051
3052 if (nr < 16)
3053 {
3054 *rgb = ansi_table[nr];
3055 }
3056 else if (nr < 232)
3057 {
3058 /* 216 color cube */
3059 idx = nr - 16;
3060 rgb->blue = cube_value[idx % 6];
3061 rgb->green = cube_value[idx / 6 % 6];
3062 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003063 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003064 }
3065 else if (nr < 256)
3066 {
3067 /* 24 grey scale ramp */
3068 idx = nr - 232;
3069 rgb->blue = grey_ramp[idx];
3070 rgb->green = grey_ramp[idx];
3071 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003072 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 }
3074}
3075
3076/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003077 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 */
3079 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003080init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003082 VTermColor *fg, *bg;
3083 int fgval, bgval;
3084 int id;
3085
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3087 term->tl_default_color.width = 1;
3088 fg = &term->tl_default_color.fg;
3089 bg = &term->tl_default_color.bg;
3090
3091 /* Vterm uses a default black background. Set it to white when
3092 * 'background' is "light". */
3093 if (*p_bg == 'l')
3094 {
3095 fgval = 0;
3096 bgval = 255;
3097 }
3098 else
3099 {
3100 fgval = 255;
3101 bgval = 0;
3102 }
3103 fg->red = fg->green = fg->blue = fgval;
3104 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003105 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003106
3107 /* The "Terminal" highlight group overrules the defaults. */
3108 id = syn_name2id((char_u *)"Terminal");
3109
Bram Moolenaar46359e12017-11-29 22:33:38 +01003110 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003111#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3112 if (0
3113# ifdef FEAT_GUI
3114 || gui.in_use
3115# endif
3116# ifdef FEAT_TERMGUICOLORS
3117 || p_tgc
3118# endif
3119 )
3120 {
3121 guicolor_T fg_rgb = INVALCOLOR;
3122 guicolor_T bg_rgb = INVALCOLOR;
3123
3124 if (id != 0)
3125 syn_id2colors(id, &fg_rgb, &bg_rgb);
3126
3127# ifdef FEAT_GUI
3128 if (gui.in_use)
3129 {
3130 if (fg_rgb == INVALCOLOR)
3131 fg_rgb = gui.norm_pixel;
3132 if (bg_rgb == INVALCOLOR)
3133 bg_rgb = gui.back_pixel;
3134 }
3135# ifdef FEAT_TERMGUICOLORS
3136 else
3137# endif
3138# endif
3139# ifdef FEAT_TERMGUICOLORS
3140 {
3141 if (fg_rgb == INVALCOLOR)
3142 fg_rgb = cterm_normal_fg_gui_color;
3143 if (bg_rgb == INVALCOLOR)
3144 bg_rgb = cterm_normal_bg_gui_color;
3145 }
3146# endif
3147 if (fg_rgb != INVALCOLOR)
3148 {
3149 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3150
3151 fg->red = (unsigned)(rgb >> 16);
3152 fg->green = (unsigned)(rgb >> 8) & 255;
3153 fg->blue = (unsigned)rgb & 255;
3154 }
3155 if (bg_rgb != INVALCOLOR)
3156 {
3157 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3158
3159 bg->red = (unsigned)(rgb >> 16);
3160 bg->green = (unsigned)(rgb >> 8) & 255;
3161 bg->blue = (unsigned)rgb & 255;
3162 }
3163 }
3164 else
3165#endif
3166 if (id != 0 && t_colors >= 16)
3167 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003168 if (term_default_cterm_fg >= 0)
3169 cterm_color2rgb(term_default_cterm_fg, fg);
3170 if (term_default_cterm_bg >= 0)
3171 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003172 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003173 else
3174 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003175#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003177#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003178
3179 /* In an MS-Windows console we know the normal colors. */
3180 if (cterm_normal_fg_color > 0)
3181 {
3182 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003183# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184 tmp = fg->red;
3185 fg->red = fg->blue;
3186 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003187# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003188 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003189# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003190 else
3191 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003192# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003194 if (cterm_normal_bg_color > 0)
3195 {
3196 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003197# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003198 tmp = bg->red;
3199 bg->red = bg->blue;
3200 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003201# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003202 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003203# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003204 else
3205 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003206# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003208}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003209
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003210#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3211/*
3212 * Set the 16 ANSI colors from array of RGB values
3213 */
3214 static void
3215set_vterm_palette(VTerm *vterm, long_u *rgb)
3216{
3217 int index = 0;
3218 VTermState *state = vterm_obtain_state(vterm);
3219 for (; index < 16; index++)
3220 {
3221 VTermColor color;
3222 color.red = (unsigned)(rgb[index] >> 16);
3223 color.green = (unsigned)(rgb[index] >> 8) & 255;
3224 color.blue = (unsigned)rgb[index] & 255;
3225 vterm_state_set_palette_color(state, index, &color);
3226 }
3227}
3228
3229/*
3230 * Set the ANSI color palette from a list of colors
3231 */
3232 static int
3233set_ansi_colors_list(VTerm *vterm, list_T *list)
3234{
3235 int n = 0;
3236 long_u rgb[16];
3237 listitem_T *li = list->lv_first;
3238
3239 for (; li != NULL && n < 16; li = li->li_next, n++)
3240 {
3241 char_u *color_name;
3242 guicolor_T guicolor;
3243
3244 color_name = get_tv_string_chk(&li->li_tv);
3245 if (color_name == NULL)
3246 return FAIL;
3247
3248 guicolor = GUI_GET_COLOR(color_name);
3249 if (guicolor == INVALCOLOR)
3250 return FAIL;
3251
3252 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3253 }
3254
3255 if (n != 16 || li != NULL)
3256 return FAIL;
3257
3258 set_vterm_palette(vterm, rgb);
3259
3260 return OK;
3261}
3262
3263/*
3264 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3265 */
3266 static void
3267init_vterm_ansi_colors(VTerm *vterm)
3268{
3269 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3270
3271 if (var != NULL
3272 && (var->di_tv.v_type != VAR_LIST
3273 || var->di_tv.vval.v_list == NULL
3274 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3275 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3276}
3277#endif
3278
Bram Moolenaar52acb112018-03-18 19:20:22 +01003279/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003280 * Handles a "drop" command from the job in the terminal.
3281 * "item" is the file name, "item->li_next" may have options.
3282 */
3283 static void
3284handle_drop_command(listitem_T *item)
3285{
3286 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003287 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003288 int bufnr;
3289 win_T *wp;
3290 tabpage_T *tp;
3291 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003292 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003293
3294 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3295 FOR_ALL_TAB_WINDOWS(tp, wp)
3296 {
3297 if (wp->w_buffer->b_fnum == bufnr)
3298 {
3299 /* buffer is in a window already, go there */
3300 goto_tabpage_win(tp, wp);
3301 return;
3302 }
3303 }
3304
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003305 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003306
3307 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3308 && opt_item->li_tv.vval.v_dict != NULL)
3309 {
3310 dict_T *dict = opt_item->li_tv.vval.v_dict;
3311 char_u *p;
3312
3313 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3314 if (p == NULL)
3315 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3316 if (p != NULL)
3317 {
3318 if (check_ff_value(p) == FAIL)
3319 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3320 else
3321 ea.force_ff = *p;
3322 }
3323 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3324 if (p == NULL)
3325 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3326 if (p != NULL)
3327 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003328 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003329 if (ea.cmd != NULL)
3330 {
3331 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3332 ea.force_enc = 11;
3333 tofree = ea.cmd;
3334 }
3335 }
3336
3337 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3338 if (p != NULL)
3339 get_bad_opt(p, &ea);
3340
3341 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3342 ea.force_bin = FORCE_BIN;
3343 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3344 ea.force_bin = FORCE_BIN;
3345 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3346 ea.force_bin = FORCE_NOBIN;
3347 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3348 ea.force_bin = FORCE_NOBIN;
3349 }
3350
3351 /* open in new window, like ":split fname" */
3352 if (ea.cmd == NULL)
3353 ea.cmd = (char_u *)"split";
3354 ea.arg = fname;
3355 ea.cmdidx = CMD_split;
3356 ex_splitview(&ea);
3357
3358 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003359}
3360
3361/*
3362 * Handles a function call from the job running in a terminal.
3363 * "item" is the function name, "item->li_next" has the arguments.
3364 */
3365 static void
3366handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3367{
3368 char_u *func;
3369 typval_T argvars[2];
3370 typval_T rettv;
3371 int doesrange;
3372
3373 if (item->li_next == NULL)
3374 {
3375 ch_log(channel, "Missing function arguments for call");
3376 return;
3377 }
3378 func = get_tv_string(&item->li_tv);
3379
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003380 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003381 {
3382 ch_log(channel, "Invalid function name: %s", func);
3383 return;
3384 }
3385
3386 argvars[0].v_type = VAR_NUMBER;
3387 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3388 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003389 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003390 2, argvars, /* argv_func */ NULL,
3391 /* firstline */ 1, /* lastline */ 1,
3392 &doesrange, /* evaluate */ TRUE,
3393 /* partial */ NULL, /* selfdict */ NULL) == OK)
3394 {
3395 clear_tv(&rettv);
3396 ch_log(channel, "Function %s called", func);
3397 }
3398 else
3399 ch_log(channel, "Calling function %s failed", func);
3400}
3401
3402/*
3403 * Called by libvterm when it cannot recognize an OSC sequence.
3404 * We recognize a terminal API command.
3405 */
3406 static int
3407parse_osc(const char *command, size_t cmdlen, void *user)
3408{
3409 term_T *term = (term_T *)user;
3410 js_read_T reader;
3411 typval_T tv;
3412 channel_T *channel = term->tl_job == NULL ? NULL
3413 : term->tl_job->jv_channel;
3414
3415 /* We recognize only OSC 5 1 ; {command} */
3416 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3417 return 0; /* not handled */
3418
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003419 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003420 if (reader.js_buf == NULL)
3421 return 1;
3422 reader.js_fill = NULL;
3423 reader.js_used = 0;
3424 if (json_decode(&reader, &tv, 0) == OK
3425 && tv.v_type == VAR_LIST
3426 && tv.vval.v_list != NULL)
3427 {
3428 listitem_T *item = tv.vval.v_list->lv_first;
3429
3430 if (item == NULL)
3431 ch_log(channel, "Missing command");
3432 else
3433 {
3434 char_u *cmd = get_tv_string(&item->li_tv);
3435
3436 item = item->li_next;
3437 if (item == NULL)
3438 ch_log(channel, "Missing argument for %s", cmd);
3439 else if (STRCMP(cmd, "drop") == 0)
3440 handle_drop_command(item);
3441 else if (STRCMP(cmd, "call") == 0)
3442 handle_call_command(term, channel, item);
3443 else
3444 ch_log(channel, "Invalid command received: %s", cmd);
3445 }
3446 }
3447 else
3448 ch_log(channel, "Invalid JSON received");
3449
3450 vim_free(reader.js_buf);
3451 clear_tv(&tv);
3452 return 1;
3453}
3454
3455static VTermParserCallbacks parser_fallbacks = {
3456 NULL, /* text */
3457 NULL, /* control */
3458 NULL, /* escape */
3459 NULL, /* csi */
3460 parse_osc, /* osc */
3461 NULL, /* dcs */
3462 NULL /* resize */
3463};
3464
3465/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003466 * Use Vim's allocation functions for vterm so profiling works.
3467 */
3468 static void *
3469vterm_malloc(size_t size, void *data UNUSED)
3470{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003471 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003472}
3473
3474 static void
3475vterm_memfree(void *ptr, void *data UNUSED)
3476{
3477 vim_free(ptr);
3478}
3479
3480static VTermAllocatorFunctions vterm_allocator = {
3481 &vterm_malloc,
3482 &vterm_memfree
3483};
3484
3485/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003486 * Create a new vterm and initialize it.
3487 */
3488 static void
3489create_vterm(term_T *term, int rows, int cols)
3490{
3491 VTerm *vterm;
3492 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003493 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003494 VTermValue value;
3495
Bram Moolenaar756ef112018-04-10 12:04:27 +02003496 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003497 term->tl_vterm = vterm;
3498 screen = vterm_obtain_screen(vterm);
3499 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3500 /* TODO: depends on 'encoding'. */
3501 vterm_set_utf8(vterm, 1);
3502
3503 init_default_colors(term);
3504
3505 vterm_state_set_default_colors(
3506 vterm_obtain_state(vterm),
3507 &term->tl_default_color.fg,
3508 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003509
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003510 if (t_colors >= 16)
3511 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3512
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003513 /* Required to initialize most things. */
3514 vterm_screen_reset(screen, 1 /* hard */);
3515
3516 /* Allow using alternate screen. */
3517 vterm_screen_enable_altscreen(screen, 1);
3518
3519 /* For unix do not use a blinking cursor. In an xterm this causes the
3520 * cursor to blink if it's blinking in the xterm.
3521 * For Windows we respect the system wide setting. */
3522#ifdef WIN3264
3523 if (GetCaretBlinkTime() == INFINITE)
3524 value.boolean = 0;
3525 else
3526 value.boolean = 1;
3527#else
3528 value.boolean = 0;
3529#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003530 state = vterm_obtain_state(vterm);
3531 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3532 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003533}
3534
3535/*
3536 * Return the text to show for the buffer name and status.
3537 */
3538 char_u *
3539term_get_status_text(term_T *term)
3540{
3541 if (term->tl_status_text == NULL)
3542 {
3543 char_u *txt;
3544 size_t len;
3545
3546 if (term->tl_normal_mode)
3547 {
3548 if (term_job_running(term))
3549 txt = (char_u *)_("Terminal");
3550 else
3551 txt = (char_u *)_("Terminal-finished");
3552 }
3553 else if (term->tl_title != NULL)
3554 txt = term->tl_title;
3555 else if (term_none_open(term))
3556 txt = (char_u *)_("active");
3557 else if (term_job_running(term))
3558 txt = (char_u *)_("running");
3559 else
3560 txt = (char_u *)_("finished");
3561 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3562 term->tl_status_text = alloc((int)len);
3563 if (term->tl_status_text != NULL)
3564 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3565 term->tl_buffer->b_fname, txt);
3566 }
3567 return term->tl_status_text;
3568}
3569
3570/*
3571 * Mark references in jobs of terminals.
3572 */
3573 int
3574set_ref_in_term(int copyID)
3575{
3576 int abort = FALSE;
3577 term_T *term;
3578 typval_T tv;
3579
3580 for (term = first_term; term != NULL; term = term->tl_next)
3581 if (term->tl_job != NULL)
3582 {
3583 tv.v_type = VAR_JOB;
3584 tv.vval.v_job = term->tl_job;
3585 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3586 }
3587 return abort;
3588}
3589
3590/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003591 * Cache "Terminal" highlight group colors.
3592 */
3593 void
3594set_terminal_default_colors(int cterm_fg, int cterm_bg)
3595{
3596 term_default_cterm_fg = cterm_fg - 1;
3597 term_default_cterm_bg = cterm_bg - 1;
3598}
3599
3600/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003601 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003602 * Returns NULL when the buffer is not for a terminal window and logs a message
3603 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003604 */
3605 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003606term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003607{
3608 buf_T *buf;
3609
3610 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3611 ++emsg_off;
3612 buf = get_buf_tv(&argvars[0], FALSE);
3613 --emsg_off;
3614 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003615 {
3616 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003617 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003618 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003619 return buf;
3620}
3621
Bram Moolenaard96ff162018-02-18 22:13:29 +01003622 static int
3623same_color(VTermColor *a, VTermColor *b)
3624{
3625 return a->red == b->red
3626 && a->green == b->green
3627 && a->blue == b->blue
3628 && a->ansi_index == b->ansi_index;
3629}
3630
3631 static void
3632dump_term_color(FILE *fd, VTermColor *color)
3633{
3634 fprintf(fd, "%02x%02x%02x%d",
3635 (int)color->red, (int)color->green, (int)color->blue,
3636 (int)color->ansi_index);
3637}
3638
3639/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003640 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003641 *
3642 * Each screen cell in full is:
3643 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3644 * {characters} is a space for an empty cell
3645 * For a double-width character "+" is changed to "*" and the next cell is
3646 * skipped.
3647 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3648 * when "&" use the same as the previous cell.
3649 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3650 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3651 * {color-idx} is a number from 0 to 255
3652 *
3653 * Screen cell with same width, attributes and color as the previous one:
3654 * |{characters}
3655 *
3656 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3657 *
3658 * Repeating the previous screen cell:
3659 * @{count}
3660 */
3661 void
3662f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3663{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003664 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003665 term_T *term;
3666 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003667 int max_height = 0;
3668 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003669 stat_T st;
3670 FILE *fd;
3671 VTermPos pos;
3672 VTermScreen *screen;
3673 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003674 VTermState *state;
3675 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003676
3677 if (check_restricted() || check_secure())
3678 return;
3679 if (buf == NULL)
3680 return;
3681 term = buf->b_term;
3682
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003683 if (argvars[2].v_type != VAR_UNKNOWN)
3684 {
3685 dict_T *d;
3686
3687 if (argvars[2].v_type != VAR_DICT)
3688 {
3689 EMSG(_(e_dictreq));
3690 return;
3691 }
3692 d = argvars[2].vval.v_dict;
3693 if (d != NULL)
3694 {
3695 max_height = get_dict_number(d, (char_u *)"rows");
3696 max_width = get_dict_number(d, (char_u *)"columns");
3697 }
3698 }
3699
Bram Moolenaard96ff162018-02-18 22:13:29 +01003700 fname = get_tv_string_chk(&argvars[1]);
3701 if (fname == NULL)
3702 return;
3703 if (mch_stat((char *)fname, &st) >= 0)
3704 {
3705 EMSG2(_("E953: File exists: %s"), fname);
3706 return;
3707 }
3708
Bram Moolenaard96ff162018-02-18 22:13:29 +01003709 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3710 {
3711 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3712 return;
3713 }
3714
3715 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3716
3717 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003718 state = vterm_obtain_state(term->tl_vterm);
3719 vterm_state_get_cursorpos(state, &cursor_pos);
3720
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003721 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3722 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003723 {
3724 int repeat = 0;
3725
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003726 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3727 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003728 {
3729 VTermScreenCell cell;
3730 int same_attr;
3731 int same_chars = TRUE;
3732 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003733 int is_cursor_pos = (pos.col == cursor_pos.col
3734 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003735
3736 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3737 vim_memset(&cell, 0, sizeof(cell));
3738
3739 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3740 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003741 int c = cell.chars[i];
3742 int pc = prev_cell.chars[i];
3743
3744 /* For the first character NUL is the same as space. */
3745 if (i == 0)
3746 {
3747 c = (c == NUL) ? ' ' : c;
3748 pc = (pc == NUL) ? ' ' : pc;
3749 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003750 if (cell.chars[i] != prev_cell.chars[i])
3751 same_chars = FALSE;
3752 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3753 break;
3754 }
3755 same_attr = vtermAttr2hl(cell.attrs)
3756 == vtermAttr2hl(prev_cell.attrs)
3757 && same_color(&cell.fg, &prev_cell.fg)
3758 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003759 if (same_chars && cell.width == prev_cell.width && same_attr
3760 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003761 {
3762 ++repeat;
3763 }
3764 else
3765 {
3766 if (repeat > 0)
3767 {
3768 fprintf(fd, "@%d", repeat);
3769 repeat = 0;
3770 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003771 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003772
3773 if (cell.chars[0] == NUL)
3774 fputs(" ", fd);
3775 else
3776 {
3777 char_u charbuf[10];
3778 int len;
3779
3780 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3781 && cell.chars[i] != NUL; ++i)
3782 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003783 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003784 fwrite(charbuf, len, 1, fd);
3785 }
3786 }
3787
3788 /* When only the characters differ we don't write anything, the
3789 * following "|", "@" or NL will indicate using the same
3790 * attributes. */
3791 if (cell.width != prev_cell.width || !same_attr)
3792 {
3793 if (cell.width == 2)
3794 {
3795 fputs("*", fd);
3796 ++pos.col;
3797 }
3798 else
3799 fputs("+", fd);
3800
3801 if (same_attr)
3802 {
3803 fputs("&", fd);
3804 }
3805 else
3806 {
3807 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3808 if (same_color(&cell.fg, &prev_cell.fg))
3809 fputs("&", fd);
3810 else
3811 {
3812 fputs("#", fd);
3813 dump_term_color(fd, &cell.fg);
3814 }
3815 if (same_color(&cell.bg, &prev_cell.bg))
3816 fputs("&", fd);
3817 else
3818 {
3819 fputs("#", fd);
3820 dump_term_color(fd, &cell.bg);
3821 }
3822 }
3823 }
3824
3825 prev_cell = cell;
3826 }
3827 }
3828 if (repeat > 0)
3829 fprintf(fd, "@%d", repeat);
3830 fputs("\n", fd);
3831 }
3832
3833 fclose(fd);
3834}
3835
3836/*
3837 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3838 */
3839 static void
3840dump_is_corrupt(garray_T *gap)
3841{
3842 ga_concat(gap, (char_u *)"CORRUPT");
3843}
3844
3845 static void
3846append_cell(garray_T *gap, cellattr_T *cell)
3847{
3848 if (ga_grow(gap, 1) == OK)
3849 {
3850 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3851 ++gap->ga_len;
3852 }
3853}
3854
3855/*
3856 * Read the dump file from "fd" and append lines to the current buffer.
3857 * Return the cell width of the longest line.
3858 */
3859 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003860read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003861{
3862 int c;
3863 garray_T ga_text;
3864 garray_T ga_cell;
3865 char_u *prev_char = NULL;
3866 int attr = 0;
3867 cellattr_T cell;
3868 term_T *term = curbuf->b_term;
3869 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003870 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003871
3872 ga_init2(&ga_text, 1, 90);
3873 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3874 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003875 cursor_pos->row = -1;
3876 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003877
3878 c = fgetc(fd);
3879 for (;;)
3880 {
3881 if (c == EOF)
3882 break;
3883 if (c == '\n')
3884 {
3885 /* End of a line: append it to the buffer. */
3886 if (ga_text.ga_data == NULL)
3887 dump_is_corrupt(&ga_text);
3888 if (ga_grow(&term->tl_scrollback, 1) == OK)
3889 {
3890 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3891 + term->tl_scrollback.ga_len;
3892
3893 if (max_cells < ga_cell.ga_len)
3894 max_cells = ga_cell.ga_len;
3895 line->sb_cols = ga_cell.ga_len;
3896 line->sb_cells = ga_cell.ga_data;
3897 line->sb_fill_attr = term->tl_default_color;
3898 ++term->tl_scrollback.ga_len;
3899 ga_init(&ga_cell);
3900
3901 ga_append(&ga_text, NUL);
3902 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3903 ga_text.ga_len, FALSE);
3904 }
3905 else
3906 ga_clear(&ga_cell);
3907 ga_text.ga_len = 0;
3908
3909 c = fgetc(fd);
3910 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003911 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003912 {
3913 int prev_len = ga_text.ga_len;
3914
Bram Moolenaar9271d052018-02-25 21:39:46 +01003915 if (c == '>')
3916 {
3917 if (cursor_pos->row != -1)
3918 dump_is_corrupt(&ga_text); /* duplicate cursor */
3919 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3920 cursor_pos->col = ga_cell.ga_len;
3921 }
3922
Bram Moolenaard96ff162018-02-18 22:13:29 +01003923 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3924 c = fgetc(fd);
3925 if (c != EOF)
3926 ga_append(&ga_text, c);
3927 for (;;)
3928 {
3929 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003930 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003931 || c == EOF || c == '\n')
3932 break;
3933 ga_append(&ga_text, c);
3934 }
3935
3936 /* save the character for repeating it */
3937 vim_free(prev_char);
3938 if (ga_text.ga_data != NULL)
3939 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3940 ga_text.ga_len - prev_len);
3941
Bram Moolenaar9271d052018-02-25 21:39:46 +01003942 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003943 {
3944 /* use all attributes from previous cell */
3945 }
3946 else if (c == '+' || c == '*')
3947 {
3948 int is_bg;
3949
3950 cell.width = c == '+' ? 1 : 2;
3951
3952 c = fgetc(fd);
3953 if (c == '&')
3954 {
3955 /* use same attr as previous cell */
3956 c = fgetc(fd);
3957 }
3958 else if (isdigit(c))
3959 {
3960 /* get the decimal attribute */
3961 attr = 0;
3962 while (isdigit(c))
3963 {
3964 attr = attr * 10 + (c - '0');
3965 c = fgetc(fd);
3966 }
3967 hl2vtermAttr(attr, &cell);
3968 }
3969 else
3970 dump_is_corrupt(&ga_text);
3971
3972 /* is_bg == 0: fg, is_bg == 1: bg */
3973 for (is_bg = 0; is_bg <= 1; ++is_bg)
3974 {
3975 if (c == '&')
3976 {
3977 /* use same color as previous cell */
3978 c = fgetc(fd);
3979 }
3980 else if (c == '#')
3981 {
3982 int red, green, blue, index = 0;
3983
3984 c = fgetc(fd);
3985 red = hex2nr(c);
3986 c = fgetc(fd);
3987 red = (red << 4) + hex2nr(c);
3988 c = fgetc(fd);
3989 green = hex2nr(c);
3990 c = fgetc(fd);
3991 green = (green << 4) + hex2nr(c);
3992 c = fgetc(fd);
3993 blue = hex2nr(c);
3994 c = fgetc(fd);
3995 blue = (blue << 4) + hex2nr(c);
3996 c = fgetc(fd);
3997 if (!isdigit(c))
3998 dump_is_corrupt(&ga_text);
3999 while (isdigit(c))
4000 {
4001 index = index * 10 + (c - '0');
4002 c = fgetc(fd);
4003 }
4004
4005 if (is_bg)
4006 {
4007 cell.bg.red = red;
4008 cell.bg.green = green;
4009 cell.bg.blue = blue;
4010 cell.bg.ansi_index = index;
4011 }
4012 else
4013 {
4014 cell.fg.red = red;
4015 cell.fg.green = green;
4016 cell.fg.blue = blue;
4017 cell.fg.ansi_index = index;
4018 }
4019 }
4020 else
4021 dump_is_corrupt(&ga_text);
4022 }
4023 }
4024 else
4025 dump_is_corrupt(&ga_text);
4026
4027 append_cell(&ga_cell, &cell);
4028 }
4029 else if (c == '@')
4030 {
4031 if (prev_char == NULL)
4032 dump_is_corrupt(&ga_text);
4033 else
4034 {
4035 int count = 0;
4036
4037 /* repeat previous character, get the count */
4038 for (;;)
4039 {
4040 c = fgetc(fd);
4041 if (!isdigit(c))
4042 break;
4043 count = count * 10 + (c - '0');
4044 }
4045
4046 while (count-- > 0)
4047 {
4048 ga_concat(&ga_text, prev_char);
4049 append_cell(&ga_cell, &cell);
4050 }
4051 }
4052 }
4053 else
4054 {
4055 dump_is_corrupt(&ga_text);
4056 c = fgetc(fd);
4057 }
4058 }
4059
4060 if (ga_text.ga_len > 0)
4061 {
4062 /* trailing characters after last NL */
4063 dump_is_corrupt(&ga_text);
4064 ga_append(&ga_text, NUL);
4065 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4066 ga_text.ga_len, FALSE);
4067 }
4068
4069 ga_clear(&ga_text);
4070 vim_free(prev_char);
4071
4072 return max_cells;
4073}
4074
4075/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004076 * Return an allocated string with at least "text_width" "=" characters and
4077 * "fname" inserted in the middle.
4078 */
4079 static char_u *
4080get_separator(int text_width, char_u *fname)
4081{
4082 int width = MAX(text_width, curwin->w_width);
4083 char_u *textline;
4084 int fname_size;
4085 char_u *p = fname;
4086 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004087 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004088
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004089 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004090 if (textline == NULL)
4091 return NULL;
4092
4093 fname_size = vim_strsize(fname);
4094 if (fname_size < width - 8)
4095 {
4096 /* enough room, don't use the full window width */
4097 width = MAX(text_width, fname_size + 8);
4098 }
4099 else if (fname_size > width - 8)
4100 {
4101 /* full name doesn't fit, use only the tail */
4102 p = gettail(fname);
4103 fname_size = vim_strsize(p);
4104 }
4105 /* skip characters until the name fits */
4106 while (fname_size > width - 8)
4107 {
4108 p += (*mb_ptr2len)(p);
4109 fname_size = vim_strsize(p);
4110 }
4111
4112 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4113 textline[i] = '=';
4114 textline[i++] = ' ';
4115
4116 STRCPY(textline + i, p);
4117 off = STRLEN(textline);
4118 textline[off] = ' ';
4119 for (i = 1; i < (width - fname_size) / 2; ++i)
4120 textline[off + i] = '=';
4121 textline[off + i] = NUL;
4122
4123 return textline;
4124}
4125
4126/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004127 * Common for "term_dumpdiff()" and "term_dumpload()".
4128 */
4129 static void
4130term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4131{
4132 jobopt_T opt;
4133 buf_T *buf;
4134 char_u buf1[NUMBUFLEN];
4135 char_u buf2[NUMBUFLEN];
4136 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004137 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004138 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004139 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004140 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004141 char_u *textline = NULL;
4142
4143 /* First open the files. If this fails bail out. */
4144 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4145 if (do_diff)
4146 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4147 if (fname1 == NULL || (do_diff && fname2 == NULL))
4148 {
4149 EMSG(_(e_invarg));
4150 return;
4151 }
4152 fd1 = mch_fopen((char *)fname1, READBIN);
4153 if (fd1 == NULL)
4154 {
4155 EMSG2(_(e_notread), fname1);
4156 return;
4157 }
4158 if (do_diff)
4159 {
4160 fd2 = mch_fopen((char *)fname2, READBIN);
4161 if (fd2 == NULL)
4162 {
4163 fclose(fd1);
4164 EMSG2(_(e_notread), fname2);
4165 return;
4166 }
4167 }
4168
4169 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004170 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4171 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4172 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4173 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4174 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004175
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004176 if (opt.jo_term_name == NULL)
4177 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004178 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004179
Bram Moolenaarb571c632018-03-21 22:27:59 +01004180 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004181 if (fname_tofree != NULL)
4182 {
4183 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4184 opt.jo_term_name = fname_tofree;
4185 }
4186 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004187
Bram Moolenaar13568252018-03-16 20:46:58 +01004188 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004189 if (buf != NULL && buf->b_term != NULL)
4190 {
4191 int i;
4192 linenr_T bot_lnum;
4193 linenr_T lnum;
4194 term_T *term = buf->b_term;
4195 int width;
4196 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004197 VTermPos cursor_pos1;
4198 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004199
Bram Moolenaar52acb112018-03-18 19:20:22 +01004200 init_default_colors(term);
4201
Bram Moolenaard96ff162018-02-18 22:13:29 +01004202 rettv->vval.v_number = buf->b_fnum;
4203
4204 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004205 width = read_dump_file(fd1, &cursor_pos1);
4206
4207 /* position the cursor */
4208 if (cursor_pos1.row >= 0)
4209 {
4210 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4211 coladvance(cursor_pos1.col);
4212 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004213
4214 /* Delete the empty line that was in the empty buffer. */
4215 ml_delete(1, FALSE);
4216
4217 /* For term_dumpload() we are done here. */
4218 if (!do_diff)
4219 goto theend;
4220
4221 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4222
Bram Moolenaar4a696342018-04-05 18:45:26 +02004223 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004224 if (textline == NULL)
4225 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004226 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4227 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4228 vim_free(textline);
4229
4230 textline = get_separator(width, fname2);
4231 if (textline == NULL)
4232 goto theend;
4233 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4234 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004235 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004236
4237 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004238 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004239 if (width2 > width)
4240 {
4241 vim_free(textline);
4242 textline = alloc(width2 + 1);
4243 if (textline == NULL)
4244 goto theend;
4245 width = width2;
4246 textline[width] = NUL;
4247 }
4248 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4249
4250 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4251 {
4252 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4253 {
4254 /* bottom part has fewer rows, fill with "-" */
4255 for (i = 0; i < width; ++i)
4256 textline[i] = '-';
4257 }
4258 else
4259 {
4260 char_u *line1;
4261 char_u *line2;
4262 char_u *p1;
4263 char_u *p2;
4264 int col;
4265 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4266 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4267 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4268 ->sb_cells;
4269
4270 /* Make a copy, getting the second line will invalidate it. */
4271 line1 = vim_strsave(ml_get(lnum));
4272 if (line1 == NULL)
4273 break;
4274 p1 = line1;
4275
4276 line2 = ml_get(lnum + bot_lnum);
4277 p2 = line2;
4278 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4279 {
4280 int len1 = utfc_ptr2len(p1);
4281 int len2 = utfc_ptr2len(p2);
4282
4283 textline[col] = ' ';
4284 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004285 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004286 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004287 else if (lnum == cursor_pos1.row + 1
4288 && col == cursor_pos1.col
4289 && (cursor_pos1.row != cursor_pos2.row
4290 || cursor_pos1.col != cursor_pos2.col))
4291 /* cursor in first but not in second */
4292 textline[col] = '>';
4293 else if (lnum == cursor_pos2.row + 1
4294 && col == cursor_pos2.col
4295 && (cursor_pos1.row != cursor_pos2.row
4296 || cursor_pos1.col != cursor_pos2.col))
4297 /* cursor in second but not in first */
4298 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004299 else if (cellattr1 != NULL && cellattr2 != NULL)
4300 {
4301 if ((cellattr1 + col)->width
4302 != (cellattr2 + col)->width)
4303 textline[col] = 'w';
4304 else if (!same_color(&(cellattr1 + col)->fg,
4305 &(cellattr2 + col)->fg))
4306 textline[col] = 'f';
4307 else if (!same_color(&(cellattr1 + col)->bg,
4308 &(cellattr2 + col)->bg))
4309 textline[col] = 'b';
4310 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4311 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4312 textline[col] = 'a';
4313 }
4314 p1 += len1;
4315 p2 += len2;
4316 /* TODO: handle different width */
4317 }
4318 vim_free(line1);
4319
4320 while (col < width)
4321 {
4322 if (*p1 == NUL && *p2 == NUL)
4323 textline[col] = '?';
4324 else if (*p1 == NUL)
4325 {
4326 textline[col] = '+';
4327 p2 += utfc_ptr2len(p2);
4328 }
4329 else
4330 {
4331 textline[col] = '-';
4332 p1 += utfc_ptr2len(p1);
4333 }
4334 ++col;
4335 }
4336 }
4337 if (add_empty_scrollback(term, &term->tl_default_color,
4338 term->tl_top_diff_rows) == OK)
4339 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4340 ++bot_lnum;
4341 }
4342
4343 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4344 {
4345 /* bottom part has more rows, fill with "+" */
4346 for (i = 0; i < width; ++i)
4347 textline[i] = '+';
4348 if (add_empty_scrollback(term, &term->tl_default_color,
4349 term->tl_top_diff_rows) == OK)
4350 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4351 ++lnum;
4352 ++bot_lnum;
4353 }
4354
4355 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004356
4357 /* looks better without wrapping */
4358 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004359 }
4360
4361theend:
4362 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004363 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004364 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004365 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004366 fclose(fd2);
4367}
4368
4369/*
4370 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4371 * bottom files.
4372 * Return FAIL when this is not possible.
4373 */
4374 int
4375term_swap_diff()
4376{
4377 term_T *term = curbuf->b_term;
4378 linenr_T line_count;
4379 linenr_T top_rows;
4380 linenr_T bot_rows;
4381 linenr_T bot_start;
4382 linenr_T lnum;
4383 char_u *p;
4384 sb_line_T *sb_line;
4385
4386 if (term == NULL
4387 || !term_is_finished(curbuf)
4388 || term->tl_top_diff_rows == 0
4389 || term->tl_scrollback.ga_len == 0)
4390 return FAIL;
4391
4392 line_count = curbuf->b_ml.ml_line_count;
4393 top_rows = term->tl_top_diff_rows;
4394 bot_rows = term->tl_bot_diff_rows;
4395 bot_start = line_count - bot_rows;
4396 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4397
4398 /* move lines from top to above the bottom part */
4399 for (lnum = 1; lnum <= top_rows; ++lnum)
4400 {
4401 p = vim_strsave(ml_get(1));
4402 if (p == NULL)
4403 return OK;
4404 ml_append(bot_start, p, 0, FALSE);
4405 ml_delete(1, FALSE);
4406 vim_free(p);
4407 }
4408
4409 /* move lines from bottom to the top */
4410 for (lnum = 1; lnum <= bot_rows; ++lnum)
4411 {
4412 p = vim_strsave(ml_get(bot_start + lnum));
4413 if (p == NULL)
4414 return OK;
4415 ml_delete(bot_start + lnum, FALSE);
4416 ml_append(lnum - 1, p, 0, FALSE);
4417 vim_free(p);
4418 }
4419
4420 if (top_rows == bot_rows)
4421 {
4422 /* rows counts are equal, can swap cell properties */
4423 for (lnum = 0; lnum < top_rows; ++lnum)
4424 {
4425 sb_line_T temp;
4426
4427 temp = *(sb_line + lnum);
4428 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4429 *(sb_line + bot_start + lnum) = temp;
4430 }
4431 }
4432 else
4433 {
4434 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4435 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4436
4437 /* need to copy cell properties into temp memory */
4438 if (temp != NULL)
4439 {
4440 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4441 mch_memmove(term->tl_scrollback.ga_data,
4442 temp + bot_start,
4443 sizeof(sb_line_T) * bot_rows);
4444 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4445 temp + top_rows,
4446 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4447 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4448 + line_count - top_rows,
4449 temp,
4450 sizeof(sb_line_T) * top_rows);
4451 vim_free(temp);
4452 }
4453 }
4454
4455 term->tl_top_diff_rows = bot_rows;
4456 term->tl_bot_diff_rows = top_rows;
4457
4458 update_screen(NOT_VALID);
4459 return OK;
4460}
4461
4462/*
4463 * "term_dumpdiff(filename, filename, options)" function
4464 */
4465 void
4466f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4467{
4468 term_load_dump(argvars, rettv, TRUE);
4469}
4470
4471/*
4472 * "term_dumpload(filename, options)" function
4473 */
4474 void
4475f_term_dumpload(typval_T *argvars, typval_T *rettv)
4476{
4477 term_load_dump(argvars, rettv, FALSE);
4478}
4479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004480/*
4481 * "term_getaltscreen(buf)" function
4482 */
4483 void
4484f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4485{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004486 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004487
4488 if (buf == NULL)
4489 return;
4490 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4491}
4492
4493/*
4494 * "term_getattr(attr, name)" function
4495 */
4496 void
4497f_term_getattr(typval_T *argvars, typval_T *rettv)
4498{
4499 int attr;
4500 size_t i;
4501 char_u *name;
4502
4503 static struct {
4504 char *name;
4505 int attr;
4506 } attrs[] = {
4507 {"bold", HL_BOLD},
4508 {"italic", HL_ITALIC},
4509 {"underline", HL_UNDERLINE},
4510 {"strike", HL_STRIKETHROUGH},
4511 {"reverse", HL_INVERSE},
4512 };
4513
4514 attr = get_tv_number(&argvars[0]);
4515 name = get_tv_string_chk(&argvars[1]);
4516 if (name == NULL)
4517 return;
4518
4519 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4520 if (STRCMP(name, attrs[i].name) == 0)
4521 {
4522 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4523 break;
4524 }
4525}
4526
4527/*
4528 * "term_getcursor(buf)" function
4529 */
4530 void
4531f_term_getcursor(typval_T *argvars, typval_T *rettv)
4532{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004533 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004534 term_T *term;
4535 list_T *l;
4536 dict_T *d;
4537
4538 if (rettv_list_alloc(rettv) == FAIL)
4539 return;
4540 if (buf == NULL)
4541 return;
4542 term = buf->b_term;
4543
4544 l = rettv->vval.v_list;
4545 list_append_number(l, term->tl_cursor_pos.row + 1);
4546 list_append_number(l, term->tl_cursor_pos.col + 1);
4547
4548 d = dict_alloc();
4549 if (d != NULL)
4550 {
4551 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4552 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4553 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4554 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4555 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4556 ? (char_u *)"" : term->tl_cursor_color);
4557 list_append_dict(l, d);
4558 }
4559}
4560
4561/*
4562 * "term_getjob(buf)" function
4563 */
4564 void
4565f_term_getjob(typval_T *argvars, typval_T *rettv)
4566{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004567 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004568
4569 rettv->v_type = VAR_JOB;
4570 rettv->vval.v_job = NULL;
4571 if (buf == NULL)
4572 return;
4573
4574 rettv->vval.v_job = buf->b_term->tl_job;
4575 if (rettv->vval.v_job != NULL)
4576 ++rettv->vval.v_job->jv_refcount;
4577}
4578
4579 static int
4580get_row_number(typval_T *tv, term_T *term)
4581{
4582 if (tv->v_type == VAR_STRING
4583 && tv->vval.v_string != NULL
4584 && STRCMP(tv->vval.v_string, ".") == 0)
4585 return term->tl_cursor_pos.row;
4586 return (int)get_tv_number(tv) - 1;
4587}
4588
4589/*
4590 * "term_getline(buf, row)" function
4591 */
4592 void
4593f_term_getline(typval_T *argvars, typval_T *rettv)
4594{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004595 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004596 term_T *term;
4597 int row;
4598
4599 rettv->v_type = VAR_STRING;
4600 if (buf == NULL)
4601 return;
4602 term = buf->b_term;
4603 row = get_row_number(&argvars[1], term);
4604
4605 if (term->tl_vterm == NULL)
4606 {
4607 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4608
4609 /* vterm is finished, get the text from the buffer */
4610 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4611 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4612 }
4613 else
4614 {
4615 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4616 VTermRect rect;
4617 int len;
4618 char_u *p;
4619
4620 if (row < 0 || row >= term->tl_rows)
4621 return;
4622 len = term->tl_cols * MB_MAXBYTES + 1;
4623 p = alloc(len);
4624 if (p == NULL)
4625 return;
4626 rettv->vval.v_string = p;
4627
4628 rect.start_col = 0;
4629 rect.end_col = term->tl_cols;
4630 rect.start_row = row;
4631 rect.end_row = row + 1;
4632 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4633 }
4634}
4635
4636/*
4637 * "term_getscrolled(buf)" function
4638 */
4639 void
4640f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4641{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004642 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004643
4644 if (buf == NULL)
4645 return;
4646 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4647}
4648
4649/*
4650 * "term_getsize(buf)" function
4651 */
4652 void
4653f_term_getsize(typval_T *argvars, typval_T *rettv)
4654{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004655 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004656 list_T *l;
4657
4658 if (rettv_list_alloc(rettv) == FAIL)
4659 return;
4660 if (buf == NULL)
4661 return;
4662
4663 l = rettv->vval.v_list;
4664 list_append_number(l, buf->b_term->tl_rows);
4665 list_append_number(l, buf->b_term->tl_cols);
4666}
4667
4668/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004669 * "term_setsize(buf, rows, cols)" function
4670 */
4671 void
4672f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4673{
4674 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4675 term_T *term;
4676 varnumber_T rows, cols;
4677
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004678 if (buf == NULL)
4679 {
4680 EMSG(_("E955: Not a terminal buffer"));
4681 return;
4682 }
4683 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004684 return;
4685 term = buf->b_term;
4686 rows = get_tv_number(&argvars[1]);
4687 rows = rows <= 0 ? term->tl_rows : rows;
4688 cols = get_tv_number(&argvars[2]);
4689 cols = cols <= 0 ? term->tl_cols : cols;
4690 vterm_set_size(term->tl_vterm, rows, cols);
4691 /* handle_resize() will resize the windows */
4692
4693 /* Get and remember the size we ended up with. Update the pty. */
4694 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4695 term_report_winsize(term, term->tl_rows, term->tl_cols);
4696}
4697
4698/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004699 * "term_getstatus(buf)" function
4700 */
4701 void
4702f_term_getstatus(typval_T *argvars, typval_T *rettv)
4703{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004704 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004705 term_T *term;
4706 char_u val[100];
4707
4708 rettv->v_type = VAR_STRING;
4709 if (buf == NULL)
4710 return;
4711 term = buf->b_term;
4712
4713 if (term_job_running(term))
4714 STRCPY(val, "running");
4715 else
4716 STRCPY(val, "finished");
4717 if (term->tl_normal_mode)
4718 STRCAT(val, ",normal");
4719 rettv->vval.v_string = vim_strsave(val);
4720}
4721
4722/*
4723 * "term_gettitle(buf)" function
4724 */
4725 void
4726f_term_gettitle(typval_T *argvars, typval_T *rettv)
4727{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004728 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004729
4730 rettv->v_type = VAR_STRING;
4731 if (buf == NULL)
4732 return;
4733
4734 if (buf->b_term->tl_title != NULL)
4735 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4736}
4737
4738/*
4739 * "term_gettty(buf)" function
4740 */
4741 void
4742f_term_gettty(typval_T *argvars, typval_T *rettv)
4743{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004744 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004745 char_u *p;
4746 int num = 0;
4747
4748 rettv->v_type = VAR_STRING;
4749 if (buf == NULL)
4750 return;
4751 if (argvars[1].v_type != VAR_UNKNOWN)
4752 num = get_tv_number(&argvars[1]);
4753
4754 switch (num)
4755 {
4756 case 0:
4757 if (buf->b_term->tl_job != NULL)
4758 p = buf->b_term->tl_job->jv_tty_out;
4759 else
4760 p = buf->b_term->tl_tty_out;
4761 break;
4762 case 1:
4763 if (buf->b_term->tl_job != NULL)
4764 p = buf->b_term->tl_job->jv_tty_in;
4765 else
4766 p = buf->b_term->tl_tty_in;
4767 break;
4768 default:
4769 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4770 return;
4771 }
4772 if (p != NULL)
4773 rettv->vval.v_string = vim_strsave(p);
4774}
4775
4776/*
4777 * "term_list()" function
4778 */
4779 void
4780f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4781{
4782 term_T *tp;
4783 list_T *l;
4784
4785 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4786 return;
4787
4788 l = rettv->vval.v_list;
4789 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4790 if (tp != NULL && tp->tl_buffer != NULL)
4791 if (list_append_number(l,
4792 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4793 return;
4794}
4795
4796/*
4797 * "term_scrape(buf, row)" function
4798 */
4799 void
4800f_term_scrape(typval_T *argvars, typval_T *rettv)
4801{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004802 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004803 VTermScreen *screen = NULL;
4804 VTermPos pos;
4805 list_T *l;
4806 term_T *term;
4807 char_u *p;
4808 sb_line_T *line;
4809
4810 if (rettv_list_alloc(rettv) == FAIL)
4811 return;
4812 if (buf == NULL)
4813 return;
4814 term = buf->b_term;
4815
4816 l = rettv->vval.v_list;
4817 pos.row = get_row_number(&argvars[1], term);
4818
4819 if (term->tl_vterm != NULL)
4820 {
4821 screen = vterm_obtain_screen(term->tl_vterm);
4822 p = NULL;
4823 line = NULL;
4824 }
4825 else
4826 {
4827 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4828
4829 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4830 return;
4831 p = ml_get_buf(buf, lnum + 1, FALSE);
4832 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4833 }
4834
4835 for (pos.col = 0; pos.col < term->tl_cols; )
4836 {
4837 dict_T *dcell;
4838 int width;
4839 VTermScreenCellAttrs attrs;
4840 VTermColor fg, bg;
4841 char_u rgb[8];
4842 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4843 int off = 0;
4844 int i;
4845
4846 if (screen == NULL)
4847 {
4848 cellattr_T *cellattr;
4849 int len;
4850
4851 /* vterm has finished, get the cell from scrollback */
4852 if (pos.col >= line->sb_cols)
4853 break;
4854 cellattr = line->sb_cells + pos.col;
4855 width = cellattr->width;
4856 attrs = cellattr->attrs;
4857 fg = cellattr->fg;
4858 bg = cellattr->bg;
4859 len = MB_PTR2LEN(p);
4860 mch_memmove(mbs, p, len);
4861 mbs[len] = NUL;
4862 p += len;
4863 }
4864 else
4865 {
4866 VTermScreenCell cell;
4867 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4868 break;
4869 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4870 {
4871 if (cell.chars[i] == 0)
4872 break;
4873 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4874 }
4875 mbs[off] = NUL;
4876 width = cell.width;
4877 attrs = cell.attrs;
4878 fg = cell.fg;
4879 bg = cell.bg;
4880 }
4881 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004882 if (dcell == NULL)
4883 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004884 list_append_dict(l, dcell);
4885
4886 dict_add_nr_str(dcell, "chars", 0, mbs);
4887
4888 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4889 fg.red, fg.green, fg.blue);
4890 dict_add_nr_str(dcell, "fg", 0, rgb);
4891 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4892 bg.red, bg.green, bg.blue);
4893 dict_add_nr_str(dcell, "bg", 0, rgb);
4894
4895 dict_add_nr_str(dcell, "attr",
4896 cell2attr(attrs, fg, bg), NULL);
4897 dict_add_nr_str(dcell, "width", width, NULL);
4898
4899 ++pos.col;
4900 if (width == 2)
4901 ++pos.col;
4902 }
4903}
4904
4905/*
4906 * "term_sendkeys(buf, keys)" function
4907 */
4908 void
4909f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4910{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004911 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004912 char_u *msg;
4913 term_T *term;
4914
4915 rettv->v_type = VAR_UNKNOWN;
4916 if (buf == NULL)
4917 return;
4918
4919 msg = get_tv_string_chk(&argvars[1]);
4920 if (msg == NULL)
4921 return;
4922 term = buf->b_term;
4923 if (term->tl_vterm == NULL)
4924 return;
4925
4926 while (*msg != NUL)
4927 {
4928 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004929 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004930 }
4931}
4932
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004933#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4934/*
4935 * "term_getansicolors(buf)" function
4936 */
4937 void
4938f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4939{
4940 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4941 term_T *term;
4942 VTermState *state;
4943 VTermColor color;
4944 char_u hexbuf[10];
4945 int index;
4946 list_T *list;
4947
4948 if (rettv_list_alloc(rettv) == FAIL)
4949 return;
4950
4951 if (buf == NULL)
4952 return;
4953 term = buf->b_term;
4954 if (term->tl_vterm == NULL)
4955 return;
4956
4957 list = rettv->vval.v_list;
4958 state = vterm_obtain_state(term->tl_vterm);
4959 for (index = 0; index < 16; index++)
4960 {
4961 vterm_state_get_palette_color(state, index, &color);
4962 sprintf((char *)hexbuf, "#%02x%02x%02x",
4963 color.red, color.green, color.blue);
4964 if (list_append_string(list, hexbuf, 7) == FAIL)
4965 return;
4966 }
4967}
4968
4969/*
4970 * "term_setansicolors(buf, list)" function
4971 */
4972 void
4973f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4974{
4975 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4976 term_T *term;
4977
4978 if (buf == NULL)
4979 return;
4980 term = buf->b_term;
4981 if (term->tl_vterm == NULL)
4982 return;
4983
4984 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4985 {
4986 EMSG(_(e_listreq));
4987 return;
4988 }
4989
4990 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4991 EMSG(_(e_invarg));
4992}
4993#endif
4994
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004995/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004996 * "term_setrestore(buf, command)" function
4997 */
4998 void
4999f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5000{
5001#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005002 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005003 term_T *term;
5004 char_u *cmd;
5005
5006 if (buf == NULL)
5007 return;
5008 term = buf->b_term;
5009 vim_free(term->tl_command);
5010 cmd = get_tv_string_chk(&argvars[1]);
5011 if (cmd != NULL)
5012 term->tl_command = vim_strsave(cmd);
5013 else
5014 term->tl_command = NULL;
5015#endif
5016}
5017
5018/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005019 * "term_setkill(buf, how)" function
5020 */
5021 void
5022f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5023{
5024 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5025 term_T *term;
5026 char_u *how;
5027
5028 if (buf == NULL)
5029 return;
5030 term = buf->b_term;
5031 vim_free(term->tl_kill);
5032 how = get_tv_string_chk(&argvars[1]);
5033 if (how != NULL)
5034 term->tl_kill = vim_strsave(how);
5035 else
5036 term->tl_kill = NULL;
5037}
5038
5039/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005040 * "term_start(command, options)" function
5041 */
5042 void
5043f_term_start(typval_T *argvars, typval_T *rettv)
5044{
5045 jobopt_T opt;
5046 buf_T *buf;
5047
5048 init_job_options(&opt);
5049 if (argvars[1].v_type != VAR_UNKNOWN
5050 && get_job_options(&argvars[1], &opt,
5051 JO_TIMEOUT_ALL + JO_STOPONEXIT
5052 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5053 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5054 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5055 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005056 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005057 + JO2_NORESTORE + JO2_TERM_KILL
5058 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005059 return;
5060
Bram Moolenaar13568252018-03-16 20:46:58 +01005061 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005062
5063 if (buf != NULL && buf->b_term != NULL)
5064 rettv->vval.v_number = buf->b_fnum;
5065}
5066
5067/*
5068 * "term_wait" function
5069 */
5070 void
5071f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5072{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005073 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005074
5075 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005076 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005077 if (buf->b_term->tl_job == NULL)
5078 {
5079 ch_log(NULL, "term_wait(): no job to wait for");
5080 return;
5081 }
5082 if (buf->b_term->tl_job->jv_channel == NULL)
5083 /* channel is closed, nothing to do */
5084 return;
5085
5086 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005087 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005088 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5089 {
5090 /* The job is dead, keep reading channel I/O until the channel is
5091 * closed. buf->b_term may become NULL if the terminal was closed while
5092 * waiting. */
5093 ch_log(NULL, "term_wait(): waiting for channel to close");
5094 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5095 {
5096 mch_check_messages();
5097 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005098 if (!buf_valid(buf))
5099 /* If the terminal is closed when the channel is closed the
5100 * buffer disappears. */
5101 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005102 ui_delay(10L, FALSE);
5103 }
5104 mch_check_messages();
5105 parse_queued_messages();
5106 }
5107 else
5108 {
5109 long wait = 10L;
5110
5111 mch_check_messages();
5112 parse_queued_messages();
5113
5114 /* Wait for some time for any channel I/O. */
5115 if (argvars[1].v_type != VAR_UNKNOWN)
5116 wait = get_tv_number(&argvars[1]);
5117 ui_delay(wait, TRUE);
5118 mch_check_messages();
5119
5120 /* Flushing messages on channels is hopefully sufficient.
5121 * TODO: is there a better way? */
5122 parse_queued_messages();
5123 }
5124}
5125
5126/*
5127 * Called when a channel has sent all the lines to a terminal.
5128 * Send a CTRL-D to mark the end of the text.
5129 */
5130 void
5131term_send_eof(channel_T *ch)
5132{
5133 term_T *term;
5134
5135 for (term = first_term; term != NULL; term = term->tl_next)
5136 if (term->tl_job == ch->ch_job)
5137 {
5138 if (term->tl_eof_chars != NULL)
5139 {
5140 channel_send(ch, PART_IN, term->tl_eof_chars,
5141 (int)STRLEN(term->tl_eof_chars), NULL);
5142 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5143 }
5144# ifdef WIN3264
5145 else
5146 /* Default: CTRL-D */
5147 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5148# endif
5149 }
5150}
5151
5152# if defined(WIN3264) || defined(PROTO)
5153
5154/**************************************
5155 * 2. MS-Windows implementation.
5156 */
5157
5158# ifndef PROTO
5159
5160#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5161#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005162#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005163
5164void* (*winpty_config_new)(UINT64, void*);
5165void* (*winpty_open)(void*, void*);
5166void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5167BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5168void (*winpty_config_set_mouse_mode)(void*, int);
5169void (*winpty_config_set_initial_size)(void*, int, int);
5170LPCWSTR (*winpty_conin_name)(void*);
5171LPCWSTR (*winpty_conout_name)(void*);
5172LPCWSTR (*winpty_conerr_name)(void*);
5173void (*winpty_free)(void*);
5174void (*winpty_config_free)(void*);
5175void (*winpty_spawn_config_free)(void*);
5176void (*winpty_error_free)(void*);
5177LPCWSTR (*winpty_error_msg)(void*);
5178BOOL (*winpty_set_size)(void*, int, int, void*);
5179HANDLE (*winpty_agent_process)(void*);
5180
5181#define WINPTY_DLL "winpty.dll"
5182
5183static HINSTANCE hWinPtyDLL = NULL;
5184# endif
5185
5186 static int
5187dyn_winpty_init(int verbose)
5188{
5189 int i;
5190 static struct
5191 {
5192 char *name;
5193 FARPROC *ptr;
5194 } winpty_entry[] =
5195 {
5196 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5197 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5198 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5199 {"winpty_config_set_mouse_mode",
5200 (FARPROC*)&winpty_config_set_mouse_mode},
5201 {"winpty_config_set_initial_size",
5202 (FARPROC*)&winpty_config_set_initial_size},
5203 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5204 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5205 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5206 {"winpty_free", (FARPROC*)&winpty_free},
5207 {"winpty_open", (FARPROC*)&winpty_open},
5208 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5209 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5210 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5211 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5212 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5213 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5214 {NULL, NULL}
5215 };
5216
5217 /* No need to initialize twice. */
5218 if (hWinPtyDLL)
5219 return OK;
5220 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5221 * winpty.dll. */
5222 if (*p_winptydll != NUL)
5223 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5224 if (!hWinPtyDLL)
5225 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5226 if (!hWinPtyDLL)
5227 {
5228 if (verbose)
5229 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5230 : (char_u *)WINPTY_DLL);
5231 return FAIL;
5232 }
5233 for (i = 0; winpty_entry[i].name != NULL
5234 && winpty_entry[i].ptr != NULL; ++i)
5235 {
5236 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5237 winpty_entry[i].name)) == NULL)
5238 {
5239 if (verbose)
5240 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5241 return FAIL;
5242 }
5243 }
5244
5245 return OK;
5246}
5247
5248/*
5249 * Create a new terminal of "rows" by "cols" cells.
5250 * Store a reference in "term".
5251 * Return OK or FAIL.
5252 */
5253 static int
5254term_and_job_init(
5255 term_T *term,
5256 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005257 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005258 jobopt_T *opt)
5259{
5260 WCHAR *cmd_wchar = NULL;
5261 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005262 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005263 channel_T *channel = NULL;
5264 job_T *job = NULL;
5265 DWORD error;
5266 HANDLE jo = NULL;
5267 HANDLE child_process_handle;
5268 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005269 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005270 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005271 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005272 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005273
5274 if (dyn_winpty_init(TRUE) == FAIL)
5275 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005276 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5277 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005278
5279 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005280 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005281 cmd = argvar->vval.v_string;
5282 }
5283 else if (argvar->v_type == VAR_LIST)
5284 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005285 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005286 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005287 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005288 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005289 if (cmd == NULL || *cmd == NUL)
5290 {
5291 EMSG(_(e_invarg));
5292 goto failed;
5293 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005294
5295 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005296 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005297 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005298 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005299 if (opt->jo_cwd != NULL)
5300 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005301
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005302 win32_build_env(opt->jo_env, &ga_env, TRUE);
5303 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005304
5305 job = job_alloc();
5306 if (job == NULL)
5307 goto failed;
5308
5309 channel = add_channel();
5310 if (channel == NULL)
5311 goto failed;
5312
5313 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5314 if (term->tl_winpty_config == NULL)
5315 goto failed;
5316
5317 winpty_config_set_mouse_mode(term->tl_winpty_config,
5318 WINPTY_MOUSE_MODE_FORCE);
5319 winpty_config_set_initial_size(term->tl_winpty_config,
5320 term->tl_cols, term->tl_rows);
5321 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5322 if (term->tl_winpty == NULL)
5323 goto failed;
5324
5325 spawn_config = winpty_spawn_config_new(
5326 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5327 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5328 NULL,
5329 cmd_wchar,
5330 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005331 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005332 &winpty_err);
5333 if (spawn_config == NULL)
5334 goto failed;
5335
5336 channel = add_channel();
5337 if (channel == NULL)
5338 goto failed;
5339
5340 job = job_alloc();
5341 if (job == NULL)
5342 goto failed;
5343
5344 if (opt->jo_set & JO_IN_BUF)
5345 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5346
5347 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5348 &child_thread_handle, &error, &winpty_err))
5349 goto failed;
5350
5351 channel_set_pipes(channel,
5352 (sock_T)CreateFileW(
5353 winpty_conin_name(term->tl_winpty),
5354 GENERIC_WRITE, 0, NULL,
5355 OPEN_EXISTING, 0, NULL),
5356 (sock_T)CreateFileW(
5357 winpty_conout_name(term->tl_winpty),
5358 GENERIC_READ, 0, NULL,
5359 OPEN_EXISTING, 0, NULL),
5360 (sock_T)CreateFileW(
5361 winpty_conerr_name(term->tl_winpty),
5362 GENERIC_READ, 0, NULL,
5363 OPEN_EXISTING, 0, NULL));
5364
5365 /* Write lines with CR instead of NL. */
5366 channel->ch_write_text_mode = TRUE;
5367
5368 jo = CreateJobObject(NULL, NULL);
5369 if (jo == NULL)
5370 goto failed;
5371
5372 if (!AssignProcessToJobObject(jo, child_process_handle))
5373 {
5374 /* Failed, switch the way to terminate process with TerminateProcess. */
5375 CloseHandle(jo);
5376 jo = NULL;
5377 }
5378
5379 winpty_spawn_config_free(spawn_config);
5380 vim_free(cmd_wchar);
5381 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005382 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005383
5384 create_vterm(term, term->tl_rows, term->tl_cols);
5385
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005386#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5387 if (opt->jo_set2 & JO2_ANSI_COLORS)
5388 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5389 else
5390 init_vterm_ansi_colors(term->tl_vterm);
5391#endif
5392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005393 channel_set_job(channel, job, opt);
5394 job_set_options(job, opt);
5395
5396 job->jv_channel = channel;
5397 job->jv_proc_info.hProcess = child_process_handle;
5398 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5399 job->jv_job_object = jo;
5400 job->jv_status = JOB_STARTED;
5401 job->jv_tty_in = utf16_to_enc(
5402 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5403 job->jv_tty_out = utf16_to_enc(
5404 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5405 ++job->jv_refcount;
5406 term->tl_job = job;
5407
5408 return OK;
5409
5410failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005411 ga_clear(&ga_cmd);
5412 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005413 vim_free(cmd_wchar);
5414 vim_free(cwd_wchar);
5415 if (spawn_config != NULL)
5416 winpty_spawn_config_free(spawn_config);
5417 if (channel != NULL)
5418 channel_clear(channel);
5419 if (job != NULL)
5420 {
5421 job->jv_channel = NULL;
5422 job_cleanup(job);
5423 }
5424 term->tl_job = NULL;
5425 if (jo != NULL)
5426 CloseHandle(jo);
5427 if (term->tl_winpty != NULL)
5428 winpty_free(term->tl_winpty);
5429 term->tl_winpty = NULL;
5430 if (term->tl_winpty_config != NULL)
5431 winpty_config_free(term->tl_winpty_config);
5432 term->tl_winpty_config = NULL;
5433 if (winpty_err != NULL)
5434 {
5435 char_u *msg = utf16_to_enc(
5436 (short_u *)winpty_error_msg(winpty_err), NULL);
5437
5438 EMSG(msg);
5439 winpty_error_free(winpty_err);
5440 }
5441 return FAIL;
5442}
5443
5444 static int
5445create_pty_only(term_T *term, jobopt_T *options)
5446{
5447 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5448 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5449 char in_name[80], out_name[80];
5450 channel_T *channel = NULL;
5451
5452 create_vterm(term, term->tl_rows, term->tl_cols);
5453
5454 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5455 GetCurrentProcessId(),
5456 curbuf->b_fnum);
5457 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5458 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5459 PIPE_UNLIMITED_INSTANCES,
5460 0, 0, NMPWAIT_NOWAIT, NULL);
5461 if (hPipeIn == INVALID_HANDLE_VALUE)
5462 goto failed;
5463
5464 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5465 GetCurrentProcessId(),
5466 curbuf->b_fnum);
5467 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5468 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5469 PIPE_UNLIMITED_INSTANCES,
5470 0, 0, 0, NULL);
5471 if (hPipeOut == INVALID_HANDLE_VALUE)
5472 goto failed;
5473
5474 ConnectNamedPipe(hPipeIn, NULL);
5475 ConnectNamedPipe(hPipeOut, NULL);
5476
5477 term->tl_job = job_alloc();
5478 if (term->tl_job == NULL)
5479 goto failed;
5480 ++term->tl_job->jv_refcount;
5481
5482 /* behave like the job is already finished */
5483 term->tl_job->jv_status = JOB_FINISHED;
5484
5485 channel = add_channel();
5486 if (channel == NULL)
5487 goto failed;
5488 term->tl_job->jv_channel = channel;
5489 channel->ch_keep_open = TRUE;
5490 channel->ch_named_pipe = TRUE;
5491
5492 channel_set_pipes(channel,
5493 (sock_T)hPipeIn,
5494 (sock_T)hPipeOut,
5495 (sock_T)hPipeOut);
5496 channel_set_job(channel, term->tl_job, options);
5497 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5498 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5499
5500 return OK;
5501
5502failed:
5503 if (hPipeIn != NULL)
5504 CloseHandle(hPipeIn);
5505 if (hPipeOut != NULL)
5506 CloseHandle(hPipeOut);
5507 return FAIL;
5508}
5509
5510/*
5511 * Free the terminal emulator part of "term".
5512 */
5513 static void
5514term_free_vterm(term_T *term)
5515{
5516 if (term->tl_winpty != NULL)
5517 winpty_free(term->tl_winpty);
5518 term->tl_winpty = NULL;
5519 if (term->tl_winpty_config != NULL)
5520 winpty_config_free(term->tl_winpty_config);
5521 term->tl_winpty_config = NULL;
5522 if (term->tl_vterm != NULL)
5523 vterm_free(term->tl_vterm);
5524 term->tl_vterm = NULL;
5525}
5526
5527/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005528 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005529 */
5530 static void
5531term_report_winsize(term_T *term, int rows, int cols)
5532{
5533 if (term->tl_winpty)
5534 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5535}
5536
5537 int
5538terminal_enabled(void)
5539{
5540 return dyn_winpty_init(FALSE) == OK;
5541}
5542
5543# else
5544
5545/**************************************
5546 * 3. Unix-like implementation.
5547 */
5548
5549/*
5550 * Create a new terminal of "rows" by "cols" cells.
5551 * Start job for "cmd".
5552 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005553 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005554 * Return OK or FAIL.
5555 */
5556 static int
5557term_and_job_init(
5558 term_T *term,
5559 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005560 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005561 jobopt_T *opt)
5562{
5563 create_vterm(term, term->tl_rows, term->tl_cols);
5564
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005565#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5566 if (opt->jo_set2 & JO2_ANSI_COLORS)
5567 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5568 else
5569 init_vterm_ansi_colors(term->tl_vterm);
5570#endif
5571
Bram Moolenaar13568252018-03-16 20:46:58 +01005572 /* This may change a string in "argvar". */
5573 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005574 if (term->tl_job != NULL)
5575 ++term->tl_job->jv_refcount;
5576
5577 return term->tl_job != NULL
5578 && term->tl_job->jv_channel != NULL
5579 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5580}
5581
5582 static int
5583create_pty_only(term_T *term, jobopt_T *opt)
5584{
5585 create_vterm(term, term->tl_rows, term->tl_cols);
5586
5587 term->tl_job = job_alloc();
5588 if (term->tl_job == NULL)
5589 return FAIL;
5590 ++term->tl_job->jv_refcount;
5591
5592 /* behave like the job is already finished */
5593 term->tl_job->jv_status = JOB_FINISHED;
5594
5595 return mch_create_pty_channel(term->tl_job, opt);
5596}
5597
5598/*
5599 * Free the terminal emulator part of "term".
5600 */
5601 static void
5602term_free_vterm(term_T *term)
5603{
5604 if (term->tl_vterm != NULL)
5605 vterm_free(term->tl_vterm);
5606 term->tl_vterm = NULL;
5607}
5608
5609/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005610 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005611 */
5612 static void
5613term_report_winsize(term_T *term, int rows, int cols)
5614{
5615 /* Use an ioctl() to report the new window size to the job. */
5616 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5617 {
5618 int fd = -1;
5619 int part;
5620
5621 for (part = PART_OUT; part < PART_COUNT; ++part)
5622 {
5623 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5624 if (isatty(fd))
5625 break;
5626 }
5627 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5628 mch_signal_job(term->tl_job, (char_u *)"winch");
5629 }
5630}
5631
5632# endif
5633
5634#endif /* FEAT_TERMINAL */