blob: 09d48872da83aa68a6dee4354962e4ebea0948fe [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 Moolenaarf59c6e82018-04-10 15:59:11 +020043 * - add an optional limit for the scrollback size. When reaching it remove
44 * 10% at the start.
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010045 * - Copy text in the vterm to the Vim buffer once in a while, so that
46 * completion works.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020047 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
48 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020049 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020050 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
51 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020052 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010053 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020054 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010056 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020057 * - add test for giving error for invalid 'termsize' value.
58 * - support minimal size when 'termsize' is "rows*cols".
59 * - support minimal size when 'termsize' is empty?
60 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020061 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020062 * - For the GUI fill termios with default values, perhaps like pangoterm:
63 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020064 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
65 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020066 */
67
68#include "vim.h"
69
70#if defined(FEAT_TERMINAL) || defined(PROTO)
71
72#ifndef MIN
73# define MIN(x,y) ((x) < (y) ? (x) : (y))
74#endif
75#ifndef MAX
76# define MAX(x,y) ((x) > (y) ? (x) : (y))
77#endif
78
79#include "libvterm/include/vterm.h"
80
81/* This is VTermScreenCell without the characters, thus much smaller. */
82typedef struct {
83 VTermScreenCellAttrs attrs;
84 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010085 VTermColor fg;
86 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087} cellattr_T;
88
89typedef struct sb_line_S {
90 int sb_cols; /* can differ per line */
91 cellattr_T *sb_cells; /* allocated */
92 cellattr_T sb_fill_attr; /* for short line */
93} sb_line_T;
94
95/* typedef term_T in structs.h */
96struct terminal_S {
97 term_T *tl_next;
98
99 VTerm *tl_vterm;
100 job_T *tl_job;
101 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100102#if defined(FEAT_GUI)
103 int tl_system; /* when non-zero used for :!cmd output */
104 int tl_toprow; /* row with first line of system terminal */
105#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200106
107 /* Set when setting the size of a vterm, reset after redrawing. */
108 int tl_vterm_size_changed;
109
110 /* used when tl_job is NULL and only a pty was created */
111 int tl_tty_fd;
112 char_u *tl_tty_in;
113 char_u *tl_tty_out;
114
115 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
116 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100117 int tl_finish;
118#define TL_FINISH_UNSET NUL
119#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
120#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
121#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200122 char_u *tl_opencmd;
123 char_u *tl_eof_chars;
124
125#ifdef WIN3264
126 void *tl_winpty_config;
127 void *tl_winpty;
128#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100129#if defined(FEAT_SESSION)
130 char_u *tl_command;
131#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100132 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
134 /* last known vterm size */
135 int tl_rows;
136 int tl_cols;
137 /* vterm size does not follow window size */
138 int tl_rows_fixed;
139 int tl_cols_fixed;
140
141 char_u *tl_title; /* NULL or allocated */
142 char_u *tl_status_text; /* NULL or allocated */
143
144 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200145 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200146 int tl_dirty_row_end; /* row below last one to update */
147
148 garray_T tl_scrollback;
149 int tl_scrollback_scrolled;
150 cellattr_T tl_default_color;
151
Bram Moolenaard96ff162018-02-18 22:13:29 +0100152 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
153 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
154
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200155 VTermPos tl_cursor_pos;
156 int tl_cursor_visible;
157 int tl_cursor_blink;
158 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
159 char_u *tl_cursor_color; /* NULL or allocated */
160
161 int tl_using_altscreen;
162};
163
164#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
165#define TMODE_LOOP 2 /* CTRL-W N used */
166
167/*
168 * List of all active terminals.
169 */
170static term_T *first_term = NULL;
171
172/* Terminal active in terminal_loop(). */
173static term_T *in_terminal_loop = NULL;
174
175#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
176#define KEY_BUF_LEN 200
177
178/*
179 * Functions with separate implementation for MS-Windows and Unix-like systems.
180 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100181static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200182static int create_pty_only(term_T *term, jobopt_T *opt);
183static void term_report_winsize(term_T *term, int rows, int cols);
184static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100185#ifdef FEAT_GUI
186static void update_system_term(term_T *term);
187#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100189/* The character that we know (or assume) that the terminal expects for the
190 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200191static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200192
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100193/* "Terminal" highlight group colors. */
194static int term_default_cterm_fg = -1;
195static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200196
Bram Moolenaard317b382018-02-08 22:33:31 +0100197/* Store the last set and the desired cursor properties, so that we only update
198 * them when needed. Doing it unnecessary may result in flicker. */
199static char_u *last_set_cursor_color = (char_u *)"";
200static char_u *desired_cursor_color = (char_u *)"";
201static int last_set_cursor_shape = -1;
202static int desired_cursor_shape = -1;
203static int last_set_cursor_blink = -1;
204static int desired_cursor_blink = -1;
205
206
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200207/**************************************
208 * 1. Generic code for all systems.
209 */
210
211/*
212 * Determine the terminal size from 'termsize' and the current window.
213 * Assumes term->tl_rows and term->tl_cols are zero.
214 */
215 static void
216set_term_and_win_size(term_T *term)
217{
Bram Moolenaar13568252018-03-16 20:46:58 +0100218#ifdef FEAT_GUI
219 if (term->tl_system)
220 {
221 /* Use the whole screen for the system command. However, it will start
222 * at the command line and scroll up as needed, using tl_toprow. */
223 term->tl_rows = Rows;
224 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200225 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100226 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100227#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200228 if (*curwin->w_p_tms != NUL)
229 {
230 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
231
232 term->tl_rows = atoi((char *)curwin->w_p_tms);
233 term->tl_cols = atoi((char *)p);
234 }
235 if (term->tl_rows == 0)
236 term->tl_rows = curwin->w_height;
237 else
238 {
239 win_setheight_win(term->tl_rows, curwin);
240 term->tl_rows_fixed = TRUE;
241 }
242 if (term->tl_cols == 0)
243 term->tl_cols = curwin->w_width;
244 else
245 {
246 win_setwidth_win(term->tl_cols, curwin);
247 term->tl_cols_fixed = TRUE;
248 }
249}
250
251/*
252 * Initialize job options for a terminal job.
253 * Caller may overrule some of them.
254 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100255 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200256init_job_options(jobopt_T *opt)
257{
258 clear_job_options(opt);
259
260 opt->jo_mode = MODE_RAW;
261 opt->jo_out_mode = MODE_RAW;
262 opt->jo_err_mode = MODE_RAW;
263 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
264}
265
266/*
267 * Set job options mandatory for a terminal job.
268 */
269 static void
270setup_job_options(jobopt_T *opt, int rows, int cols)
271{
272 if (!(opt->jo_set & JO_OUT_IO))
273 {
274 /* Connect stdout to the terminal. */
275 opt->jo_io[PART_OUT] = JIO_BUFFER;
276 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
277 opt->jo_modifiable[PART_OUT] = 0;
278 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
279 }
280
281 if (!(opt->jo_set & JO_ERR_IO))
282 {
283 /* Connect stderr to the terminal. */
284 opt->jo_io[PART_ERR] = JIO_BUFFER;
285 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
286 opt->jo_modifiable[PART_ERR] = 0;
287 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
288 }
289
290 opt->jo_pty = TRUE;
291 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
292 opt->jo_term_rows = rows;
293 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
294 opt->jo_term_cols = cols;
295}
296
297/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100298 * Close a terminal buffer (and its window). Used when creating the terminal
299 * fails.
300 */
301 static void
302term_close_buffer(buf_T *buf, buf_T *old_curbuf)
303{
304 free_terminal(buf);
305 if (old_curbuf != NULL)
306 {
307 --curbuf->b_nwindows;
308 curbuf = old_curbuf;
309 curwin->w_buffer = curbuf;
310 ++curbuf->b_nwindows;
311 }
312
313 /* Wiping out the buffer will also close the window and call
314 * free_terminal(). */
315 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
316}
317
318/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200319 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100320 * Use either "argvar" or "argv", the other must be NULL.
321 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
322 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200323 * Returns NULL when failed.
324 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100325 buf_T *
326term_start(
327 typval_T *argvar,
328 char **argv,
329 jobopt_T *opt,
330 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200331{
332 exarg_T split_ea;
333 win_T *old_curwin = curwin;
334 term_T *term;
335 buf_T *old_curbuf = NULL;
336 int res;
337 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100338 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339
340 if (check_restricted() || check_secure())
341 return NULL;
342
343 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
344 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
345 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
346 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
347 {
348 EMSG(_(e_invarg));
349 return NULL;
350 }
351
352 term = (term_T *)alloc_clear(sizeof(term_T));
353 if (term == NULL)
354 return NULL;
355 term->tl_dirty_row_end = MAX_ROW;
356 term->tl_cursor_visible = TRUE;
357 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
358 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100359#ifdef FEAT_GUI
360 term->tl_system = (flags & TERM_START_SYSTEM);
361#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200362 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
363
364 vim_memset(&split_ea, 0, sizeof(split_ea));
365 if (opt->jo_curwin)
366 {
367 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100368 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200369 {
370 no_write_message();
371 vim_free(term);
372 return NULL;
373 }
374 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100375 ECMD_HIDE
376 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
377 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200378 {
379 vim_free(term);
380 return NULL;
381 }
382 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100383 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200384 {
385 buf_T *buf;
386
387 /* Create a new buffer without a window. Make it the current buffer for
388 * a moment to be able to do the initialisations. */
389 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
390 BLN_NEW | BLN_LISTED);
391 if (buf == NULL || ml_open(buf) == FAIL)
392 {
393 vim_free(term);
394 return NULL;
395 }
396 old_curbuf = curbuf;
397 --curbuf->b_nwindows;
398 curbuf = buf;
399 curwin->w_buffer = buf;
400 ++curbuf->b_nwindows;
401 }
402 else
403 {
404 /* Open a new window or tab. */
405 split_ea.cmdidx = CMD_new;
406 split_ea.cmd = (char_u *)"new";
407 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100408 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200409 {
410 split_ea.line2 = opt->jo_term_rows;
411 split_ea.addr_count = 1;
412 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100413 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414 {
415 split_ea.line2 = opt->jo_term_cols;
416 split_ea.addr_count = 1;
417 }
418
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100419 if (vertical)
420 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200421 ex_splitview(&split_ea);
422 if (curwin == old_curwin)
423 {
424 /* split failed */
425 vim_free(term);
426 return NULL;
427 }
428 }
429 term->tl_buffer = curbuf;
430 curbuf->b_term = term;
431
432 if (!opt->jo_hidden)
433 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100434 /* Only one size was taken care of with :new, do the other one. With
435 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100436 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100438 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200439 win_setwidth(opt->jo_term_cols);
440 }
441
442 /* Link the new terminal in the list of active terminals. */
443 term->tl_next = first_term;
444 first_term = term;
445
446 if (opt->jo_term_name != NULL)
447 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100448 else if (argv != NULL)
449 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450 else
451 {
452 int i;
453 size_t len;
454 char_u *cmd, *p;
455
456 if (argvar->v_type == VAR_STRING)
457 {
458 cmd = argvar->vval.v_string;
459 if (cmd == NULL)
460 cmd = (char_u *)"";
461 else if (STRCMP(cmd, "NONE") == 0)
462 cmd = (char_u *)"pty";
463 }
464 else if (argvar->v_type != VAR_LIST
465 || argvar->vval.v_list == NULL
466 || argvar->vval.v_list->lv_len < 1
467 || (cmd = get_tv_string_chk(
468 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
469 cmd = (char_u*)"";
470
471 len = STRLEN(cmd) + 10;
472 p = alloc((int)len);
473
474 for (i = 0; p != NULL; ++i)
475 {
476 /* Prepend a ! to the command name to avoid the buffer name equals
477 * the executable, otherwise ":w!" would overwrite it. */
478 if (i == 0)
479 vim_snprintf((char *)p, len, "!%s", cmd);
480 else
481 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
482 if (buflist_findname(p) == NULL)
483 {
484 vim_free(curbuf->b_ffname);
485 curbuf->b_ffname = p;
486 break;
487 }
488 }
489 }
490 curbuf->b_fname = curbuf->b_ffname;
491
492 if (opt->jo_term_opencmd != NULL)
493 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
494
495 if (opt->jo_eof_chars != NULL)
496 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
497
498 set_string_option_direct((char_u *)"buftype", -1,
499 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
500
501 /* Mark the buffer as not modifiable. It can only be made modifiable after
502 * the job finished. */
503 curbuf->b_p_ma = FALSE;
504
505 set_term_and_win_size(term);
506 setup_job_options(opt, term->tl_rows, term->tl_cols);
507
Bram Moolenaar13568252018-03-16 20:46:58 +0100508 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100509 return curbuf;
510
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100511#if defined(FEAT_SESSION)
512 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100513 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100514 {
515 term->tl_command = vim_strsave((char_u *)"NONE");
516 }
517 else if (argvar->v_type == VAR_STRING)
518 {
519 char_u *cmd = argvar->vval.v_string;
520
521 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
522 term->tl_command = vim_strsave(cmd);
523 }
524 else if (argvar->v_type == VAR_LIST
525 && argvar->vval.v_list != NULL
526 && argvar->vval.v_list->lv_len > 0)
527 {
528 garray_T ga;
529 listitem_T *item;
530
531 ga_init2(&ga, 1, 100);
532 for (item = argvar->vval.v_list->lv_first;
533 item != NULL; item = item->li_next)
534 {
535 char_u *s = get_tv_string_chk(&item->li_tv);
536 char_u *p;
537
538 if (s == NULL)
539 break;
540 p = vim_strsave_fnameescape(s, FALSE);
541 if (p == NULL)
542 break;
543 ga_concat(&ga, p);
544 vim_free(p);
545 ga_append(&ga, ' ');
546 }
547 if (item == NULL)
548 {
549 ga_append(&ga, NUL);
550 term->tl_command = ga.ga_data;
551 }
552 else
553 ga_clear(&ga);
554 }
555#endif
556
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100557 if (opt->jo_term_kill != NULL)
558 {
559 char_u *p = skiptowhite(opt->jo_term_kill);
560
561 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
562 }
563
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200564 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100565 if (argv == NULL
566 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200567 && argvar->vval.v_string != NULL
568 && STRCMP(argvar->vval.v_string, "NONE") == 0)
569 res = create_pty_only(term, opt);
570 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100571 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572
573 newbuf = curbuf;
574 if (res == OK)
575 {
576 /* Get and remember the size we ended up with. Update the pty. */
577 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
578 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100579#ifdef FEAT_GUI
580 if (term->tl_system)
581 {
582 /* display first line below typed command */
583 term->tl_toprow = msg_row + 1;
584 term->tl_dirty_row_end = 0;
585 }
586#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587
588 /* Make sure we don't get stuck on sending keys to the job, it leads to
589 * a deadlock if the job is waiting for Vim to read. */
590 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
591
Bram Moolenaar13568252018-03-16 20:46:58 +0100592 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100593 {
594 ++curbuf->b_locked;
595 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
596 --curbuf->b_locked;
597 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100598 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599 {
600 --curbuf->b_nwindows;
601 curbuf = old_curbuf;
602 curwin->w_buffer = curbuf;
603 ++curbuf->b_nwindows;
604 }
605 }
606 else
607 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100608 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200609 return NULL;
610 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100611
Bram Moolenaar13568252018-03-16 20:46:58 +0100612 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200613 return newbuf;
614}
615
616/*
617 * ":terminal": open a terminal window and execute a job in it.
618 */
619 void
620ex_terminal(exarg_T *eap)
621{
622 typval_T argvar[2];
623 jobopt_T opt;
624 char_u *cmd;
625 char_u *tofree = NULL;
626
627 init_job_options(&opt);
628
629 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100630 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 {
632 char_u *p, *ep;
633
634 cmd += 2;
635 p = skiptowhite(cmd);
636 ep = vim_strchr(cmd, '=');
637 if (ep != NULL && ep < p)
638 p = ep;
639
640 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
641 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100642 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
643 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200644 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
645 opt.jo_term_finish = 'o';
646 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
647 opt.jo_curwin = 1;
648 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
649 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100650 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
651 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100652 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
653 && ep != NULL)
654 {
655 opt.jo_set2 |= JO2_TERM_KILL;
656 opt.jo_term_kill = ep + 1;
657 p = skiptowhite(cmd);
658 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200659 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
660 && ep != NULL && isdigit(ep[1]))
661 {
662 opt.jo_set2 |= JO2_TERM_ROWS;
663 opt.jo_term_rows = atoi((char *)ep + 1);
664 p = skiptowhite(cmd);
665 }
666 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
667 && ep != NULL && isdigit(ep[1]))
668 {
669 opt.jo_set2 |= JO2_TERM_COLS;
670 opt.jo_term_cols = atoi((char *)ep + 1);
671 p = skiptowhite(cmd);
672 }
673 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
674 && ep != NULL)
675 {
676 char_u *buf = NULL;
677 char_u *keys;
678
679 p = skiptowhite(cmd);
680 *p = NUL;
681 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
682 opt.jo_set2 |= JO2_EOF_CHARS;
683 opt.jo_eof_chars = vim_strsave(keys);
684 vim_free(buf);
685 *p = ' ';
686 }
687 else
688 {
689 if (*p)
690 *p = NUL;
691 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100692 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200693 }
694 cmd = skipwhite(p);
695 }
696 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100697 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200698 /* Make a copy of 'shell', an autocommand may change the option. */
699 tofree = cmd = vim_strsave(p_sh);
700
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100701 /* default to close when the shell exits */
702 if (opt.jo_term_finish == NUL)
703 opt.jo_term_finish = 'c';
704 }
705
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200706 if (eap->addr_count > 0)
707 {
708 /* Write lines from current buffer to the job. */
709 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
710 opt.jo_io[PART_IN] = JIO_BUFFER;
711 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
712 opt.jo_in_top = eap->line1;
713 opt.jo_in_bot = eap->line2;
714 }
715
716 argvar[0].v_type = VAR_STRING;
717 argvar[0].vval.v_string = cmd;
718 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100719 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200720 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100721
722theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200723 vim_free(opt.jo_eof_chars);
724}
725
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100726#if defined(FEAT_SESSION) || defined(PROTO)
727/*
728 * Write a :terminal command to the session file to restore the terminal in
729 * window "wp".
730 * Return FAIL if writing fails.
731 */
732 int
733term_write_session(FILE *fd, win_T *wp)
734{
735 term_T *term = wp->w_buffer->b_term;
736
737 /* Create the terminal and run the command. This is not without
738 * risk, but let's assume the user only creates a session when this
739 * will be OK. */
740 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
741 term->tl_cols, term->tl_rows) < 0)
742 return FAIL;
743 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
744 return FAIL;
745
746 return put_eol(fd);
747}
748
749/*
750 * Return TRUE if "buf" has a terminal that should be restored.
751 */
752 int
753term_should_restore(buf_T *buf)
754{
755 term_T *term = buf->b_term;
756
757 return term != NULL && (term->tl_command == NULL
758 || STRCMP(term->tl_command, "NONE") != 0);
759}
760#endif
761
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762/*
763 * Free the scrollback buffer for "term".
764 */
765 static void
766free_scrollback(term_T *term)
767{
768 int i;
769
770 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
771 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
772 ga_clear(&term->tl_scrollback);
773}
774
775/*
776 * Free a terminal and everything it refers to.
777 * Kills the job if there is one.
778 * Called when wiping out a buffer.
779 */
780 void
781free_terminal(buf_T *buf)
782{
783 term_T *term = buf->b_term;
784 term_T *tp;
785
786 if (term == NULL)
787 return;
788 if (first_term == term)
789 first_term = term->tl_next;
790 else
791 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
792 if (tp->tl_next == term)
793 {
794 tp->tl_next = term->tl_next;
795 break;
796 }
797
798 if (term->tl_job != NULL)
799 {
800 if (term->tl_job->jv_status != JOB_ENDED
801 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100802 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200803 job_stop(term->tl_job, NULL, "kill");
804 job_unref(term->tl_job);
805 }
806
807 free_scrollback(term);
808
809 term_free_vterm(term);
810 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100811#ifdef FEAT_SESSION
812 vim_free(term->tl_command);
813#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100814 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200815 vim_free(term->tl_status_text);
816 vim_free(term->tl_opencmd);
817 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100818 if (desired_cursor_color == term->tl_cursor_color)
819 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200820 vim_free(term->tl_cursor_color);
821 vim_free(term);
822 buf->b_term = NULL;
823 if (in_terminal_loop == term)
824 in_terminal_loop = NULL;
825}
826
827/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100828 * Get the part that is connected to the tty. Normally this is PART_IN, but
829 * when writing buffer lines to the job it can be another. This makes it
830 * possible to do "1,5term vim -".
831 */
832 static ch_part_T
833get_tty_part(term_T *term)
834{
835#ifdef UNIX
836 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
837 int i;
838
839 for (i = 0; i < 3; ++i)
840 {
841 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
842
843 if (isatty(fd))
844 return parts[i];
845 }
846#endif
847 return PART_IN;
848}
849
850/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200851 * Write job output "msg[len]" to the vterm.
852 */
853 static void
854term_write_job_output(term_T *term, char_u *msg, size_t len)
855{
856 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100857 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200858
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100859 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200860
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100861 /* flush vterm buffer when vterm responded to control sequence */
862 if (prevlen != vterm_output_get_buffer_current(vterm))
863 {
864 char buf[KEY_BUF_LEN];
865 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
866
867 if (curlen > 0)
868 channel_send(term->tl_job->jv_channel, get_tty_part(term),
869 (char_u *)buf, (int)curlen, NULL);
870 }
871
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200872 /* this invokes the damage callbacks */
873 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
874}
875
876 static void
877update_cursor(term_T *term, int redraw)
878{
879 if (term->tl_normal_mode)
880 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100881#ifdef FEAT_GUI
882 if (term->tl_system)
883 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
884 term->tl_cursor_pos.col);
885 else
886#endif
887 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200888 if (redraw)
889 {
890 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
891 cursor_on();
892 out_flush();
893#ifdef FEAT_GUI
894 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100895 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200896 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100897 gui_mch_flush();
898 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899#endif
900 }
901}
902
903/*
904 * Invoked when "msg" output from a job was received. Write it to the terminal
905 * of "buffer".
906 */
907 void
908write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
909{
910 size_t len = STRLEN(msg);
911 term_T *term = buffer->b_term;
912
913 if (term->tl_vterm == NULL)
914 {
915 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
916 return;
917 }
918 ch_log(channel, "writing %d bytes to terminal", (int)len);
919 term_write_job_output(term, msg, len);
920
Bram Moolenaar13568252018-03-16 20:46:58 +0100921#ifdef FEAT_GUI
922 if (term->tl_system)
923 {
924 /* show system output, scrolling up the screen as needed */
925 update_system_term(term);
926 update_cursor(term, TRUE);
927 }
928 else
929#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200930 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
931 * contents, thus no screen update is needed. */
932 if (!term->tl_normal_mode)
933 {
934 /* TODO: only update once in a while. */
935 ch_log(term->tl_job->jv_channel, "updating screen");
936 if (buffer == curbuf)
937 {
938 update_screen(0);
939 update_cursor(term, TRUE);
940 }
941 else
942 redraw_after_callback(TRUE);
943 }
944}
945
946/*
947 * Send a mouse position and click to the vterm
948 */
949 static int
950term_send_mouse(VTerm *vterm, int button, int pressed)
951{
952 VTermModifier mod = VTERM_MOD_NONE;
953
954 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200955 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100956 if (button != 0)
957 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200958 return TRUE;
959}
960
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100961static int enter_mouse_col = -1;
962static int enter_mouse_row = -1;
963
964/*
965 * Handle a mouse click, drag or release.
966 * Return TRUE when a mouse event is sent to the terminal.
967 */
968 static int
969term_mouse_click(VTerm *vterm, int key)
970{
971#if defined(FEAT_CLIPBOARD)
972 /* For modeless selection mouse drag and release events are ignored, unless
973 * they are preceded with a mouse down event */
974 static int ignore_drag_release = TRUE;
975 VTermMouseState mouse_state;
976
977 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
978 if (mouse_state.flags == 0)
979 {
980 /* Terminal is not using the mouse, use modeless selection. */
981 switch (key)
982 {
983 case K_LEFTDRAG:
984 case K_LEFTRELEASE:
985 case K_RIGHTDRAG:
986 case K_RIGHTRELEASE:
987 /* Ignore drag and release events when the button-down wasn't
988 * seen before. */
989 if (ignore_drag_release)
990 {
991 int save_mouse_col, save_mouse_row;
992
993 if (enter_mouse_col < 0)
994 break;
995
996 /* mouse click in the window gave us focus, handle that
997 * click now */
998 save_mouse_col = mouse_col;
999 save_mouse_row = mouse_row;
1000 mouse_col = enter_mouse_col;
1001 mouse_row = enter_mouse_row;
1002 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1003 mouse_col = save_mouse_col;
1004 mouse_row = save_mouse_row;
1005 }
1006 /* FALLTHROUGH */
1007 case K_LEFTMOUSE:
1008 case K_RIGHTMOUSE:
1009 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1010 ignore_drag_release = TRUE;
1011 else
1012 ignore_drag_release = FALSE;
1013 /* Should we call mouse_has() here? */
1014 if (clip_star.available)
1015 {
1016 int button, is_click, is_drag;
1017
1018 button = get_mouse_button(KEY2TERMCAP1(key),
1019 &is_click, &is_drag);
1020 if (mouse_model_popup() && button == MOUSE_LEFT
1021 && (mod_mask & MOD_MASK_SHIFT))
1022 {
1023 /* Translate shift-left to right button. */
1024 button = MOUSE_RIGHT;
1025 mod_mask &= ~MOD_MASK_SHIFT;
1026 }
1027 clip_modeless(button, is_click, is_drag);
1028 }
1029 break;
1030
1031 case K_MIDDLEMOUSE:
1032 if (clip_star.available)
1033 insert_reg('*', TRUE);
1034 break;
1035 }
1036 enter_mouse_col = -1;
1037 return FALSE;
1038 }
1039#endif
1040 enter_mouse_col = -1;
1041
1042 switch (key)
1043 {
1044 case K_LEFTMOUSE:
1045 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1046 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1047 case K_LEFTRELEASE:
1048 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1049 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1050 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1051 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1052 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1053 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1054 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1055 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1056 }
1057 return TRUE;
1058}
1059
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001060/*
1061 * Convert typed key "c" into bytes to send to the job.
1062 * Return the number of bytes in "buf".
1063 */
1064 static int
1065term_convert_key(term_T *term, int c, char *buf)
1066{
1067 VTerm *vterm = term->tl_vterm;
1068 VTermKey key = VTERM_KEY_NONE;
1069 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001070 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071
1072 switch (c)
1073 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001074 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1075
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001076 /* don't use VTERM_KEY_BACKSPACE, it always
1077 * becomes 0x7f DEL */
1078 case K_BS: c = term_backspace_char; break;
1079
1080 case ESC: key = VTERM_KEY_ESCAPE; break;
1081 case K_DEL: key = VTERM_KEY_DEL; break;
1082 case K_DOWN: key = VTERM_KEY_DOWN; break;
1083 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1084 key = VTERM_KEY_DOWN; break;
1085 case K_END: key = VTERM_KEY_END; break;
1086 case K_S_END: mod = VTERM_MOD_SHIFT;
1087 key = VTERM_KEY_END; break;
1088 case K_C_END: mod = VTERM_MOD_CTRL;
1089 key = VTERM_KEY_END; break;
1090 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1091 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1092 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1093 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1094 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1095 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1096 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1097 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1098 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1099 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1100 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1101 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1102 case K_HOME: key = VTERM_KEY_HOME; break;
1103 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1104 key = VTERM_KEY_HOME; break;
1105 case K_C_HOME: mod = VTERM_MOD_CTRL;
1106 key = VTERM_KEY_HOME; break;
1107 case K_INS: key = VTERM_KEY_INS; break;
1108 case K_K0: key = VTERM_KEY_KP_0; break;
1109 case K_K1: key = VTERM_KEY_KP_1; break;
1110 case K_K2: key = VTERM_KEY_KP_2; break;
1111 case K_K3: key = VTERM_KEY_KP_3; break;
1112 case K_K4: key = VTERM_KEY_KP_4; break;
1113 case K_K5: key = VTERM_KEY_KP_5; break;
1114 case K_K6: key = VTERM_KEY_KP_6; break;
1115 case K_K7: key = VTERM_KEY_KP_7; break;
1116 case K_K8: key = VTERM_KEY_KP_8; break;
1117 case K_K9: key = VTERM_KEY_KP_9; break;
1118 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1119 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1120 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1121 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1122 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1123 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1124 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1125 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1126 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1127 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1128 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1129 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1130 case K_LEFT: key = VTERM_KEY_LEFT; break;
1131 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1132 key = VTERM_KEY_LEFT; break;
1133 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1134 key = VTERM_KEY_LEFT; break;
1135 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1136 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1137 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1138 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1139 key = VTERM_KEY_RIGHT; break;
1140 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1141 key = VTERM_KEY_RIGHT; break;
1142 case K_UP: key = VTERM_KEY_UP; break;
1143 case K_S_UP: mod = VTERM_MOD_SHIFT;
1144 key = VTERM_KEY_UP; break;
1145 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001146 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1147 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001148
Bram Moolenaara42ad572017-11-16 13:08:04 +01001149 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1150 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001151 case K_MOUSELEFT: /* TODO */ return 0;
1152 case K_MOUSERIGHT: /* TODO */ return 0;
1153
1154 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001155 case K_LEFTMOUSE_NM:
1156 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001157 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001158 case K_LEFTRELEASE_NM:
1159 case K_MOUSEMOVE:
1160 case K_MIDDLEMOUSE:
1161 case K_MIDDLEDRAG:
1162 case K_MIDDLERELEASE:
1163 case K_RIGHTMOUSE:
1164 case K_RIGHTDRAG:
1165 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1166 return 0;
1167 other = TRUE;
1168 break;
1169
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001170 case K_X1MOUSE: /* TODO */ return 0;
1171 case K_X1DRAG: /* TODO */ return 0;
1172 case K_X1RELEASE: /* TODO */ return 0;
1173 case K_X2MOUSE: /* TODO */ return 0;
1174 case K_X2DRAG: /* TODO */ return 0;
1175 case K_X2RELEASE: /* TODO */ return 0;
1176
1177 case K_IGNORE: return 0;
1178 case K_NOP: return 0;
1179 case K_UNDO: return 0;
1180 case K_HELP: return 0;
1181 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1182 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1183 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1184 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1185 case K_SELECT: return 0;
1186#ifdef FEAT_GUI
1187 case K_VER_SCROLLBAR: return 0;
1188 case K_HOR_SCROLLBAR: return 0;
1189#endif
1190#ifdef FEAT_GUI_TABLINE
1191 case K_TABLINE: return 0;
1192 case K_TABMENU: return 0;
1193#endif
1194#ifdef FEAT_NETBEANS_INTG
1195 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1196#endif
1197#ifdef FEAT_DND
1198 case K_DROP: return 0;
1199#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001201 case K_PS: vterm_keyboard_start_paste(vterm);
1202 other = TRUE;
1203 break;
1204 case K_PE: vterm_keyboard_end_paste(vterm);
1205 other = TRUE;
1206 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001207 }
1208
1209 /*
1210 * Convert special keys to vterm keys:
1211 * - Write keys to vterm: vterm_keyboard_key()
1212 * - Write output to channel.
1213 * TODO: use mod_mask
1214 */
1215 if (key != VTERM_KEY_NONE)
1216 /* Special key, let vterm convert it. */
1217 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001218 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001219 /* Normal character, let vterm convert it. */
1220 vterm_keyboard_unichar(vterm, c, mod);
1221
1222 /* Read back the converted escape sequence. */
1223 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1224}
1225
1226/*
1227 * Return TRUE if the job for "term" is still running.
1228 */
1229 int
1230term_job_running(term_T *term)
1231{
1232 /* Also consider the job finished when the channel is closed, to avoid a
1233 * race condition when updating the title. */
1234 return term != NULL
1235 && term->tl_job != NULL
1236 && channel_is_open(term->tl_job->jv_channel)
1237 && (term->tl_job->jv_status == JOB_STARTED
1238 || term->tl_job->jv_channel->ch_keep_open);
1239}
1240
1241/*
1242 * Return TRUE if "term" has an active channel and used ":term NONE".
1243 */
1244 int
1245term_none_open(term_T *term)
1246{
1247 /* Also consider the job finished when the channel is closed, to avoid a
1248 * race condition when updating the title. */
1249 return term != NULL
1250 && term->tl_job != NULL
1251 && channel_is_open(term->tl_job->jv_channel)
1252 && term->tl_job->jv_channel->ch_keep_open;
1253}
1254
1255/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001256 * Used when exiting: kill the job in "buf" if so desired.
1257 * Return OK when the job finished.
1258 * Return FAIL when the job is still running.
1259 */
1260 int
1261term_try_stop_job(buf_T *buf)
1262{
1263 int count;
1264 char *how = (char *)buf->b_term->tl_kill;
1265
1266#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1267 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1268 {
1269 char_u buff[DIALOG_MSG_SIZE];
1270 int ret;
1271
1272 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1273 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1274 if (ret == VIM_YES)
1275 how = "kill";
1276 else if (ret == VIM_CANCEL)
1277 return FAIL;
1278 }
1279#endif
1280 if (how == NULL || *how == NUL)
1281 return FAIL;
1282
1283 job_stop(buf->b_term->tl_job, NULL, how);
1284
1285 /* wait for up to a second for the job to die */
1286 for (count = 0; count < 100; ++count)
1287 {
1288 /* buffer, terminal and job may be cleaned up while waiting */
1289 if (!buf_valid(buf)
1290 || buf->b_term == NULL
1291 || buf->b_term->tl_job == NULL)
1292 return OK;
1293
1294 /* call job_status() to update jv_status */
1295 job_status(buf->b_term->tl_job);
1296 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1297 return OK;
1298 ui_delay(10L, FALSE);
1299 mch_check_messages();
1300 parse_queued_messages();
1301 }
1302 return FAIL;
1303}
1304
1305/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001306 * Add the last line of the scrollback buffer to the buffer in the window.
1307 */
1308 static void
1309add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1310{
1311 buf_T *buf = term->tl_buffer;
1312 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1313 linenr_T lnum = buf->b_ml.ml_line_count;
1314
1315#ifdef WIN3264
1316 if (!enc_utf8 && enc_codepage > 0)
1317 {
1318 WCHAR *ret = NULL;
1319 int length = 0;
1320
1321 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1322 &ret, &length);
1323 if (ret != NULL)
1324 {
1325 WideCharToMultiByte_alloc(enc_codepage, 0,
1326 ret, length, (char **)&text, &len, 0, 0);
1327 vim_free(ret);
1328 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1329 vim_free(text);
1330 }
1331 }
1332 else
1333#endif
1334 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1335 if (empty)
1336 {
1337 /* Delete the empty line that was in the empty buffer. */
1338 curbuf = buf;
1339 ml_delete(1, FALSE);
1340 curbuf = curwin->w_buffer;
1341 }
1342}
1343
1344 static void
1345cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1346{
1347 attr->width = cell->width;
1348 attr->attrs = cell->attrs;
1349 attr->fg = cell->fg;
1350 attr->bg = cell->bg;
1351}
1352
1353 static int
1354equal_celattr(cellattr_T *a, cellattr_T *b)
1355{
1356 /* Comparing the colors should be sufficient. */
1357 return a->fg.red == b->fg.red
1358 && a->fg.green == b->fg.green
1359 && a->fg.blue == b->fg.blue
1360 && a->bg.red == b->bg.red
1361 && a->bg.green == b->bg.green
1362 && a->bg.blue == b->bg.blue;
1363}
1364
Bram Moolenaard96ff162018-02-18 22:13:29 +01001365/*
1366 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1367 * line at this position. Otherwise at the end.
1368 */
1369 static int
1370add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1371{
1372 if (ga_grow(&term->tl_scrollback, 1) == OK)
1373 {
1374 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1375 + term->tl_scrollback.ga_len;
1376
1377 if (lnum > 0)
1378 {
1379 int i;
1380
1381 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1382 {
1383 *line = *(line - 1);
1384 --line;
1385 }
1386 }
1387 line->sb_cols = 0;
1388 line->sb_cells = NULL;
1389 line->sb_fill_attr = *fill_attr;
1390 ++term->tl_scrollback.ga_len;
1391 return OK;
1392 }
1393 return FALSE;
1394}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001395
1396/*
1397 * Add the current lines of the terminal to scrollback and to the buffer.
1398 * Called after the job has ended and when switching to Terminal-Normal mode.
1399 */
1400 static void
1401move_terminal_to_buffer(term_T *term)
1402{
1403 win_T *wp;
1404 int len;
1405 int lines_skipped = 0;
1406 VTermPos pos;
1407 VTermScreenCell cell;
1408 cellattr_T fill_attr, new_fill_attr;
1409 cellattr_T *p;
1410 VTermScreen *screen;
1411
1412 if (term->tl_vterm == NULL)
1413 return;
1414 screen = vterm_obtain_screen(term->tl_vterm);
1415 fill_attr = new_fill_attr = term->tl_default_color;
1416
1417 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1418 {
1419 len = 0;
1420 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1421 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1422 && cell.chars[0] != NUL)
1423 {
1424 len = pos.col + 1;
1425 new_fill_attr = term->tl_default_color;
1426 }
1427 else
1428 /* Assume the last attr is the filler attr. */
1429 cell2cellattr(&cell, &new_fill_attr);
1430
1431 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1432 ++lines_skipped;
1433 else
1434 {
1435 while (lines_skipped > 0)
1436 {
1437 /* Line was skipped, add an empty line. */
1438 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001439 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001440 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001441 }
1442
1443 if (len == 0)
1444 p = NULL;
1445 else
1446 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1447 if ((p != NULL || len == 0)
1448 && ga_grow(&term->tl_scrollback, 1) == OK)
1449 {
1450 garray_T ga;
1451 int width;
1452 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1453 + term->tl_scrollback.ga_len;
1454
1455 ga_init2(&ga, 1, 100);
1456 for (pos.col = 0; pos.col < len; pos.col += width)
1457 {
1458 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1459 {
1460 width = 1;
1461 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1462 if (ga_grow(&ga, 1) == OK)
1463 ga.ga_len += utf_char2bytes(' ',
1464 (char_u *)ga.ga_data + ga.ga_len);
1465 }
1466 else
1467 {
1468 width = cell.width;
1469
1470 cell2cellattr(&cell, &p[pos.col]);
1471
1472 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1473 {
1474 int i;
1475 int c;
1476
1477 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1478 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1479 (char_u *)ga.ga_data + ga.ga_len);
1480 }
1481 }
1482 }
1483 line->sb_cols = len;
1484 line->sb_cells = p;
1485 line->sb_fill_attr = new_fill_attr;
1486 fill_attr = new_fill_attr;
1487 ++term->tl_scrollback.ga_len;
1488
1489 if (ga_grow(&ga, 1) == FAIL)
1490 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1491 else
1492 {
1493 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1494 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1495 }
1496 ga_clear(&ga);
1497 }
1498 else
1499 vim_free(p);
1500 }
1501 }
1502
1503 /* Obtain the current background color. */
1504 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1505 &term->tl_default_color.fg, &term->tl_default_color.bg);
1506
1507 FOR_ALL_WINDOWS(wp)
1508 {
1509 if (wp->w_buffer == term->tl_buffer)
1510 {
1511 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1512 wp->w_cursor.col = 0;
1513 wp->w_valid = 0;
1514 if (wp->w_cursor.lnum >= wp->w_height)
1515 {
1516 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1517
1518 if (wp->w_topline < min_topline)
1519 wp->w_topline = min_topline;
1520 }
1521 redraw_win_later(wp, NOT_VALID);
1522 }
1523 }
1524}
1525
1526 static void
1527set_terminal_mode(term_T *term, int normal_mode)
1528{
1529 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001530 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001531 if (term->tl_buffer == curbuf)
1532 maketitle();
1533}
1534
1535/*
1536 * Called after the job if finished and Terminal mode is not active:
1537 * Move the vterm contents into the scrollback buffer and free the vterm.
1538 */
1539 static void
1540cleanup_vterm(term_T *term)
1541{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001542 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001543 move_terminal_to_buffer(term);
1544 term_free_vterm(term);
1545 set_terminal_mode(term, FALSE);
1546}
1547
1548/*
1549 * Switch from Terminal-Job mode to Terminal-Normal mode.
1550 * Suspends updating the terminal window.
1551 */
1552 static void
1553term_enter_normal_mode(void)
1554{
1555 term_T *term = curbuf->b_term;
1556
1557 /* Append the current terminal contents to the buffer. */
1558 move_terminal_to_buffer(term);
1559
1560 set_terminal_mode(term, TRUE);
1561
1562 /* Move the window cursor to the position of the cursor in the
1563 * terminal. */
1564 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1565 + term->tl_cursor_pos.row + 1;
1566 check_cursor();
1567 coladvance(term->tl_cursor_pos.col);
1568
1569 /* Display the same lines as in the terminal. */
1570 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1571}
1572
1573/*
1574 * Returns TRUE if the current window contains a terminal and we are in
1575 * Terminal-Normal mode.
1576 */
1577 int
1578term_in_normal_mode(void)
1579{
1580 term_T *term = curbuf->b_term;
1581
1582 return term != NULL && term->tl_normal_mode;
1583}
1584
1585/*
1586 * Switch from Terminal-Normal mode to Terminal-Job mode.
1587 * Restores updating the terminal window.
1588 */
1589 void
1590term_enter_job_mode()
1591{
1592 term_T *term = curbuf->b_term;
1593 sb_line_T *line;
1594 garray_T *gap;
1595
1596 /* Remove the terminal contents from the scrollback and the buffer. */
1597 gap = &term->tl_scrollback;
1598 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1599 && gap->ga_len > 0)
1600 {
1601 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1602 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1603 vim_free(line->sb_cells);
1604 --gap->ga_len;
1605 }
1606 check_cursor();
1607
1608 set_terminal_mode(term, FALSE);
1609
1610 if (term->tl_channel_closed)
1611 cleanup_vterm(term);
1612 redraw_buf_and_status_later(curbuf, NOT_VALID);
1613}
1614
1615/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001616 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617 * Note: while waiting a terminal may be closed and freed if the channel is
1618 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619 */
1620 static int
1621term_vgetc()
1622{
1623 int c;
1624 int save_State = State;
1625
1626 State = TERMINAL;
1627 got_int = FALSE;
1628#ifdef WIN3264
1629 ctrl_break_was_pressed = FALSE;
1630#endif
1631 c = vgetc();
1632 got_int = FALSE;
1633 State = save_State;
1634 return c;
1635}
1636
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001637static int mouse_was_outside = FALSE;
1638
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001639/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001640 * Send keys to terminal.
1641 * Return FAIL when the key needs to be handled in Normal mode.
1642 * Return OK when the key was dropped or sent to the terminal.
1643 */
1644 int
1645send_keys_to_term(term_T *term, int c, int typed)
1646{
1647 char msg[KEY_BUF_LEN];
1648 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001649 int dragging_outside = FALSE;
1650
1651 /* Catch keys that need to be handled as in Normal mode. */
1652 switch (c)
1653 {
1654 case NUL:
1655 case K_ZERO:
1656 if (typed)
1657 stuffcharReadbuff(c);
1658 return FAIL;
1659
1660 case K_IGNORE:
1661 return FAIL;
1662
1663 case K_LEFTDRAG:
1664 case K_MIDDLEDRAG:
1665 case K_RIGHTDRAG:
1666 case K_X1DRAG:
1667 case K_X2DRAG:
1668 dragging_outside = mouse_was_outside;
1669 /* FALLTHROUGH */
1670 case K_LEFTMOUSE:
1671 case K_LEFTMOUSE_NM:
1672 case K_LEFTRELEASE:
1673 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001674 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001675 case K_MIDDLEMOUSE:
1676 case K_MIDDLERELEASE:
1677 case K_RIGHTMOUSE:
1678 case K_RIGHTRELEASE:
1679 case K_X1MOUSE:
1680 case K_X1RELEASE:
1681 case K_X2MOUSE:
1682 case K_X2RELEASE:
1683
1684 case K_MOUSEUP:
1685 case K_MOUSEDOWN:
1686 case K_MOUSELEFT:
1687 case K_MOUSERIGHT:
1688 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001689 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001690 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001691 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 || dragging_outside)
1693 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001694 /* click or scroll outside the current window or on status line
1695 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001696 if (typed)
1697 {
1698 stuffcharReadbuff(c);
1699 mouse_was_outside = TRUE;
1700 }
1701 return FAIL;
1702 }
1703 }
1704 if (typed)
1705 mouse_was_outside = FALSE;
1706
1707 /* Convert the typed key to a sequence of bytes for the job. */
1708 len = term_convert_key(term, c, msg);
1709 if (len > 0)
1710 /* TODO: if FAIL is returned, stop? */
1711 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1712 (char_u *)msg, (int)len, NULL);
1713
1714 return OK;
1715}
1716
1717 static void
1718position_cursor(win_T *wp, VTermPos *pos)
1719{
1720 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1721 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1722 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1723}
1724
1725/*
1726 * Handle CTRL-W "": send register contents to the job.
1727 */
1728 static void
1729term_paste_register(int prev_c UNUSED)
1730{
1731 int c;
1732 list_T *l;
1733 listitem_T *item;
1734 long reglen = 0;
1735 int type;
1736
1737#ifdef FEAT_CMDL_INFO
1738 if (add_to_showcmd(prev_c))
1739 if (add_to_showcmd('"'))
1740 out_flush();
1741#endif
1742 c = term_vgetc();
1743#ifdef FEAT_CMDL_INFO
1744 clear_showcmd();
1745#endif
1746 if (!term_use_loop())
1747 /* job finished while waiting for a character */
1748 return;
1749
1750 /* CTRL-W "= prompt for expression to evaluate. */
1751 if (c == '=' && get_expr_register() != '=')
1752 return;
1753 if (!term_use_loop())
1754 /* job finished while waiting for a character */
1755 return;
1756
1757 l = (list_T *)get_reg_contents(c, GREG_LIST);
1758 if (l != NULL)
1759 {
1760 type = get_reg_type(c, &reglen);
1761 for (item = l->lv_first; item != NULL; item = item->li_next)
1762 {
1763 char_u *s = get_tv_string(&item->li_tv);
1764#ifdef WIN3264
1765 char_u *tmp = s;
1766
1767 if (!enc_utf8 && enc_codepage > 0)
1768 {
1769 WCHAR *ret = NULL;
1770 int length = 0;
1771
1772 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1773 (int)STRLEN(s), &ret, &length);
1774 if (ret != NULL)
1775 {
1776 WideCharToMultiByte_alloc(CP_UTF8, 0,
1777 ret, length, (char **)&s, &length, 0, 0);
1778 vim_free(ret);
1779 }
1780 }
1781#endif
1782 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1783 s, (int)STRLEN(s), NULL);
1784#ifdef WIN3264
1785 if (tmp != s)
1786 vim_free(s);
1787#endif
1788
1789 if (item->li_next != NULL || type == MLINE)
1790 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1791 (char_u *)"\r", 1, NULL);
1792 }
1793 list_free(l);
1794 }
1795}
1796
1797#if defined(FEAT_GUI) || defined(PROTO)
1798/*
1799 * Return TRUE when the cursor of the terminal should be displayed.
1800 */
1801 int
1802terminal_is_active()
1803{
1804 return in_terminal_loop != NULL;
1805}
1806
1807 cursorentry_T *
1808term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1809{
1810 term_T *term = in_terminal_loop;
1811 static cursorentry_T entry;
1812
1813 vim_memset(&entry, 0, sizeof(entry));
1814 entry.shape = entry.mshape =
1815 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1816 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1817 SHAPE_BLOCK;
1818 entry.percentage = 20;
1819 if (term->tl_cursor_blink)
1820 {
1821 entry.blinkwait = 700;
1822 entry.blinkon = 400;
1823 entry.blinkoff = 250;
1824 }
1825 *fg = gui.back_pixel;
1826 if (term->tl_cursor_color == NULL)
1827 *bg = gui.norm_pixel;
1828 else
1829 *bg = color_name2handle(term->tl_cursor_color);
1830 entry.name = "n";
1831 entry.used_for = SHAPE_CURSOR;
1832
1833 return &entry;
1834}
1835#endif
1836
Bram Moolenaard317b382018-02-08 22:33:31 +01001837 static void
1838may_output_cursor_props(void)
1839{
1840 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1841 || last_set_cursor_shape != desired_cursor_shape
1842 || last_set_cursor_blink != desired_cursor_blink)
1843 {
1844 last_set_cursor_color = desired_cursor_color;
1845 last_set_cursor_shape = desired_cursor_shape;
1846 last_set_cursor_blink = desired_cursor_blink;
1847 term_cursor_color(desired_cursor_color);
1848 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1849 /* this will restore the initial cursor style, if possible */
1850 ui_cursor_shape_forced(TRUE);
1851 else
1852 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1853 }
1854}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001855
Bram Moolenaard317b382018-02-08 22:33:31 +01001856/*
1857 * Set the cursor color and shape, if not last set to these.
1858 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001859 static void
1860may_set_cursor_props(term_T *term)
1861{
1862#ifdef FEAT_GUI
1863 /* For the GUI the cursor properties are obtained with
1864 * term_get_cursor_shape(). */
1865 if (gui.in_use)
1866 return;
1867#endif
1868 if (in_terminal_loop == term)
1869 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001870 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001871 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001873 desired_cursor_color = (char_u *)"";
1874 desired_cursor_shape = term->tl_cursor_shape;
1875 desired_cursor_blink = term->tl_cursor_blink;
1876 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001877 }
1878}
1879
Bram Moolenaard317b382018-02-08 22:33:31 +01001880/*
1881 * Reset the desired cursor properties and restore them when needed.
1882 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001884prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001885{
1886#ifdef FEAT_GUI
1887 if (gui.in_use)
1888 return;
1889#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001890 desired_cursor_color = (char_u *)"";
1891 desired_cursor_shape = -1;
1892 desired_cursor_blink = -1;
1893 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001894}
1895
1896/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001897 * Called when entering a window with the mouse. If this is a terminal window
1898 * we may want to change state.
1899 */
1900 void
1901term_win_entered()
1902{
1903 term_T *term = curbuf->b_term;
1904
1905 if (term != NULL)
1906 {
1907 if (term_use_loop())
1908 {
1909 reset_VIsual_and_resel();
1910 if (State & INSERT)
1911 stop_insert_mode = TRUE;
1912 }
1913 mouse_was_outside = FALSE;
1914 enter_mouse_col = mouse_col;
1915 enter_mouse_row = mouse_row;
1916 }
1917}
1918
1919/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001920 * Returns TRUE if the current window contains a terminal and we are sending
1921 * keys to the job.
1922 */
1923 int
1924term_use_loop(void)
1925{
1926 term_T *term = curbuf->b_term;
1927
1928 return term != NULL
1929 && !term->tl_normal_mode
1930 && term->tl_vterm != NULL
1931 && term_job_running(term);
1932}
1933
1934/*
1935 * Wait for input and send it to the job.
1936 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1937 * when there is no more typahead.
1938 * Return when the start of a CTRL-W command is typed or anything else that
1939 * should be handled as a Normal mode command.
1940 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1941 * the terminal was closed.
1942 */
1943 int
1944terminal_loop(int blocking)
1945{
1946 int c;
1947 int termkey = 0;
1948 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001949#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001950 int tty_fd = curbuf->b_term->tl_job->jv_channel
1951 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001952#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001953 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001954
1955 /* Remember the terminal we are sending keys to. However, the terminal
1956 * might be closed while waiting for a character, e.g. typing "exit" in a
1957 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1958 * stored reference. */
1959 in_terminal_loop = curbuf->b_term;
1960
1961 if (*curwin->w_p_tk != NUL)
1962 termkey = string_to_key(curwin->w_p_tk, TRUE);
1963 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1964 may_set_cursor_props(curbuf->b_term);
1965
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001966 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001967 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001968#ifdef FEAT_GUI
1969 if (!curbuf->b_term->tl_system)
1970#endif
1971 /* TODO: skip screen update when handling a sequence of keys. */
1972 /* Repeat redrawing in case a message is received while redrawing.
1973 */
1974 while (must_redraw != 0)
1975 if (update_screen(0) == FAIL)
1976 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001977 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001978 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979
1980 c = term_vgetc();
1981 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001982 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001983 /* Job finished while waiting for a character. Push back the
1984 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001985 if (c != K_IGNORE)
1986 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001987 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001988 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001989 if (c == K_IGNORE)
1990 continue;
1991
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001992#ifdef UNIX
1993 /*
1994 * The shell or another program may change the tty settings. Getting
1995 * them for every typed character is a bit of overhead, but it's needed
1996 * for the first character typed, e.g. when Vim starts in a shell.
1997 */
1998 if (isatty(tty_fd))
1999 {
2000 ttyinfo_T info;
2001
2002 /* Get the current backspace character of the pty. */
2003 if (get_tty_info(tty_fd, &info) == OK)
2004 term_backspace_char = info.backspace;
2005 }
2006#endif
2007
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008#ifdef WIN3264
2009 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2010 * Use CTRL-BREAK to kill the job. */
2011 if (ctrl_break_was_pressed)
2012 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2013#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002014 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2015 * Not in a system terminal. */
2016 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2017#ifdef FEAT_GUI
2018 && !curbuf->b_term->tl_system
2019#endif
2020 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 {
2022 int prev_c = c;
2023
2024#ifdef FEAT_CMDL_INFO
2025 if (add_to_showcmd(c))
2026 out_flush();
2027#endif
2028 c = term_vgetc();
2029#ifdef FEAT_CMDL_INFO
2030 clear_showcmd();
2031#endif
2032 if (!term_use_loop())
2033 /* job finished while waiting for a character */
2034 break;
2035
2036 if (prev_c == Ctrl_BSL)
2037 {
2038 if (c == Ctrl_N)
2039 {
2040 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2041 term_enter_normal_mode();
2042 ret = FAIL;
2043 goto theend;
2044 }
2045 /* Send both keys to the terminal. */
2046 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2047 }
2048 else if (c == Ctrl_C)
2049 {
2050 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2051 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2052 }
2053 else if (termkey == 0 && c == '.')
2054 {
2055 /* "CTRL-W .": send CTRL-W to the job */
2056 c = Ctrl_W;
2057 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002058 else if (termkey == 0 && c == Ctrl_BSL)
2059 {
2060 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2061 c = Ctrl_BSL;
2062 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002063 else if (c == 'N')
2064 {
2065 /* CTRL-W N : go to Terminal-Normal mode. */
2066 term_enter_normal_mode();
2067 ret = FAIL;
2068 goto theend;
2069 }
2070 else if (c == '"')
2071 {
2072 term_paste_register(prev_c);
2073 continue;
2074 }
2075 else if (termkey == 0 || c != termkey)
2076 {
2077 stuffcharReadbuff(Ctrl_W);
2078 stuffcharReadbuff(c);
2079 ret = OK;
2080 goto theend;
2081 }
2082 }
2083# ifdef WIN3264
2084 if (!enc_utf8 && has_mbyte && c >= 0x80)
2085 {
2086 WCHAR wc;
2087 char_u mb[3];
2088
2089 mb[0] = (unsigned)c >> 8;
2090 mb[1] = c;
2091 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2092 c = wc;
2093 }
2094# endif
2095 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2096 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002097 if (c == K_MOUSEMOVE)
2098 /* We are sure to come back here, don't reset the cursor color
2099 * and shape to avoid flickering. */
2100 restore_cursor = FALSE;
2101
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 ret = OK;
2103 goto theend;
2104 }
2105 }
2106 ret = FAIL;
2107
2108theend:
2109 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002110 if (restore_cursor)
2111 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112 return ret;
2113}
2114
2115/*
2116 * Called when a job has finished.
2117 * This updates the title and status, but does not close the vterm, because
2118 * there might still be pending output in the channel.
2119 */
2120 void
2121term_job_ended(job_T *job)
2122{
2123 term_T *term;
2124 int did_one = FALSE;
2125
2126 for (term = first_term; term != NULL; term = term->tl_next)
2127 if (term->tl_job == job)
2128 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002129 VIM_CLEAR(term->tl_title);
2130 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 redraw_buf_and_status_later(term->tl_buffer, VALID);
2132 did_one = TRUE;
2133 }
2134 if (did_one)
2135 redraw_statuslines();
2136 if (curbuf->b_term != NULL)
2137 {
2138 if (curbuf->b_term->tl_job == job)
2139 maketitle();
2140 update_cursor(curbuf->b_term, TRUE);
2141 }
2142}
2143
2144 static void
2145may_toggle_cursor(term_T *term)
2146{
2147 if (in_terminal_loop == term)
2148 {
2149 if (term->tl_cursor_visible)
2150 cursor_on();
2151 else
2152 cursor_off();
2153 }
2154}
2155
2156/*
2157 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002158 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002159 */
2160 static int
2161color2index(VTermColor *color, int fg, int *boldp)
2162{
2163 int red = color->red;
2164 int blue = color->blue;
2165 int green = color->green;
2166
Bram Moolenaar46359e12017-11-29 22:33:38 +01002167 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002168 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002169 /* First 16 colors and default: use the ANSI index, because these
2170 * colors can be redefined. */
2171 if (t_colors >= 16)
2172 return color->ansi_index;
2173 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002175 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002176 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002177 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2178 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2179 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002180 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002181 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2182 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2183 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2184 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2185 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2186 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2187 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2188 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2189 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2190 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2191 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002192 }
2193 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002194
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002195 if (t_colors >= 256)
2196 {
2197 if (red == blue && red == green)
2198 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002199 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002201 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2202 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2203 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 int i;
2205
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002206 if (red < 5)
2207 return 17; /* 00/00/00 */
2208 if (red > 245) /* ff/ff/ff */
2209 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002210 for (i = 0; i < 23; ++i)
2211 if (red < cutoff[i])
2212 return i + 233;
2213 return 256;
2214 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002215 {
2216 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2217 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002218
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002219 /* 216-color cube */
2220 for (ri = 0; ri < 5; ++ri)
2221 if (red < cutoff[ri])
2222 break;
2223 for (gi = 0; gi < 5; ++gi)
2224 if (green < cutoff[gi])
2225 break;
2226 for (bi = 0; bi < 5; ++bi)
2227 if (blue < cutoff[bi])
2228 break;
2229 return 17 + ri * 36 + gi * 6 + bi;
2230 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002231 }
2232 return 0;
2233}
2234
2235/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002236 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002237 */
2238 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002239vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002240{
2241 int attr = 0;
2242
2243 if (cellattrs.bold)
2244 attr |= HL_BOLD;
2245 if (cellattrs.underline)
2246 attr |= HL_UNDERLINE;
2247 if (cellattrs.italic)
2248 attr |= HL_ITALIC;
2249 if (cellattrs.strike)
2250 attr |= HL_STRIKETHROUGH;
2251 if (cellattrs.reverse)
2252 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002253 return attr;
2254}
2255
2256/*
2257 * Store Vterm attributes in "cell" from highlight flags.
2258 */
2259 static void
2260hl2vtermAttr(int attr, cellattr_T *cell)
2261{
2262 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2263 if (attr & HL_BOLD)
2264 cell->attrs.bold = 1;
2265 if (attr & HL_UNDERLINE)
2266 cell->attrs.underline = 1;
2267 if (attr & HL_ITALIC)
2268 cell->attrs.italic = 1;
2269 if (attr & HL_STRIKETHROUGH)
2270 cell->attrs.strike = 1;
2271 if (attr & HL_INVERSE)
2272 cell->attrs.reverse = 1;
2273}
2274
2275/*
2276 * Convert the attributes of a vterm cell into an attribute index.
2277 */
2278 static int
2279cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2280{
2281 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002282
2283#ifdef FEAT_GUI
2284 if (gui.in_use)
2285 {
2286 guicolor_T fg, bg;
2287
2288 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2289 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2290 return get_gui_attr_idx(attr, fg, bg);
2291 }
2292 else
2293#endif
2294#ifdef FEAT_TERMGUICOLORS
2295 if (p_tgc)
2296 {
2297 guicolor_T fg, bg;
2298
2299 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2300 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2301
2302 return get_tgc_attr_idx(attr, fg, bg);
2303 }
2304 else
2305#endif
2306 {
2307 int bold = MAYBE;
2308 int fg = color2index(&cellfg, TRUE, &bold);
2309 int bg = color2index(&cellbg, FALSE, &bold);
2310
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002311 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002312 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002313 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002314 if (fg == 0 && term_default_cterm_fg >= 0)
2315 fg = term_default_cterm_fg + 1;
2316 if (bg == 0 && term_default_cterm_bg >= 0)
2317 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002318 }
2319
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002320 /* with 8 colors set the bold attribute to get a bright foreground */
2321 if (bold == TRUE)
2322 attr |= HL_BOLD;
2323 return get_cterm_attr_idx(attr, fg, bg);
2324 }
2325 return 0;
2326}
2327
2328 static int
2329handle_damage(VTermRect rect, void *user)
2330{
2331 term_T *term = (term_T *)user;
2332
2333 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2334 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2335 redraw_buf_later(term->tl_buffer, NOT_VALID);
2336 return 1;
2337}
2338
2339 static int
2340handle_moverect(VTermRect dest, VTermRect src, void *user)
2341{
2342 term_T *term = (term_T *)user;
2343
2344 /* Scrolling up is done much more efficiently by deleting lines instead of
2345 * redrawing the text. */
2346 if (dest.start_col == src.start_col
2347 && dest.end_col == src.end_col
2348 && dest.start_row < src.start_row)
2349 {
2350 win_T *wp;
2351 VTermColor fg, bg;
2352 VTermScreenCellAttrs attr;
2353 int clear_attr;
2354
2355 /* Set the color to clear lines with. */
2356 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2357 &fg, &bg);
2358 vim_memset(&attr, 0, sizeof(attr));
2359 clear_attr = cell2attr(attr, fg, bg);
2360
2361 FOR_ALL_WINDOWS(wp)
2362 {
2363 if (wp->w_buffer == term->tl_buffer)
2364 win_del_lines(wp, dest.start_row,
2365 src.start_row - dest.start_row, FALSE, FALSE,
2366 clear_attr);
2367 }
2368 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002369
2370 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2371 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2372
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 redraw_buf_later(term->tl_buffer, NOT_VALID);
2374 return 1;
2375}
2376
2377 static int
2378handle_movecursor(
2379 VTermPos pos,
2380 VTermPos oldpos UNUSED,
2381 int visible,
2382 void *user)
2383{
2384 term_T *term = (term_T *)user;
2385 win_T *wp;
2386
2387 term->tl_cursor_pos = pos;
2388 term->tl_cursor_visible = visible;
2389
2390 FOR_ALL_WINDOWS(wp)
2391 {
2392 if (wp->w_buffer == term->tl_buffer)
2393 position_cursor(wp, &pos);
2394 }
2395 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2396 {
2397 may_toggle_cursor(term);
2398 update_cursor(term, term->tl_cursor_visible);
2399 }
2400
2401 return 1;
2402}
2403
2404 static int
2405handle_settermprop(
2406 VTermProp prop,
2407 VTermValue *value,
2408 void *user)
2409{
2410 term_T *term = (term_T *)user;
2411
2412 switch (prop)
2413 {
2414 case VTERM_PROP_TITLE:
2415 vim_free(term->tl_title);
2416 /* a blank title isn't useful, make it empty, so that "running" is
2417 * displayed */
2418 if (*skipwhite((char_u *)value->string) == NUL)
2419 term->tl_title = NULL;
2420#ifdef WIN3264
2421 else if (!enc_utf8 && enc_codepage > 0)
2422 {
2423 WCHAR *ret = NULL;
2424 int length = 0;
2425
2426 MultiByteToWideChar_alloc(CP_UTF8, 0,
2427 (char*)value->string, (int)STRLEN(value->string),
2428 &ret, &length);
2429 if (ret != NULL)
2430 {
2431 WideCharToMultiByte_alloc(enc_codepage, 0,
2432 ret, length, (char**)&term->tl_title,
2433 &length, 0, 0);
2434 vim_free(ret);
2435 }
2436 }
2437#endif
2438 else
2439 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002440 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441 if (term == curbuf->b_term)
2442 maketitle();
2443 break;
2444
2445 case VTERM_PROP_CURSORVISIBLE:
2446 term->tl_cursor_visible = value->boolean;
2447 may_toggle_cursor(term);
2448 out_flush();
2449 break;
2450
2451 case VTERM_PROP_CURSORBLINK:
2452 term->tl_cursor_blink = value->boolean;
2453 may_set_cursor_props(term);
2454 break;
2455
2456 case VTERM_PROP_CURSORSHAPE:
2457 term->tl_cursor_shape = value->number;
2458 may_set_cursor_props(term);
2459 break;
2460
2461 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002462 if (desired_cursor_color == term->tl_cursor_color)
2463 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002464 vim_free(term->tl_cursor_color);
2465 if (*value->string == NUL)
2466 term->tl_cursor_color = NULL;
2467 else
2468 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2469 may_set_cursor_props(term);
2470 break;
2471
2472 case VTERM_PROP_ALTSCREEN:
2473 /* TODO: do anything else? */
2474 term->tl_using_altscreen = value->boolean;
2475 break;
2476
2477 default:
2478 break;
2479 }
2480 /* Always return 1, otherwise vterm doesn't store the value internally. */
2481 return 1;
2482}
2483
2484/*
2485 * The job running in the terminal resized the terminal.
2486 */
2487 static int
2488handle_resize(int rows, int cols, void *user)
2489{
2490 term_T *term = (term_T *)user;
2491 win_T *wp;
2492
2493 term->tl_rows = rows;
2494 term->tl_cols = cols;
2495 if (term->tl_vterm_size_changed)
2496 /* Size was set by vterm_set_size(), don't set the window size. */
2497 term->tl_vterm_size_changed = FALSE;
2498 else
2499 {
2500 FOR_ALL_WINDOWS(wp)
2501 {
2502 if (wp->w_buffer == term->tl_buffer)
2503 {
2504 win_setheight_win(rows, wp);
2505 win_setwidth_win(cols, wp);
2506 }
2507 }
2508 redraw_buf_later(term->tl_buffer, NOT_VALID);
2509 }
2510 return 1;
2511}
2512
2513/*
2514 * Handle a line that is pushed off the top of the screen.
2515 */
2516 static int
2517handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2518{
2519 term_T *term = (term_T *)user;
2520
2521 /* TODO: Limit the number of lines that are stored. */
2522 if (ga_grow(&term->tl_scrollback, 1) == OK)
2523 {
2524 cellattr_T *p = NULL;
2525 int len = 0;
2526 int i;
2527 int c;
2528 int col;
2529 sb_line_T *line;
2530 garray_T ga;
2531 cellattr_T fill_attr = term->tl_default_color;
2532
2533 /* do not store empty cells at the end */
2534 for (i = 0; i < cols; ++i)
2535 if (cells[i].chars[0] != 0)
2536 len = i + 1;
2537 else
2538 cell2cellattr(&cells[i], &fill_attr);
2539
2540 ga_init2(&ga, 1, 100);
2541 if (len > 0)
2542 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2543 if (p != NULL)
2544 {
2545 for (col = 0; col < len; col += cells[col].width)
2546 {
2547 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2548 {
2549 ga.ga_len = 0;
2550 break;
2551 }
2552 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2553 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2554 (char_u *)ga.ga_data + ga.ga_len);
2555 cell2cellattr(&cells[col], &p[col]);
2556 }
2557 }
2558 if (ga_grow(&ga, 1) == FAIL)
2559 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2560 else
2561 {
2562 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2563 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2564 }
2565 ga_clear(&ga);
2566
2567 line = (sb_line_T *)term->tl_scrollback.ga_data
2568 + term->tl_scrollback.ga_len;
2569 line->sb_cols = len;
2570 line->sb_cells = p;
2571 line->sb_fill_attr = fill_attr;
2572 ++term->tl_scrollback.ga_len;
2573 ++term->tl_scrollback_scrolled;
2574 }
2575 return 0; /* ignored */
2576}
2577
2578static VTermScreenCallbacks screen_callbacks = {
2579 handle_damage, /* damage */
2580 handle_moverect, /* moverect */
2581 handle_movecursor, /* movecursor */
2582 handle_settermprop, /* settermprop */
2583 NULL, /* bell */
2584 handle_resize, /* resize */
2585 handle_pushline, /* sb_pushline */
2586 NULL /* sb_popline */
2587};
2588
2589/*
2590 * Called when a channel has been closed.
2591 * If this was a channel for a terminal window then finish it up.
2592 */
2593 void
2594term_channel_closed(channel_T *ch)
2595{
2596 term_T *term;
2597 int did_one = FALSE;
2598
2599 for (term = first_term; term != NULL; term = term->tl_next)
2600 if (term->tl_job == ch->ch_job)
2601 {
2602 term->tl_channel_closed = TRUE;
2603 did_one = TRUE;
2604
Bram Moolenaard23a8232018-02-10 18:45:26 +01002605 VIM_CLEAR(term->tl_title);
2606 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002607
2608 /* Unless in Terminal-Normal mode: clear the vterm. */
2609 if (!term->tl_normal_mode)
2610 {
2611 int fnum = term->tl_buffer->b_fnum;
2612
2613 cleanup_vterm(term);
2614
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002615 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002616 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002617 aco_save_T aco;
2618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 /* ++close or term_finish == "close" */
2620 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002621 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002622 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002623 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 break;
2625 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002626 if (term->tl_finish == TL_FINISH_OPEN
2627 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628 {
2629 char buf[50];
2630
2631 /* TODO: use term_opencmd */
2632 ch_log(NULL, "terminal job finished, opening window");
2633 vim_snprintf(buf, sizeof(buf),
2634 term->tl_opencmd == NULL
2635 ? "botright sbuf %d"
2636 : (char *)term->tl_opencmd, fnum);
2637 do_cmdline_cmd((char_u *)buf);
2638 }
2639 else
2640 ch_log(NULL, "terminal job finished");
2641 }
2642
2643 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2644 }
2645 if (did_one)
2646 {
2647 redraw_statuslines();
2648
2649 /* Need to break out of vgetc(). */
2650 ins_char_typebuf(K_IGNORE);
2651 typebuf_was_filled = TRUE;
2652
2653 term = curbuf->b_term;
2654 if (term != NULL)
2655 {
2656 if (term->tl_job == ch->ch_job)
2657 maketitle();
2658 update_cursor(term, term->tl_cursor_visible);
2659 }
2660 }
2661}
2662
2663/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002664 * Fill one screen line from a line of the terminal.
2665 * Advances "pos" to past the last column.
2666 */
2667 static void
2668term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2669{
2670 int off = screen_get_current_line_off();
2671
2672 for (pos->col = 0; pos->col < max_col; )
2673 {
2674 VTermScreenCell cell;
2675 int c;
2676
2677 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2678 vim_memset(&cell, 0, sizeof(cell));
2679
2680 c = cell.chars[0];
2681 if (c == NUL)
2682 {
2683 ScreenLines[off] = ' ';
2684 if (enc_utf8)
2685 ScreenLinesUC[off] = NUL;
2686 }
2687 else
2688 {
2689 if (enc_utf8)
2690 {
2691 int i;
2692
2693 /* composing chars */
2694 for (i = 0; i < Screen_mco
2695 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2696 {
2697 ScreenLinesC[i][off] = cell.chars[i + 1];
2698 if (cell.chars[i + 1] == 0)
2699 break;
2700 }
2701 if (c >= 0x80 || (Screen_mco > 0
2702 && ScreenLinesC[0][off] != 0))
2703 {
2704 ScreenLines[off] = ' ';
2705 ScreenLinesUC[off] = c;
2706 }
2707 else
2708 {
2709 ScreenLines[off] = c;
2710 ScreenLinesUC[off] = NUL;
2711 }
2712 }
2713#ifdef WIN3264
2714 else if (has_mbyte && c >= 0x80)
2715 {
2716 char_u mb[MB_MAXBYTES+1];
2717 WCHAR wc = c;
2718
2719 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2720 (char*)mb, 2, 0, 0) > 1)
2721 {
2722 ScreenLines[off] = mb[0];
2723 ScreenLines[off + 1] = mb[1];
2724 cell.width = mb_ptr2cells(mb);
2725 }
2726 else
2727 ScreenLines[off] = c;
2728 }
2729#endif
2730 else
2731 ScreenLines[off] = c;
2732 }
2733 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2734
2735 ++pos->col;
2736 ++off;
2737 if (cell.width == 2)
2738 {
2739 if (enc_utf8)
2740 ScreenLinesUC[off] = NUL;
2741
2742 /* don't set the second byte to NUL for a DBCS encoding, it
2743 * has been set above */
2744 if (enc_utf8 || !has_mbyte)
2745 ScreenLines[off] = NUL;
2746
2747 ++pos->col;
2748 ++off;
2749 }
2750 }
2751}
2752
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002753#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002754 static void
2755update_system_term(term_T *term)
2756{
2757 VTermPos pos;
2758 VTermScreen *screen;
2759
2760 if (term->tl_vterm == NULL)
2761 return;
2762 screen = vterm_obtain_screen(term->tl_vterm);
2763
2764 /* Scroll up to make more room for terminal lines if needed. */
2765 while (term->tl_toprow > 0
2766 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2767 {
2768 int save_p_more = p_more;
2769
2770 p_more = FALSE;
2771 msg_row = Rows - 1;
2772 msg_puts((char_u *)"\n");
2773 p_more = save_p_more;
2774 --term->tl_toprow;
2775 }
2776
2777 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2778 && pos.row < Rows; ++pos.row)
2779 {
2780 if (pos.row < term->tl_rows)
2781 {
2782 int max_col = MIN(Columns, term->tl_cols);
2783
2784 term_line2screenline(screen, &pos, max_col);
2785 }
2786 else
2787 pos.col = 0;
2788
2789 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2790 }
2791
2792 term->tl_dirty_row_start = MAX_ROW;
2793 term->tl_dirty_row_end = 0;
2794 update_cursor(term, TRUE);
2795}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002796#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002797
2798/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002799 * Called to update a window that contains an active terminal.
2800 * Returns FAIL when there is no terminal running in this window or in
2801 * Terminal-Normal mode.
2802 */
2803 int
2804term_update_window(win_T *wp)
2805{
2806 term_T *term = wp->w_buffer->b_term;
2807 VTerm *vterm;
2808 VTermScreen *screen;
2809 VTermState *state;
2810 VTermPos pos;
2811
2812 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2813 return FAIL;
2814
2815 vterm = term->tl_vterm;
2816 screen = vterm_obtain_screen(vterm);
2817 state = vterm_obtain_state(vterm);
2818
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002819 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002820 {
2821 term->tl_dirty_row_start = 0;
2822 term->tl_dirty_row_end = MAX_ROW;
2823 }
2824
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002825 /*
2826 * If the window was resized a redraw will be triggered and we get here.
2827 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2828 */
2829 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2830 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2831 {
2832 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2833 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2834 win_T *twp;
2835
2836 FOR_ALL_WINDOWS(twp)
2837 {
2838 /* When more than one window shows the same terminal, use the
2839 * smallest size. */
2840 if (twp->w_buffer == term->tl_buffer)
2841 {
2842 if (!term->tl_rows_fixed && rows > twp->w_height)
2843 rows = twp->w_height;
2844 if (!term->tl_cols_fixed && cols > twp->w_width)
2845 cols = twp->w_width;
2846 }
2847 }
2848
2849 term->tl_vterm_size_changed = TRUE;
2850 vterm_set_size(vterm, rows, cols);
2851 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2852 rows);
2853 term_report_winsize(term, rows, cols);
2854 }
2855
2856 /* The cursor may have been moved when resizing. */
2857 vterm_state_get_cursorpos(state, &pos);
2858 position_cursor(wp, &pos);
2859
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002860 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2861 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002862 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002863 if (pos.row < term->tl_rows)
2864 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002865 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002866
Bram Moolenaar13568252018-03-16 20:46:58 +01002867 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002868 }
2869 else
2870 pos.col = 0;
2871
Bram Moolenaarf118d482018-03-13 13:14:00 +01002872 screen_line(wp->w_winrow + pos.row
2873#ifdef FEAT_MENU
2874 + winbar_height(wp)
2875#endif
2876 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002877 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002878 term->tl_dirty_row_start = MAX_ROW;
2879 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880
2881 return OK;
2882}
2883
2884/*
2885 * Return TRUE if "wp" is a terminal window where the job has finished.
2886 */
2887 int
2888term_is_finished(buf_T *buf)
2889{
2890 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2891}
2892
2893/*
2894 * Return TRUE if "wp" is a terminal window where the job has finished or we
2895 * are in Terminal-Normal mode, thus we show the buffer contents.
2896 */
2897 int
2898term_show_buffer(buf_T *buf)
2899{
2900 term_T *term = buf->b_term;
2901
2902 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2903}
2904
2905/*
2906 * The current buffer is going to be changed. If there is terminal
2907 * highlighting remove it now.
2908 */
2909 void
2910term_change_in_curbuf(void)
2911{
2912 term_T *term = curbuf->b_term;
2913
2914 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2915 {
2916 free_scrollback(term);
2917 redraw_buf_later(term->tl_buffer, NOT_VALID);
2918
2919 /* The buffer is now like a normal buffer, it cannot be easily
2920 * abandoned when changed. */
2921 set_string_option_direct((char_u *)"buftype", -1,
2922 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2923 }
2924}
2925
2926/*
2927 * Get the screen attribute for a position in the buffer.
2928 * Use a negative "col" to get the filler background color.
2929 */
2930 int
2931term_get_attr(buf_T *buf, linenr_T lnum, int col)
2932{
2933 term_T *term = buf->b_term;
2934 sb_line_T *line;
2935 cellattr_T *cellattr;
2936
2937 if (lnum > term->tl_scrollback.ga_len)
2938 cellattr = &term->tl_default_color;
2939 else
2940 {
2941 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2942 if (col < 0 || col >= line->sb_cols)
2943 cellattr = &line->sb_fill_attr;
2944 else
2945 cellattr = line->sb_cells + col;
2946 }
2947 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2948}
2949
2950static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002951 { 0, 0, 0, 1}, /* black */
2952 {224, 0, 0, 2}, /* dark red */
2953 { 0, 224, 0, 3}, /* dark green */
2954 {224, 224, 0, 4}, /* dark yellow / brown */
2955 { 0, 0, 224, 5}, /* dark blue */
2956 {224, 0, 224, 6}, /* dark magenta */
2957 { 0, 224, 224, 7}, /* dark cyan */
2958 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002959
Bram Moolenaar46359e12017-11-29 22:33:38 +01002960 {128, 128, 128, 9}, /* dark grey */
2961 {255, 64, 64, 10}, /* light red */
2962 { 64, 255, 64, 11}, /* light green */
2963 {255, 255, 64, 12}, /* yellow */
2964 { 64, 64, 255, 13}, /* light blue */
2965 {255, 64, 255, 14}, /* light magenta */
2966 { 64, 255, 255, 15}, /* light cyan */
2967 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968};
2969
2970static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002971 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002972};
2973
2974static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002975 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2976 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977};
2978
2979/*
2980 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002981 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002982 */
2983 static void
2984cterm_color2rgb(int nr, VTermColor *rgb)
2985{
2986 int idx;
2987
2988 if (nr < 16)
2989 {
2990 *rgb = ansi_table[nr];
2991 }
2992 else if (nr < 232)
2993 {
2994 /* 216 color cube */
2995 idx = nr - 16;
2996 rgb->blue = cube_value[idx % 6];
2997 rgb->green = cube_value[idx / 6 % 6];
2998 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002999 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 }
3001 else if (nr < 256)
3002 {
3003 /* 24 grey scale ramp */
3004 idx = nr - 232;
3005 rgb->blue = grey_ramp[idx];
3006 rgb->green = grey_ramp[idx];
3007 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003008 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009 }
3010}
3011
3012/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003013 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003014 */
3015 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003016init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003018 VTermColor *fg, *bg;
3019 int fgval, bgval;
3020 int id;
3021
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003022 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3023 term->tl_default_color.width = 1;
3024 fg = &term->tl_default_color.fg;
3025 bg = &term->tl_default_color.bg;
3026
3027 /* Vterm uses a default black background. Set it to white when
3028 * 'background' is "light". */
3029 if (*p_bg == 'l')
3030 {
3031 fgval = 0;
3032 bgval = 255;
3033 }
3034 else
3035 {
3036 fgval = 255;
3037 bgval = 0;
3038 }
3039 fg->red = fg->green = fg->blue = fgval;
3040 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003041 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003042
3043 /* The "Terminal" highlight group overrules the defaults. */
3044 id = syn_name2id((char_u *)"Terminal");
3045
Bram Moolenaar46359e12017-11-29 22:33:38 +01003046 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003047#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3048 if (0
3049# ifdef FEAT_GUI
3050 || gui.in_use
3051# endif
3052# ifdef FEAT_TERMGUICOLORS
3053 || p_tgc
3054# endif
3055 )
3056 {
3057 guicolor_T fg_rgb = INVALCOLOR;
3058 guicolor_T bg_rgb = INVALCOLOR;
3059
3060 if (id != 0)
3061 syn_id2colors(id, &fg_rgb, &bg_rgb);
3062
3063# ifdef FEAT_GUI
3064 if (gui.in_use)
3065 {
3066 if (fg_rgb == INVALCOLOR)
3067 fg_rgb = gui.norm_pixel;
3068 if (bg_rgb == INVALCOLOR)
3069 bg_rgb = gui.back_pixel;
3070 }
3071# ifdef FEAT_TERMGUICOLORS
3072 else
3073# endif
3074# endif
3075# ifdef FEAT_TERMGUICOLORS
3076 {
3077 if (fg_rgb == INVALCOLOR)
3078 fg_rgb = cterm_normal_fg_gui_color;
3079 if (bg_rgb == INVALCOLOR)
3080 bg_rgb = cterm_normal_bg_gui_color;
3081 }
3082# endif
3083 if (fg_rgb != INVALCOLOR)
3084 {
3085 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3086
3087 fg->red = (unsigned)(rgb >> 16);
3088 fg->green = (unsigned)(rgb >> 8) & 255;
3089 fg->blue = (unsigned)rgb & 255;
3090 }
3091 if (bg_rgb != INVALCOLOR)
3092 {
3093 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3094
3095 bg->red = (unsigned)(rgb >> 16);
3096 bg->green = (unsigned)(rgb >> 8) & 255;
3097 bg->blue = (unsigned)rgb & 255;
3098 }
3099 }
3100 else
3101#endif
3102 if (id != 0 && t_colors >= 16)
3103 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003104 if (term_default_cterm_fg >= 0)
3105 cterm_color2rgb(term_default_cterm_fg, fg);
3106 if (term_default_cterm_bg >= 0)
3107 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003108 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003109 else
3110 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003111#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003113#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003114
3115 /* In an MS-Windows console we know the normal colors. */
3116 if (cterm_normal_fg_color > 0)
3117 {
3118 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003119# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003120 tmp = fg->red;
3121 fg->red = fg->blue;
3122 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003123# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003125# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003126 else
3127 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003128# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003130 if (cterm_normal_bg_color > 0)
3131 {
3132 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003133# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003134 tmp = bg->red;
3135 bg->red = bg->blue;
3136 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003137# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003138 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003139# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003140 else
3141 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003142# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003143 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003144}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003145
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003146#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3147/*
3148 * Set the 16 ANSI colors from array of RGB values
3149 */
3150 static void
3151set_vterm_palette(VTerm *vterm, long_u *rgb)
3152{
3153 int index = 0;
3154 VTermState *state = vterm_obtain_state(vterm);
3155 for (; index < 16; index++)
3156 {
3157 VTermColor color;
3158 color.red = (unsigned)(rgb[index] >> 16);
3159 color.green = (unsigned)(rgb[index] >> 8) & 255;
3160 color.blue = (unsigned)rgb[index] & 255;
3161 vterm_state_set_palette_color(state, index, &color);
3162 }
3163}
3164
3165/*
3166 * Set the ANSI color palette from a list of colors
3167 */
3168 static int
3169set_ansi_colors_list(VTerm *vterm, list_T *list)
3170{
3171 int n = 0;
3172 long_u rgb[16];
3173 listitem_T *li = list->lv_first;
3174
3175 for (; li != NULL && n < 16; li = li->li_next, n++)
3176 {
3177 char_u *color_name;
3178 guicolor_T guicolor;
3179
3180 color_name = get_tv_string_chk(&li->li_tv);
3181 if (color_name == NULL)
3182 return FAIL;
3183
3184 guicolor = GUI_GET_COLOR(color_name);
3185 if (guicolor == INVALCOLOR)
3186 return FAIL;
3187
3188 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3189 }
3190
3191 if (n != 16 || li != NULL)
3192 return FAIL;
3193
3194 set_vterm_palette(vterm, rgb);
3195
3196 return OK;
3197}
3198
3199/*
3200 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3201 */
3202 static void
3203init_vterm_ansi_colors(VTerm *vterm)
3204{
3205 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3206
3207 if (var != NULL
3208 && (var->di_tv.v_type != VAR_LIST
3209 || var->di_tv.vval.v_list == NULL
3210 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3211 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3212}
3213#endif
3214
Bram Moolenaar52acb112018-03-18 19:20:22 +01003215/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003216 * Handles a "drop" command from the job in the terminal.
3217 * "item" is the file name, "item->li_next" may have options.
3218 */
3219 static void
3220handle_drop_command(listitem_T *item)
3221{
3222 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003223 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003224 int bufnr;
3225 win_T *wp;
3226 tabpage_T *tp;
3227 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003228 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003229
3230 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3231 FOR_ALL_TAB_WINDOWS(tp, wp)
3232 {
3233 if (wp->w_buffer->b_fnum == bufnr)
3234 {
3235 /* buffer is in a window already, go there */
3236 goto_tabpage_win(tp, wp);
3237 return;
3238 }
3239 }
3240
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003241 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003242
3243 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3244 && opt_item->li_tv.vval.v_dict != NULL)
3245 {
3246 dict_T *dict = opt_item->li_tv.vval.v_dict;
3247 char_u *p;
3248
3249 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3250 if (p == NULL)
3251 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3252 if (p != NULL)
3253 {
3254 if (check_ff_value(p) == FAIL)
3255 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3256 else
3257 ea.force_ff = *p;
3258 }
3259 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3260 if (p == NULL)
3261 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3262 if (p != NULL)
3263 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003264 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003265 if (ea.cmd != NULL)
3266 {
3267 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3268 ea.force_enc = 11;
3269 tofree = ea.cmd;
3270 }
3271 }
3272
3273 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3274 if (p != NULL)
3275 get_bad_opt(p, &ea);
3276
3277 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3278 ea.force_bin = FORCE_BIN;
3279 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3280 ea.force_bin = FORCE_BIN;
3281 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3282 ea.force_bin = FORCE_NOBIN;
3283 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3284 ea.force_bin = FORCE_NOBIN;
3285 }
3286
3287 /* open in new window, like ":split fname" */
3288 if (ea.cmd == NULL)
3289 ea.cmd = (char_u *)"split";
3290 ea.arg = fname;
3291 ea.cmdidx = CMD_split;
3292 ex_splitview(&ea);
3293
3294 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003295}
3296
3297/*
3298 * Handles a function call from the job running in a terminal.
3299 * "item" is the function name, "item->li_next" has the arguments.
3300 */
3301 static void
3302handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3303{
3304 char_u *func;
3305 typval_T argvars[2];
3306 typval_T rettv;
3307 int doesrange;
3308
3309 if (item->li_next == NULL)
3310 {
3311 ch_log(channel, "Missing function arguments for call");
3312 return;
3313 }
3314 func = get_tv_string(&item->li_tv);
3315
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003316 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003317 {
3318 ch_log(channel, "Invalid function name: %s", func);
3319 return;
3320 }
3321
3322 argvars[0].v_type = VAR_NUMBER;
3323 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3324 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003325 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003326 2, argvars, /* argv_func */ NULL,
3327 /* firstline */ 1, /* lastline */ 1,
3328 &doesrange, /* evaluate */ TRUE,
3329 /* partial */ NULL, /* selfdict */ NULL) == OK)
3330 {
3331 clear_tv(&rettv);
3332 ch_log(channel, "Function %s called", func);
3333 }
3334 else
3335 ch_log(channel, "Calling function %s failed", func);
3336}
3337
3338/*
3339 * Called by libvterm when it cannot recognize an OSC sequence.
3340 * We recognize a terminal API command.
3341 */
3342 static int
3343parse_osc(const char *command, size_t cmdlen, void *user)
3344{
3345 term_T *term = (term_T *)user;
3346 js_read_T reader;
3347 typval_T tv;
3348 channel_T *channel = term->tl_job == NULL ? NULL
3349 : term->tl_job->jv_channel;
3350
3351 /* We recognize only OSC 5 1 ; {command} */
3352 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3353 return 0; /* not handled */
3354
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003355 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003356 if (reader.js_buf == NULL)
3357 return 1;
3358 reader.js_fill = NULL;
3359 reader.js_used = 0;
3360 if (json_decode(&reader, &tv, 0) == OK
3361 && tv.v_type == VAR_LIST
3362 && tv.vval.v_list != NULL)
3363 {
3364 listitem_T *item = tv.vval.v_list->lv_first;
3365
3366 if (item == NULL)
3367 ch_log(channel, "Missing command");
3368 else
3369 {
3370 char_u *cmd = get_tv_string(&item->li_tv);
3371
3372 item = item->li_next;
3373 if (item == NULL)
3374 ch_log(channel, "Missing argument for %s", cmd);
3375 else if (STRCMP(cmd, "drop") == 0)
3376 handle_drop_command(item);
3377 else if (STRCMP(cmd, "call") == 0)
3378 handle_call_command(term, channel, item);
3379 else
3380 ch_log(channel, "Invalid command received: %s", cmd);
3381 }
3382 }
3383 else
3384 ch_log(channel, "Invalid JSON received");
3385
3386 vim_free(reader.js_buf);
3387 clear_tv(&tv);
3388 return 1;
3389}
3390
3391static VTermParserCallbacks parser_fallbacks = {
3392 NULL, /* text */
3393 NULL, /* control */
3394 NULL, /* escape */
3395 NULL, /* csi */
3396 parse_osc, /* osc */
3397 NULL, /* dcs */
3398 NULL /* resize */
3399};
3400
3401/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003402 * Use Vim's allocation functions for vterm so profiling works.
3403 */
3404 static void *
3405vterm_malloc(size_t size, void *data UNUSED)
3406{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003407 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003408}
3409
3410 static void
3411vterm_memfree(void *ptr, void *data UNUSED)
3412{
3413 vim_free(ptr);
3414}
3415
3416static VTermAllocatorFunctions vterm_allocator = {
3417 &vterm_malloc,
3418 &vterm_memfree
3419};
3420
3421/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003422 * Create a new vterm and initialize it.
3423 */
3424 static void
3425create_vterm(term_T *term, int rows, int cols)
3426{
3427 VTerm *vterm;
3428 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003429 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003430 VTermValue value;
3431
Bram Moolenaar756ef112018-04-10 12:04:27 +02003432 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003433 term->tl_vterm = vterm;
3434 screen = vterm_obtain_screen(vterm);
3435 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3436 /* TODO: depends on 'encoding'. */
3437 vterm_set_utf8(vterm, 1);
3438
3439 init_default_colors(term);
3440
3441 vterm_state_set_default_colors(
3442 vterm_obtain_state(vterm),
3443 &term->tl_default_color.fg,
3444 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003445
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003446 if (t_colors >= 16)
3447 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3448
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003449 /* Required to initialize most things. */
3450 vterm_screen_reset(screen, 1 /* hard */);
3451
3452 /* Allow using alternate screen. */
3453 vterm_screen_enable_altscreen(screen, 1);
3454
3455 /* For unix do not use a blinking cursor. In an xterm this causes the
3456 * cursor to blink if it's blinking in the xterm.
3457 * For Windows we respect the system wide setting. */
3458#ifdef WIN3264
3459 if (GetCaretBlinkTime() == INFINITE)
3460 value.boolean = 0;
3461 else
3462 value.boolean = 1;
3463#else
3464 value.boolean = 0;
3465#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003466 state = vterm_obtain_state(vterm);
3467 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3468 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003469}
3470
3471/*
3472 * Return the text to show for the buffer name and status.
3473 */
3474 char_u *
3475term_get_status_text(term_T *term)
3476{
3477 if (term->tl_status_text == NULL)
3478 {
3479 char_u *txt;
3480 size_t len;
3481
3482 if (term->tl_normal_mode)
3483 {
3484 if (term_job_running(term))
3485 txt = (char_u *)_("Terminal");
3486 else
3487 txt = (char_u *)_("Terminal-finished");
3488 }
3489 else if (term->tl_title != NULL)
3490 txt = term->tl_title;
3491 else if (term_none_open(term))
3492 txt = (char_u *)_("active");
3493 else if (term_job_running(term))
3494 txt = (char_u *)_("running");
3495 else
3496 txt = (char_u *)_("finished");
3497 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3498 term->tl_status_text = alloc((int)len);
3499 if (term->tl_status_text != NULL)
3500 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3501 term->tl_buffer->b_fname, txt);
3502 }
3503 return term->tl_status_text;
3504}
3505
3506/*
3507 * Mark references in jobs of terminals.
3508 */
3509 int
3510set_ref_in_term(int copyID)
3511{
3512 int abort = FALSE;
3513 term_T *term;
3514 typval_T tv;
3515
3516 for (term = first_term; term != NULL; term = term->tl_next)
3517 if (term->tl_job != NULL)
3518 {
3519 tv.v_type = VAR_JOB;
3520 tv.vval.v_job = term->tl_job;
3521 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3522 }
3523 return abort;
3524}
3525
3526/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003527 * Cache "Terminal" highlight group colors.
3528 */
3529 void
3530set_terminal_default_colors(int cterm_fg, int cterm_bg)
3531{
3532 term_default_cterm_fg = cterm_fg - 1;
3533 term_default_cterm_bg = cterm_bg - 1;
3534}
3535
3536/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003537 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003538 * Returns NULL when the buffer is not for a terminal window and logs a message
3539 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003540 */
3541 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003542term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003543{
3544 buf_T *buf;
3545
3546 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3547 ++emsg_off;
3548 buf = get_buf_tv(&argvars[0], FALSE);
3549 --emsg_off;
3550 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003551 {
3552 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003553 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003554 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003555 return buf;
3556}
3557
Bram Moolenaard96ff162018-02-18 22:13:29 +01003558 static int
3559same_color(VTermColor *a, VTermColor *b)
3560{
3561 return a->red == b->red
3562 && a->green == b->green
3563 && a->blue == b->blue
3564 && a->ansi_index == b->ansi_index;
3565}
3566
3567 static void
3568dump_term_color(FILE *fd, VTermColor *color)
3569{
3570 fprintf(fd, "%02x%02x%02x%d",
3571 (int)color->red, (int)color->green, (int)color->blue,
3572 (int)color->ansi_index);
3573}
3574
3575/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003576 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003577 *
3578 * Each screen cell in full is:
3579 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3580 * {characters} is a space for an empty cell
3581 * For a double-width character "+" is changed to "*" and the next cell is
3582 * skipped.
3583 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3584 * when "&" use the same as the previous cell.
3585 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3586 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3587 * {color-idx} is a number from 0 to 255
3588 *
3589 * Screen cell with same width, attributes and color as the previous one:
3590 * |{characters}
3591 *
3592 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3593 *
3594 * Repeating the previous screen cell:
3595 * @{count}
3596 */
3597 void
3598f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3599{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003600 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003601 term_T *term;
3602 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003603 int max_height = 0;
3604 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003605 stat_T st;
3606 FILE *fd;
3607 VTermPos pos;
3608 VTermScreen *screen;
3609 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003610 VTermState *state;
3611 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003612
3613 if (check_restricted() || check_secure())
3614 return;
3615 if (buf == NULL)
3616 return;
3617 term = buf->b_term;
3618
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003619 if (argvars[2].v_type != VAR_UNKNOWN)
3620 {
3621 dict_T *d;
3622
3623 if (argvars[2].v_type != VAR_DICT)
3624 {
3625 EMSG(_(e_dictreq));
3626 return;
3627 }
3628 d = argvars[2].vval.v_dict;
3629 if (d != NULL)
3630 {
3631 max_height = get_dict_number(d, (char_u *)"rows");
3632 max_width = get_dict_number(d, (char_u *)"columns");
3633 }
3634 }
3635
Bram Moolenaard96ff162018-02-18 22:13:29 +01003636 fname = get_tv_string_chk(&argvars[1]);
3637 if (fname == NULL)
3638 return;
3639 if (mch_stat((char *)fname, &st) >= 0)
3640 {
3641 EMSG2(_("E953: File exists: %s"), fname);
3642 return;
3643 }
3644
Bram Moolenaard96ff162018-02-18 22:13:29 +01003645 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3646 {
3647 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3648 return;
3649 }
3650
3651 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3652
3653 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003654 state = vterm_obtain_state(term->tl_vterm);
3655 vterm_state_get_cursorpos(state, &cursor_pos);
3656
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003657 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3658 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003659 {
3660 int repeat = 0;
3661
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003662 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3663 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003664 {
3665 VTermScreenCell cell;
3666 int same_attr;
3667 int same_chars = TRUE;
3668 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003669 int is_cursor_pos = (pos.col == cursor_pos.col
3670 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003671
3672 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3673 vim_memset(&cell, 0, sizeof(cell));
3674
3675 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3676 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003677 int c = cell.chars[i];
3678 int pc = prev_cell.chars[i];
3679
3680 /* For the first character NUL is the same as space. */
3681 if (i == 0)
3682 {
3683 c = (c == NUL) ? ' ' : c;
3684 pc = (pc == NUL) ? ' ' : pc;
3685 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003686 if (cell.chars[i] != prev_cell.chars[i])
3687 same_chars = FALSE;
3688 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3689 break;
3690 }
3691 same_attr = vtermAttr2hl(cell.attrs)
3692 == vtermAttr2hl(prev_cell.attrs)
3693 && same_color(&cell.fg, &prev_cell.fg)
3694 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003695 if (same_chars && cell.width == prev_cell.width && same_attr
3696 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003697 {
3698 ++repeat;
3699 }
3700 else
3701 {
3702 if (repeat > 0)
3703 {
3704 fprintf(fd, "@%d", repeat);
3705 repeat = 0;
3706 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003707 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003708
3709 if (cell.chars[0] == NUL)
3710 fputs(" ", fd);
3711 else
3712 {
3713 char_u charbuf[10];
3714 int len;
3715
3716 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3717 && cell.chars[i] != NUL; ++i)
3718 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003719 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003720 fwrite(charbuf, len, 1, fd);
3721 }
3722 }
3723
3724 /* When only the characters differ we don't write anything, the
3725 * following "|", "@" or NL will indicate using the same
3726 * attributes. */
3727 if (cell.width != prev_cell.width || !same_attr)
3728 {
3729 if (cell.width == 2)
3730 {
3731 fputs("*", fd);
3732 ++pos.col;
3733 }
3734 else
3735 fputs("+", fd);
3736
3737 if (same_attr)
3738 {
3739 fputs("&", fd);
3740 }
3741 else
3742 {
3743 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3744 if (same_color(&cell.fg, &prev_cell.fg))
3745 fputs("&", fd);
3746 else
3747 {
3748 fputs("#", fd);
3749 dump_term_color(fd, &cell.fg);
3750 }
3751 if (same_color(&cell.bg, &prev_cell.bg))
3752 fputs("&", fd);
3753 else
3754 {
3755 fputs("#", fd);
3756 dump_term_color(fd, &cell.bg);
3757 }
3758 }
3759 }
3760
3761 prev_cell = cell;
3762 }
3763 }
3764 if (repeat > 0)
3765 fprintf(fd, "@%d", repeat);
3766 fputs("\n", fd);
3767 }
3768
3769 fclose(fd);
3770}
3771
3772/*
3773 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3774 */
3775 static void
3776dump_is_corrupt(garray_T *gap)
3777{
3778 ga_concat(gap, (char_u *)"CORRUPT");
3779}
3780
3781 static void
3782append_cell(garray_T *gap, cellattr_T *cell)
3783{
3784 if (ga_grow(gap, 1) == OK)
3785 {
3786 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3787 ++gap->ga_len;
3788 }
3789}
3790
3791/*
3792 * Read the dump file from "fd" and append lines to the current buffer.
3793 * Return the cell width of the longest line.
3794 */
3795 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003796read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003797{
3798 int c;
3799 garray_T ga_text;
3800 garray_T ga_cell;
3801 char_u *prev_char = NULL;
3802 int attr = 0;
3803 cellattr_T cell;
3804 term_T *term = curbuf->b_term;
3805 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003806 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003807
3808 ga_init2(&ga_text, 1, 90);
3809 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3810 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003811 cursor_pos->row = -1;
3812 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003813
3814 c = fgetc(fd);
3815 for (;;)
3816 {
3817 if (c == EOF)
3818 break;
3819 if (c == '\n')
3820 {
3821 /* End of a line: append it to the buffer. */
3822 if (ga_text.ga_data == NULL)
3823 dump_is_corrupt(&ga_text);
3824 if (ga_grow(&term->tl_scrollback, 1) == OK)
3825 {
3826 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3827 + term->tl_scrollback.ga_len;
3828
3829 if (max_cells < ga_cell.ga_len)
3830 max_cells = ga_cell.ga_len;
3831 line->sb_cols = ga_cell.ga_len;
3832 line->sb_cells = ga_cell.ga_data;
3833 line->sb_fill_attr = term->tl_default_color;
3834 ++term->tl_scrollback.ga_len;
3835 ga_init(&ga_cell);
3836
3837 ga_append(&ga_text, NUL);
3838 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3839 ga_text.ga_len, FALSE);
3840 }
3841 else
3842 ga_clear(&ga_cell);
3843 ga_text.ga_len = 0;
3844
3845 c = fgetc(fd);
3846 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003847 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003848 {
3849 int prev_len = ga_text.ga_len;
3850
Bram Moolenaar9271d052018-02-25 21:39:46 +01003851 if (c == '>')
3852 {
3853 if (cursor_pos->row != -1)
3854 dump_is_corrupt(&ga_text); /* duplicate cursor */
3855 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3856 cursor_pos->col = ga_cell.ga_len;
3857 }
3858
Bram Moolenaard96ff162018-02-18 22:13:29 +01003859 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3860 c = fgetc(fd);
3861 if (c != EOF)
3862 ga_append(&ga_text, c);
3863 for (;;)
3864 {
3865 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003866 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003867 || c == EOF || c == '\n')
3868 break;
3869 ga_append(&ga_text, c);
3870 }
3871
3872 /* save the character for repeating it */
3873 vim_free(prev_char);
3874 if (ga_text.ga_data != NULL)
3875 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3876 ga_text.ga_len - prev_len);
3877
Bram Moolenaar9271d052018-02-25 21:39:46 +01003878 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003879 {
3880 /* use all attributes from previous cell */
3881 }
3882 else if (c == '+' || c == '*')
3883 {
3884 int is_bg;
3885
3886 cell.width = c == '+' ? 1 : 2;
3887
3888 c = fgetc(fd);
3889 if (c == '&')
3890 {
3891 /* use same attr as previous cell */
3892 c = fgetc(fd);
3893 }
3894 else if (isdigit(c))
3895 {
3896 /* get the decimal attribute */
3897 attr = 0;
3898 while (isdigit(c))
3899 {
3900 attr = attr * 10 + (c - '0');
3901 c = fgetc(fd);
3902 }
3903 hl2vtermAttr(attr, &cell);
3904 }
3905 else
3906 dump_is_corrupt(&ga_text);
3907
3908 /* is_bg == 0: fg, is_bg == 1: bg */
3909 for (is_bg = 0; is_bg <= 1; ++is_bg)
3910 {
3911 if (c == '&')
3912 {
3913 /* use same color as previous cell */
3914 c = fgetc(fd);
3915 }
3916 else if (c == '#')
3917 {
3918 int red, green, blue, index = 0;
3919
3920 c = fgetc(fd);
3921 red = hex2nr(c);
3922 c = fgetc(fd);
3923 red = (red << 4) + hex2nr(c);
3924 c = fgetc(fd);
3925 green = hex2nr(c);
3926 c = fgetc(fd);
3927 green = (green << 4) + hex2nr(c);
3928 c = fgetc(fd);
3929 blue = hex2nr(c);
3930 c = fgetc(fd);
3931 blue = (blue << 4) + hex2nr(c);
3932 c = fgetc(fd);
3933 if (!isdigit(c))
3934 dump_is_corrupt(&ga_text);
3935 while (isdigit(c))
3936 {
3937 index = index * 10 + (c - '0');
3938 c = fgetc(fd);
3939 }
3940
3941 if (is_bg)
3942 {
3943 cell.bg.red = red;
3944 cell.bg.green = green;
3945 cell.bg.blue = blue;
3946 cell.bg.ansi_index = index;
3947 }
3948 else
3949 {
3950 cell.fg.red = red;
3951 cell.fg.green = green;
3952 cell.fg.blue = blue;
3953 cell.fg.ansi_index = index;
3954 }
3955 }
3956 else
3957 dump_is_corrupt(&ga_text);
3958 }
3959 }
3960 else
3961 dump_is_corrupt(&ga_text);
3962
3963 append_cell(&ga_cell, &cell);
3964 }
3965 else if (c == '@')
3966 {
3967 if (prev_char == NULL)
3968 dump_is_corrupt(&ga_text);
3969 else
3970 {
3971 int count = 0;
3972
3973 /* repeat previous character, get the count */
3974 for (;;)
3975 {
3976 c = fgetc(fd);
3977 if (!isdigit(c))
3978 break;
3979 count = count * 10 + (c - '0');
3980 }
3981
3982 while (count-- > 0)
3983 {
3984 ga_concat(&ga_text, prev_char);
3985 append_cell(&ga_cell, &cell);
3986 }
3987 }
3988 }
3989 else
3990 {
3991 dump_is_corrupt(&ga_text);
3992 c = fgetc(fd);
3993 }
3994 }
3995
3996 if (ga_text.ga_len > 0)
3997 {
3998 /* trailing characters after last NL */
3999 dump_is_corrupt(&ga_text);
4000 ga_append(&ga_text, NUL);
4001 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4002 ga_text.ga_len, FALSE);
4003 }
4004
4005 ga_clear(&ga_text);
4006 vim_free(prev_char);
4007
4008 return max_cells;
4009}
4010
4011/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004012 * Return an allocated string with at least "text_width" "=" characters and
4013 * "fname" inserted in the middle.
4014 */
4015 static char_u *
4016get_separator(int text_width, char_u *fname)
4017{
4018 int width = MAX(text_width, curwin->w_width);
4019 char_u *textline;
4020 int fname_size;
4021 char_u *p = fname;
4022 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004023 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004024
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004025 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004026 if (textline == NULL)
4027 return NULL;
4028
4029 fname_size = vim_strsize(fname);
4030 if (fname_size < width - 8)
4031 {
4032 /* enough room, don't use the full window width */
4033 width = MAX(text_width, fname_size + 8);
4034 }
4035 else if (fname_size > width - 8)
4036 {
4037 /* full name doesn't fit, use only the tail */
4038 p = gettail(fname);
4039 fname_size = vim_strsize(p);
4040 }
4041 /* skip characters until the name fits */
4042 while (fname_size > width - 8)
4043 {
4044 p += (*mb_ptr2len)(p);
4045 fname_size = vim_strsize(p);
4046 }
4047
4048 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4049 textline[i] = '=';
4050 textline[i++] = ' ';
4051
4052 STRCPY(textline + i, p);
4053 off = STRLEN(textline);
4054 textline[off] = ' ';
4055 for (i = 1; i < (width - fname_size) / 2; ++i)
4056 textline[off + i] = '=';
4057 textline[off + i] = NUL;
4058
4059 return textline;
4060}
4061
4062/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004063 * Common for "term_dumpdiff()" and "term_dumpload()".
4064 */
4065 static void
4066term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4067{
4068 jobopt_T opt;
4069 buf_T *buf;
4070 char_u buf1[NUMBUFLEN];
4071 char_u buf2[NUMBUFLEN];
4072 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004073 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004074 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004075 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004076 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004077 char_u *textline = NULL;
4078
4079 /* First open the files. If this fails bail out. */
4080 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4081 if (do_diff)
4082 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4083 if (fname1 == NULL || (do_diff && fname2 == NULL))
4084 {
4085 EMSG(_(e_invarg));
4086 return;
4087 }
4088 fd1 = mch_fopen((char *)fname1, READBIN);
4089 if (fd1 == NULL)
4090 {
4091 EMSG2(_(e_notread), fname1);
4092 return;
4093 }
4094 if (do_diff)
4095 {
4096 fd2 = mch_fopen((char *)fname2, READBIN);
4097 if (fd2 == NULL)
4098 {
4099 fclose(fd1);
4100 EMSG2(_(e_notread), fname2);
4101 return;
4102 }
4103 }
4104
4105 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004106 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4107 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4108 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4109 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4110 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004111
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004112 if (opt.jo_term_name == NULL)
4113 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004114 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004115
Bram Moolenaarb571c632018-03-21 22:27:59 +01004116 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004117 if (fname_tofree != NULL)
4118 {
4119 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4120 opt.jo_term_name = fname_tofree;
4121 }
4122 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004123
Bram Moolenaar13568252018-03-16 20:46:58 +01004124 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004125 if (buf != NULL && buf->b_term != NULL)
4126 {
4127 int i;
4128 linenr_T bot_lnum;
4129 linenr_T lnum;
4130 term_T *term = buf->b_term;
4131 int width;
4132 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004133 VTermPos cursor_pos1;
4134 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004135
Bram Moolenaar52acb112018-03-18 19:20:22 +01004136 init_default_colors(term);
4137
Bram Moolenaard96ff162018-02-18 22:13:29 +01004138 rettv->vval.v_number = buf->b_fnum;
4139
4140 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004141 width = read_dump_file(fd1, &cursor_pos1);
4142
4143 /* position the cursor */
4144 if (cursor_pos1.row >= 0)
4145 {
4146 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4147 coladvance(cursor_pos1.col);
4148 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004149
4150 /* Delete the empty line that was in the empty buffer. */
4151 ml_delete(1, FALSE);
4152
4153 /* For term_dumpload() we are done here. */
4154 if (!do_diff)
4155 goto theend;
4156
4157 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4158
Bram Moolenaar4a696342018-04-05 18:45:26 +02004159 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004160 if (textline == NULL)
4161 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004162 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4163 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4164 vim_free(textline);
4165
4166 textline = get_separator(width, fname2);
4167 if (textline == NULL)
4168 goto theend;
4169 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4170 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004171 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004172
4173 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004174 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004175 if (width2 > width)
4176 {
4177 vim_free(textline);
4178 textline = alloc(width2 + 1);
4179 if (textline == NULL)
4180 goto theend;
4181 width = width2;
4182 textline[width] = NUL;
4183 }
4184 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4185
4186 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4187 {
4188 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4189 {
4190 /* bottom part has fewer rows, fill with "-" */
4191 for (i = 0; i < width; ++i)
4192 textline[i] = '-';
4193 }
4194 else
4195 {
4196 char_u *line1;
4197 char_u *line2;
4198 char_u *p1;
4199 char_u *p2;
4200 int col;
4201 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4202 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4203 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4204 ->sb_cells;
4205
4206 /* Make a copy, getting the second line will invalidate it. */
4207 line1 = vim_strsave(ml_get(lnum));
4208 if (line1 == NULL)
4209 break;
4210 p1 = line1;
4211
4212 line2 = ml_get(lnum + bot_lnum);
4213 p2 = line2;
4214 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4215 {
4216 int len1 = utfc_ptr2len(p1);
4217 int len2 = utfc_ptr2len(p2);
4218
4219 textline[col] = ' ';
4220 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004221 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004222 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004223 else if (lnum == cursor_pos1.row + 1
4224 && col == cursor_pos1.col
4225 && (cursor_pos1.row != cursor_pos2.row
4226 || cursor_pos1.col != cursor_pos2.col))
4227 /* cursor in first but not in second */
4228 textline[col] = '>';
4229 else if (lnum == cursor_pos2.row + 1
4230 && col == cursor_pos2.col
4231 && (cursor_pos1.row != cursor_pos2.row
4232 || cursor_pos1.col != cursor_pos2.col))
4233 /* cursor in second but not in first */
4234 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004235 else if (cellattr1 != NULL && cellattr2 != NULL)
4236 {
4237 if ((cellattr1 + col)->width
4238 != (cellattr2 + col)->width)
4239 textline[col] = 'w';
4240 else if (!same_color(&(cellattr1 + col)->fg,
4241 &(cellattr2 + col)->fg))
4242 textline[col] = 'f';
4243 else if (!same_color(&(cellattr1 + col)->bg,
4244 &(cellattr2 + col)->bg))
4245 textline[col] = 'b';
4246 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4247 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4248 textline[col] = 'a';
4249 }
4250 p1 += len1;
4251 p2 += len2;
4252 /* TODO: handle different width */
4253 }
4254 vim_free(line1);
4255
4256 while (col < width)
4257 {
4258 if (*p1 == NUL && *p2 == NUL)
4259 textline[col] = '?';
4260 else if (*p1 == NUL)
4261 {
4262 textline[col] = '+';
4263 p2 += utfc_ptr2len(p2);
4264 }
4265 else
4266 {
4267 textline[col] = '-';
4268 p1 += utfc_ptr2len(p1);
4269 }
4270 ++col;
4271 }
4272 }
4273 if (add_empty_scrollback(term, &term->tl_default_color,
4274 term->tl_top_diff_rows) == OK)
4275 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4276 ++bot_lnum;
4277 }
4278
4279 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4280 {
4281 /* bottom part has more rows, fill with "+" */
4282 for (i = 0; i < width; ++i)
4283 textline[i] = '+';
4284 if (add_empty_scrollback(term, &term->tl_default_color,
4285 term->tl_top_diff_rows) == OK)
4286 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4287 ++lnum;
4288 ++bot_lnum;
4289 }
4290
4291 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004292
4293 /* looks better without wrapping */
4294 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004295 }
4296
4297theend:
4298 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004299 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004300 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004301 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004302 fclose(fd2);
4303}
4304
4305/*
4306 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4307 * bottom files.
4308 * Return FAIL when this is not possible.
4309 */
4310 int
4311term_swap_diff()
4312{
4313 term_T *term = curbuf->b_term;
4314 linenr_T line_count;
4315 linenr_T top_rows;
4316 linenr_T bot_rows;
4317 linenr_T bot_start;
4318 linenr_T lnum;
4319 char_u *p;
4320 sb_line_T *sb_line;
4321
4322 if (term == NULL
4323 || !term_is_finished(curbuf)
4324 || term->tl_top_diff_rows == 0
4325 || term->tl_scrollback.ga_len == 0)
4326 return FAIL;
4327
4328 line_count = curbuf->b_ml.ml_line_count;
4329 top_rows = term->tl_top_diff_rows;
4330 bot_rows = term->tl_bot_diff_rows;
4331 bot_start = line_count - bot_rows;
4332 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4333
4334 /* move lines from top to above the bottom part */
4335 for (lnum = 1; lnum <= top_rows; ++lnum)
4336 {
4337 p = vim_strsave(ml_get(1));
4338 if (p == NULL)
4339 return OK;
4340 ml_append(bot_start, p, 0, FALSE);
4341 ml_delete(1, FALSE);
4342 vim_free(p);
4343 }
4344
4345 /* move lines from bottom to the top */
4346 for (lnum = 1; lnum <= bot_rows; ++lnum)
4347 {
4348 p = vim_strsave(ml_get(bot_start + lnum));
4349 if (p == NULL)
4350 return OK;
4351 ml_delete(bot_start + lnum, FALSE);
4352 ml_append(lnum - 1, p, 0, FALSE);
4353 vim_free(p);
4354 }
4355
4356 if (top_rows == bot_rows)
4357 {
4358 /* rows counts are equal, can swap cell properties */
4359 for (lnum = 0; lnum < top_rows; ++lnum)
4360 {
4361 sb_line_T temp;
4362
4363 temp = *(sb_line + lnum);
4364 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4365 *(sb_line + bot_start + lnum) = temp;
4366 }
4367 }
4368 else
4369 {
4370 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4371 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4372
4373 /* need to copy cell properties into temp memory */
4374 if (temp != NULL)
4375 {
4376 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4377 mch_memmove(term->tl_scrollback.ga_data,
4378 temp + bot_start,
4379 sizeof(sb_line_T) * bot_rows);
4380 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4381 temp + top_rows,
4382 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4383 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4384 + line_count - top_rows,
4385 temp,
4386 sizeof(sb_line_T) * top_rows);
4387 vim_free(temp);
4388 }
4389 }
4390
4391 term->tl_top_diff_rows = bot_rows;
4392 term->tl_bot_diff_rows = top_rows;
4393
4394 update_screen(NOT_VALID);
4395 return OK;
4396}
4397
4398/*
4399 * "term_dumpdiff(filename, filename, options)" function
4400 */
4401 void
4402f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4403{
4404 term_load_dump(argvars, rettv, TRUE);
4405}
4406
4407/*
4408 * "term_dumpload(filename, options)" function
4409 */
4410 void
4411f_term_dumpload(typval_T *argvars, typval_T *rettv)
4412{
4413 term_load_dump(argvars, rettv, FALSE);
4414}
4415
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004416/*
4417 * "term_getaltscreen(buf)" function
4418 */
4419 void
4420f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4421{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004422 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004423
4424 if (buf == NULL)
4425 return;
4426 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4427}
4428
4429/*
4430 * "term_getattr(attr, name)" function
4431 */
4432 void
4433f_term_getattr(typval_T *argvars, typval_T *rettv)
4434{
4435 int attr;
4436 size_t i;
4437 char_u *name;
4438
4439 static struct {
4440 char *name;
4441 int attr;
4442 } attrs[] = {
4443 {"bold", HL_BOLD},
4444 {"italic", HL_ITALIC},
4445 {"underline", HL_UNDERLINE},
4446 {"strike", HL_STRIKETHROUGH},
4447 {"reverse", HL_INVERSE},
4448 };
4449
4450 attr = get_tv_number(&argvars[0]);
4451 name = get_tv_string_chk(&argvars[1]);
4452 if (name == NULL)
4453 return;
4454
4455 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4456 if (STRCMP(name, attrs[i].name) == 0)
4457 {
4458 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4459 break;
4460 }
4461}
4462
4463/*
4464 * "term_getcursor(buf)" function
4465 */
4466 void
4467f_term_getcursor(typval_T *argvars, typval_T *rettv)
4468{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004469 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004470 term_T *term;
4471 list_T *l;
4472 dict_T *d;
4473
4474 if (rettv_list_alloc(rettv) == FAIL)
4475 return;
4476 if (buf == NULL)
4477 return;
4478 term = buf->b_term;
4479
4480 l = rettv->vval.v_list;
4481 list_append_number(l, term->tl_cursor_pos.row + 1);
4482 list_append_number(l, term->tl_cursor_pos.col + 1);
4483
4484 d = dict_alloc();
4485 if (d != NULL)
4486 {
4487 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4488 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4489 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4490 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4491 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4492 ? (char_u *)"" : term->tl_cursor_color);
4493 list_append_dict(l, d);
4494 }
4495}
4496
4497/*
4498 * "term_getjob(buf)" function
4499 */
4500 void
4501f_term_getjob(typval_T *argvars, typval_T *rettv)
4502{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004503 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004504
4505 rettv->v_type = VAR_JOB;
4506 rettv->vval.v_job = NULL;
4507 if (buf == NULL)
4508 return;
4509
4510 rettv->vval.v_job = buf->b_term->tl_job;
4511 if (rettv->vval.v_job != NULL)
4512 ++rettv->vval.v_job->jv_refcount;
4513}
4514
4515 static int
4516get_row_number(typval_T *tv, term_T *term)
4517{
4518 if (tv->v_type == VAR_STRING
4519 && tv->vval.v_string != NULL
4520 && STRCMP(tv->vval.v_string, ".") == 0)
4521 return term->tl_cursor_pos.row;
4522 return (int)get_tv_number(tv) - 1;
4523}
4524
4525/*
4526 * "term_getline(buf, row)" function
4527 */
4528 void
4529f_term_getline(typval_T *argvars, typval_T *rettv)
4530{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004531 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004532 term_T *term;
4533 int row;
4534
4535 rettv->v_type = VAR_STRING;
4536 if (buf == NULL)
4537 return;
4538 term = buf->b_term;
4539 row = get_row_number(&argvars[1], term);
4540
4541 if (term->tl_vterm == NULL)
4542 {
4543 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4544
4545 /* vterm is finished, get the text from the buffer */
4546 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4547 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4548 }
4549 else
4550 {
4551 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4552 VTermRect rect;
4553 int len;
4554 char_u *p;
4555
4556 if (row < 0 || row >= term->tl_rows)
4557 return;
4558 len = term->tl_cols * MB_MAXBYTES + 1;
4559 p = alloc(len);
4560 if (p == NULL)
4561 return;
4562 rettv->vval.v_string = p;
4563
4564 rect.start_col = 0;
4565 rect.end_col = term->tl_cols;
4566 rect.start_row = row;
4567 rect.end_row = row + 1;
4568 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4569 }
4570}
4571
4572/*
4573 * "term_getscrolled(buf)" function
4574 */
4575 void
4576f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4577{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004578 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004579
4580 if (buf == NULL)
4581 return;
4582 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4583}
4584
4585/*
4586 * "term_getsize(buf)" function
4587 */
4588 void
4589f_term_getsize(typval_T *argvars, typval_T *rettv)
4590{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004591 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004592 list_T *l;
4593
4594 if (rettv_list_alloc(rettv) == FAIL)
4595 return;
4596 if (buf == NULL)
4597 return;
4598
4599 l = rettv->vval.v_list;
4600 list_append_number(l, buf->b_term->tl_rows);
4601 list_append_number(l, buf->b_term->tl_cols);
4602}
4603
4604/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004605 * "term_setsize(buf, rows, cols)" function
4606 */
4607 void
4608f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4609{
4610 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4611 term_T *term;
4612 varnumber_T rows, cols;
4613
4614 if (buf == NULL || buf->b_term->tl_vterm == NULL)
4615 return;
4616 term = buf->b_term;
4617 rows = get_tv_number(&argvars[1]);
4618 rows = rows <= 0 ? term->tl_rows : rows;
4619 cols = get_tv_number(&argvars[2]);
4620 cols = cols <= 0 ? term->tl_cols : cols;
4621 vterm_set_size(term->tl_vterm, rows, cols);
4622 /* handle_resize() will resize the windows */
4623
4624 /* Get and remember the size we ended up with. Update the pty. */
4625 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4626 term_report_winsize(term, term->tl_rows, term->tl_cols);
4627}
4628
4629/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004630 * "term_getstatus(buf)" function
4631 */
4632 void
4633f_term_getstatus(typval_T *argvars, typval_T *rettv)
4634{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004635 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004636 term_T *term;
4637 char_u val[100];
4638
4639 rettv->v_type = VAR_STRING;
4640 if (buf == NULL)
4641 return;
4642 term = buf->b_term;
4643
4644 if (term_job_running(term))
4645 STRCPY(val, "running");
4646 else
4647 STRCPY(val, "finished");
4648 if (term->tl_normal_mode)
4649 STRCAT(val, ",normal");
4650 rettv->vval.v_string = vim_strsave(val);
4651}
4652
4653/*
4654 * "term_gettitle(buf)" function
4655 */
4656 void
4657f_term_gettitle(typval_T *argvars, typval_T *rettv)
4658{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004659 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004660
4661 rettv->v_type = VAR_STRING;
4662 if (buf == NULL)
4663 return;
4664
4665 if (buf->b_term->tl_title != NULL)
4666 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4667}
4668
4669/*
4670 * "term_gettty(buf)" function
4671 */
4672 void
4673f_term_gettty(typval_T *argvars, typval_T *rettv)
4674{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004675 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004676 char_u *p;
4677 int num = 0;
4678
4679 rettv->v_type = VAR_STRING;
4680 if (buf == NULL)
4681 return;
4682 if (argvars[1].v_type != VAR_UNKNOWN)
4683 num = get_tv_number(&argvars[1]);
4684
4685 switch (num)
4686 {
4687 case 0:
4688 if (buf->b_term->tl_job != NULL)
4689 p = buf->b_term->tl_job->jv_tty_out;
4690 else
4691 p = buf->b_term->tl_tty_out;
4692 break;
4693 case 1:
4694 if (buf->b_term->tl_job != NULL)
4695 p = buf->b_term->tl_job->jv_tty_in;
4696 else
4697 p = buf->b_term->tl_tty_in;
4698 break;
4699 default:
4700 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4701 return;
4702 }
4703 if (p != NULL)
4704 rettv->vval.v_string = vim_strsave(p);
4705}
4706
4707/*
4708 * "term_list()" function
4709 */
4710 void
4711f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4712{
4713 term_T *tp;
4714 list_T *l;
4715
4716 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4717 return;
4718
4719 l = rettv->vval.v_list;
4720 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4721 if (tp != NULL && tp->tl_buffer != NULL)
4722 if (list_append_number(l,
4723 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4724 return;
4725}
4726
4727/*
4728 * "term_scrape(buf, row)" function
4729 */
4730 void
4731f_term_scrape(typval_T *argvars, typval_T *rettv)
4732{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004733 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004734 VTermScreen *screen = NULL;
4735 VTermPos pos;
4736 list_T *l;
4737 term_T *term;
4738 char_u *p;
4739 sb_line_T *line;
4740
4741 if (rettv_list_alloc(rettv) == FAIL)
4742 return;
4743 if (buf == NULL)
4744 return;
4745 term = buf->b_term;
4746
4747 l = rettv->vval.v_list;
4748 pos.row = get_row_number(&argvars[1], term);
4749
4750 if (term->tl_vterm != NULL)
4751 {
4752 screen = vterm_obtain_screen(term->tl_vterm);
4753 p = NULL;
4754 line = NULL;
4755 }
4756 else
4757 {
4758 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4759
4760 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4761 return;
4762 p = ml_get_buf(buf, lnum + 1, FALSE);
4763 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4764 }
4765
4766 for (pos.col = 0; pos.col < term->tl_cols; )
4767 {
4768 dict_T *dcell;
4769 int width;
4770 VTermScreenCellAttrs attrs;
4771 VTermColor fg, bg;
4772 char_u rgb[8];
4773 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4774 int off = 0;
4775 int i;
4776
4777 if (screen == NULL)
4778 {
4779 cellattr_T *cellattr;
4780 int len;
4781
4782 /* vterm has finished, get the cell from scrollback */
4783 if (pos.col >= line->sb_cols)
4784 break;
4785 cellattr = line->sb_cells + pos.col;
4786 width = cellattr->width;
4787 attrs = cellattr->attrs;
4788 fg = cellattr->fg;
4789 bg = cellattr->bg;
4790 len = MB_PTR2LEN(p);
4791 mch_memmove(mbs, p, len);
4792 mbs[len] = NUL;
4793 p += len;
4794 }
4795 else
4796 {
4797 VTermScreenCell cell;
4798 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4799 break;
4800 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4801 {
4802 if (cell.chars[i] == 0)
4803 break;
4804 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4805 }
4806 mbs[off] = NUL;
4807 width = cell.width;
4808 attrs = cell.attrs;
4809 fg = cell.fg;
4810 bg = cell.bg;
4811 }
4812 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004813 if (dcell == NULL)
4814 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004815 list_append_dict(l, dcell);
4816
4817 dict_add_nr_str(dcell, "chars", 0, mbs);
4818
4819 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4820 fg.red, fg.green, fg.blue);
4821 dict_add_nr_str(dcell, "fg", 0, rgb);
4822 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4823 bg.red, bg.green, bg.blue);
4824 dict_add_nr_str(dcell, "bg", 0, rgb);
4825
4826 dict_add_nr_str(dcell, "attr",
4827 cell2attr(attrs, fg, bg), NULL);
4828 dict_add_nr_str(dcell, "width", width, NULL);
4829
4830 ++pos.col;
4831 if (width == 2)
4832 ++pos.col;
4833 }
4834}
4835
4836/*
4837 * "term_sendkeys(buf, keys)" function
4838 */
4839 void
4840f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4841{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004842 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004843 char_u *msg;
4844 term_T *term;
4845
4846 rettv->v_type = VAR_UNKNOWN;
4847 if (buf == NULL)
4848 return;
4849
4850 msg = get_tv_string_chk(&argvars[1]);
4851 if (msg == NULL)
4852 return;
4853 term = buf->b_term;
4854 if (term->tl_vterm == NULL)
4855 return;
4856
4857 while (*msg != NUL)
4858 {
4859 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004860 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004861 }
4862}
4863
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004864#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4865/*
4866 * "term_getansicolors(buf)" function
4867 */
4868 void
4869f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4870{
4871 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4872 term_T *term;
4873 VTermState *state;
4874 VTermColor color;
4875 char_u hexbuf[10];
4876 int index;
4877 list_T *list;
4878
4879 if (rettv_list_alloc(rettv) == FAIL)
4880 return;
4881
4882 if (buf == NULL)
4883 return;
4884 term = buf->b_term;
4885 if (term->tl_vterm == NULL)
4886 return;
4887
4888 list = rettv->vval.v_list;
4889 state = vterm_obtain_state(term->tl_vterm);
4890 for (index = 0; index < 16; index++)
4891 {
4892 vterm_state_get_palette_color(state, index, &color);
4893 sprintf((char *)hexbuf, "#%02x%02x%02x",
4894 color.red, color.green, color.blue);
4895 if (list_append_string(list, hexbuf, 7) == FAIL)
4896 return;
4897 }
4898}
4899
4900/*
4901 * "term_setansicolors(buf, list)" function
4902 */
4903 void
4904f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4905{
4906 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4907 term_T *term;
4908
4909 if (buf == NULL)
4910 return;
4911 term = buf->b_term;
4912 if (term->tl_vterm == NULL)
4913 return;
4914
4915 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4916 {
4917 EMSG(_(e_listreq));
4918 return;
4919 }
4920
4921 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4922 EMSG(_(e_invarg));
4923}
4924#endif
4925
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004926/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004927 * "term_setrestore(buf, command)" function
4928 */
4929 void
4930f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4931{
4932#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004933 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004934 term_T *term;
4935 char_u *cmd;
4936
4937 if (buf == NULL)
4938 return;
4939 term = buf->b_term;
4940 vim_free(term->tl_command);
4941 cmd = get_tv_string_chk(&argvars[1]);
4942 if (cmd != NULL)
4943 term->tl_command = vim_strsave(cmd);
4944 else
4945 term->tl_command = NULL;
4946#endif
4947}
4948
4949/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004950 * "term_setkill(buf, how)" function
4951 */
4952 void
4953f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4954{
4955 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4956 term_T *term;
4957 char_u *how;
4958
4959 if (buf == NULL)
4960 return;
4961 term = buf->b_term;
4962 vim_free(term->tl_kill);
4963 how = get_tv_string_chk(&argvars[1]);
4964 if (how != NULL)
4965 term->tl_kill = vim_strsave(how);
4966 else
4967 term->tl_kill = NULL;
4968}
4969
4970/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004971 * "term_start(command, options)" function
4972 */
4973 void
4974f_term_start(typval_T *argvars, typval_T *rettv)
4975{
4976 jobopt_T opt;
4977 buf_T *buf;
4978
4979 init_job_options(&opt);
4980 if (argvars[1].v_type != VAR_UNKNOWN
4981 && get_job_options(&argvars[1], &opt,
4982 JO_TIMEOUT_ALL + JO_STOPONEXIT
4983 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4984 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4985 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4986 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004987 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004988 + JO2_NORESTORE + JO2_TERM_KILL
4989 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004990 return;
4991
Bram Moolenaar13568252018-03-16 20:46:58 +01004992 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004993
4994 if (buf != NULL && buf->b_term != NULL)
4995 rettv->vval.v_number = buf->b_fnum;
4996}
4997
4998/*
4999 * "term_wait" function
5000 */
5001 void
5002f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5003{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005004 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005005
5006 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005007 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005008 if (buf->b_term->tl_job == NULL)
5009 {
5010 ch_log(NULL, "term_wait(): no job to wait for");
5011 return;
5012 }
5013 if (buf->b_term->tl_job->jv_channel == NULL)
5014 /* channel is closed, nothing to do */
5015 return;
5016
5017 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005018 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005019 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5020 {
5021 /* The job is dead, keep reading channel I/O until the channel is
5022 * closed. buf->b_term may become NULL if the terminal was closed while
5023 * waiting. */
5024 ch_log(NULL, "term_wait(): waiting for channel to close");
5025 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5026 {
5027 mch_check_messages();
5028 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005029 if (!buf_valid(buf))
5030 /* If the terminal is closed when the channel is closed the
5031 * buffer disappears. */
5032 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005033 ui_delay(10L, FALSE);
5034 }
5035 mch_check_messages();
5036 parse_queued_messages();
5037 }
5038 else
5039 {
5040 long wait = 10L;
5041
5042 mch_check_messages();
5043 parse_queued_messages();
5044
5045 /* Wait for some time for any channel I/O. */
5046 if (argvars[1].v_type != VAR_UNKNOWN)
5047 wait = get_tv_number(&argvars[1]);
5048 ui_delay(wait, TRUE);
5049 mch_check_messages();
5050
5051 /* Flushing messages on channels is hopefully sufficient.
5052 * TODO: is there a better way? */
5053 parse_queued_messages();
5054 }
5055}
5056
5057/*
5058 * Called when a channel has sent all the lines to a terminal.
5059 * Send a CTRL-D to mark the end of the text.
5060 */
5061 void
5062term_send_eof(channel_T *ch)
5063{
5064 term_T *term;
5065
5066 for (term = first_term; term != NULL; term = term->tl_next)
5067 if (term->tl_job == ch->ch_job)
5068 {
5069 if (term->tl_eof_chars != NULL)
5070 {
5071 channel_send(ch, PART_IN, term->tl_eof_chars,
5072 (int)STRLEN(term->tl_eof_chars), NULL);
5073 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5074 }
5075# ifdef WIN3264
5076 else
5077 /* Default: CTRL-D */
5078 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5079# endif
5080 }
5081}
5082
5083# if defined(WIN3264) || defined(PROTO)
5084
5085/**************************************
5086 * 2. MS-Windows implementation.
5087 */
5088
5089# ifndef PROTO
5090
5091#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5092#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005093#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005094
5095void* (*winpty_config_new)(UINT64, void*);
5096void* (*winpty_open)(void*, void*);
5097void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5098BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5099void (*winpty_config_set_mouse_mode)(void*, int);
5100void (*winpty_config_set_initial_size)(void*, int, int);
5101LPCWSTR (*winpty_conin_name)(void*);
5102LPCWSTR (*winpty_conout_name)(void*);
5103LPCWSTR (*winpty_conerr_name)(void*);
5104void (*winpty_free)(void*);
5105void (*winpty_config_free)(void*);
5106void (*winpty_spawn_config_free)(void*);
5107void (*winpty_error_free)(void*);
5108LPCWSTR (*winpty_error_msg)(void*);
5109BOOL (*winpty_set_size)(void*, int, int, void*);
5110HANDLE (*winpty_agent_process)(void*);
5111
5112#define WINPTY_DLL "winpty.dll"
5113
5114static HINSTANCE hWinPtyDLL = NULL;
5115# endif
5116
5117 static int
5118dyn_winpty_init(int verbose)
5119{
5120 int i;
5121 static struct
5122 {
5123 char *name;
5124 FARPROC *ptr;
5125 } winpty_entry[] =
5126 {
5127 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5128 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5129 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5130 {"winpty_config_set_mouse_mode",
5131 (FARPROC*)&winpty_config_set_mouse_mode},
5132 {"winpty_config_set_initial_size",
5133 (FARPROC*)&winpty_config_set_initial_size},
5134 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5135 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5136 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5137 {"winpty_free", (FARPROC*)&winpty_free},
5138 {"winpty_open", (FARPROC*)&winpty_open},
5139 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5140 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5141 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5142 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5143 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5144 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5145 {NULL, NULL}
5146 };
5147
5148 /* No need to initialize twice. */
5149 if (hWinPtyDLL)
5150 return OK;
5151 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5152 * winpty.dll. */
5153 if (*p_winptydll != NUL)
5154 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5155 if (!hWinPtyDLL)
5156 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5157 if (!hWinPtyDLL)
5158 {
5159 if (verbose)
5160 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5161 : (char_u *)WINPTY_DLL);
5162 return FAIL;
5163 }
5164 for (i = 0; winpty_entry[i].name != NULL
5165 && winpty_entry[i].ptr != NULL; ++i)
5166 {
5167 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5168 winpty_entry[i].name)) == NULL)
5169 {
5170 if (verbose)
5171 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5172 return FAIL;
5173 }
5174 }
5175
5176 return OK;
5177}
5178
5179/*
5180 * Create a new terminal of "rows" by "cols" cells.
5181 * Store a reference in "term".
5182 * Return OK or FAIL.
5183 */
5184 static int
5185term_and_job_init(
5186 term_T *term,
5187 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005188 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005189 jobopt_T *opt)
5190{
5191 WCHAR *cmd_wchar = NULL;
5192 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005193 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005194 channel_T *channel = NULL;
5195 job_T *job = NULL;
5196 DWORD error;
5197 HANDLE jo = NULL;
5198 HANDLE child_process_handle;
5199 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005200 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005201 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005202 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005203 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005204
5205 if (dyn_winpty_init(TRUE) == FAIL)
5206 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005207 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5208 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005209
5210 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005211 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005212 cmd = argvar->vval.v_string;
5213 }
5214 else if (argvar->v_type == VAR_LIST)
5215 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005216 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005217 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005218 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005219 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005220 if (cmd == NULL || *cmd == NUL)
5221 {
5222 EMSG(_(e_invarg));
5223 goto failed;
5224 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005225
5226 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005227 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005228 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005229 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005230 if (opt->jo_cwd != NULL)
5231 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005232
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005233 win32_build_env(opt->jo_env, &ga_env, TRUE);
5234 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005235
5236 job = job_alloc();
5237 if (job == NULL)
5238 goto failed;
5239
5240 channel = add_channel();
5241 if (channel == NULL)
5242 goto failed;
5243
5244 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5245 if (term->tl_winpty_config == NULL)
5246 goto failed;
5247
5248 winpty_config_set_mouse_mode(term->tl_winpty_config,
5249 WINPTY_MOUSE_MODE_FORCE);
5250 winpty_config_set_initial_size(term->tl_winpty_config,
5251 term->tl_cols, term->tl_rows);
5252 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5253 if (term->tl_winpty == NULL)
5254 goto failed;
5255
5256 spawn_config = winpty_spawn_config_new(
5257 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5258 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5259 NULL,
5260 cmd_wchar,
5261 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005262 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005263 &winpty_err);
5264 if (spawn_config == NULL)
5265 goto failed;
5266
5267 channel = add_channel();
5268 if (channel == NULL)
5269 goto failed;
5270
5271 job = job_alloc();
5272 if (job == NULL)
5273 goto failed;
5274
5275 if (opt->jo_set & JO_IN_BUF)
5276 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5277
5278 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5279 &child_thread_handle, &error, &winpty_err))
5280 goto failed;
5281
5282 channel_set_pipes(channel,
5283 (sock_T)CreateFileW(
5284 winpty_conin_name(term->tl_winpty),
5285 GENERIC_WRITE, 0, NULL,
5286 OPEN_EXISTING, 0, NULL),
5287 (sock_T)CreateFileW(
5288 winpty_conout_name(term->tl_winpty),
5289 GENERIC_READ, 0, NULL,
5290 OPEN_EXISTING, 0, NULL),
5291 (sock_T)CreateFileW(
5292 winpty_conerr_name(term->tl_winpty),
5293 GENERIC_READ, 0, NULL,
5294 OPEN_EXISTING, 0, NULL));
5295
5296 /* Write lines with CR instead of NL. */
5297 channel->ch_write_text_mode = TRUE;
5298
5299 jo = CreateJobObject(NULL, NULL);
5300 if (jo == NULL)
5301 goto failed;
5302
5303 if (!AssignProcessToJobObject(jo, child_process_handle))
5304 {
5305 /* Failed, switch the way to terminate process with TerminateProcess. */
5306 CloseHandle(jo);
5307 jo = NULL;
5308 }
5309
5310 winpty_spawn_config_free(spawn_config);
5311 vim_free(cmd_wchar);
5312 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005313 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005314
5315 create_vterm(term, term->tl_rows, term->tl_cols);
5316
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005317#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5318 if (opt->jo_set2 & JO2_ANSI_COLORS)
5319 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5320 else
5321 init_vterm_ansi_colors(term->tl_vterm);
5322#endif
5323
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005324 channel_set_job(channel, job, opt);
5325 job_set_options(job, opt);
5326
5327 job->jv_channel = channel;
5328 job->jv_proc_info.hProcess = child_process_handle;
5329 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5330 job->jv_job_object = jo;
5331 job->jv_status = JOB_STARTED;
5332 job->jv_tty_in = utf16_to_enc(
5333 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5334 job->jv_tty_out = utf16_to_enc(
5335 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5336 ++job->jv_refcount;
5337 term->tl_job = job;
5338
5339 return OK;
5340
5341failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005342 ga_clear(&ga_cmd);
5343 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005344 vim_free(cmd_wchar);
5345 vim_free(cwd_wchar);
5346 if (spawn_config != NULL)
5347 winpty_spawn_config_free(spawn_config);
5348 if (channel != NULL)
5349 channel_clear(channel);
5350 if (job != NULL)
5351 {
5352 job->jv_channel = NULL;
5353 job_cleanup(job);
5354 }
5355 term->tl_job = NULL;
5356 if (jo != NULL)
5357 CloseHandle(jo);
5358 if (term->tl_winpty != NULL)
5359 winpty_free(term->tl_winpty);
5360 term->tl_winpty = NULL;
5361 if (term->tl_winpty_config != NULL)
5362 winpty_config_free(term->tl_winpty_config);
5363 term->tl_winpty_config = NULL;
5364 if (winpty_err != NULL)
5365 {
5366 char_u *msg = utf16_to_enc(
5367 (short_u *)winpty_error_msg(winpty_err), NULL);
5368
5369 EMSG(msg);
5370 winpty_error_free(winpty_err);
5371 }
5372 return FAIL;
5373}
5374
5375 static int
5376create_pty_only(term_T *term, jobopt_T *options)
5377{
5378 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5379 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5380 char in_name[80], out_name[80];
5381 channel_T *channel = NULL;
5382
5383 create_vterm(term, term->tl_rows, term->tl_cols);
5384
5385 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5386 GetCurrentProcessId(),
5387 curbuf->b_fnum);
5388 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5389 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5390 PIPE_UNLIMITED_INSTANCES,
5391 0, 0, NMPWAIT_NOWAIT, NULL);
5392 if (hPipeIn == INVALID_HANDLE_VALUE)
5393 goto failed;
5394
5395 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5396 GetCurrentProcessId(),
5397 curbuf->b_fnum);
5398 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5399 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5400 PIPE_UNLIMITED_INSTANCES,
5401 0, 0, 0, NULL);
5402 if (hPipeOut == INVALID_HANDLE_VALUE)
5403 goto failed;
5404
5405 ConnectNamedPipe(hPipeIn, NULL);
5406 ConnectNamedPipe(hPipeOut, NULL);
5407
5408 term->tl_job = job_alloc();
5409 if (term->tl_job == NULL)
5410 goto failed;
5411 ++term->tl_job->jv_refcount;
5412
5413 /* behave like the job is already finished */
5414 term->tl_job->jv_status = JOB_FINISHED;
5415
5416 channel = add_channel();
5417 if (channel == NULL)
5418 goto failed;
5419 term->tl_job->jv_channel = channel;
5420 channel->ch_keep_open = TRUE;
5421 channel->ch_named_pipe = TRUE;
5422
5423 channel_set_pipes(channel,
5424 (sock_T)hPipeIn,
5425 (sock_T)hPipeOut,
5426 (sock_T)hPipeOut);
5427 channel_set_job(channel, term->tl_job, options);
5428 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5429 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5430
5431 return OK;
5432
5433failed:
5434 if (hPipeIn != NULL)
5435 CloseHandle(hPipeIn);
5436 if (hPipeOut != NULL)
5437 CloseHandle(hPipeOut);
5438 return FAIL;
5439}
5440
5441/*
5442 * Free the terminal emulator part of "term".
5443 */
5444 static void
5445term_free_vterm(term_T *term)
5446{
5447 if (term->tl_winpty != NULL)
5448 winpty_free(term->tl_winpty);
5449 term->tl_winpty = NULL;
5450 if (term->tl_winpty_config != NULL)
5451 winpty_config_free(term->tl_winpty_config);
5452 term->tl_winpty_config = NULL;
5453 if (term->tl_vterm != NULL)
5454 vterm_free(term->tl_vterm);
5455 term->tl_vterm = NULL;
5456}
5457
5458/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005459 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460 */
5461 static void
5462term_report_winsize(term_T *term, int rows, int cols)
5463{
5464 if (term->tl_winpty)
5465 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5466}
5467
5468 int
5469terminal_enabled(void)
5470{
5471 return dyn_winpty_init(FALSE) == OK;
5472}
5473
5474# else
5475
5476/**************************************
5477 * 3. Unix-like implementation.
5478 */
5479
5480/*
5481 * Create a new terminal of "rows" by "cols" cells.
5482 * Start job for "cmd".
5483 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005484 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485 * Return OK or FAIL.
5486 */
5487 static int
5488term_and_job_init(
5489 term_T *term,
5490 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005491 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005492 jobopt_T *opt)
5493{
5494 create_vterm(term, term->tl_rows, term->tl_cols);
5495
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005496#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5497 if (opt->jo_set2 & JO2_ANSI_COLORS)
5498 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5499 else
5500 init_vterm_ansi_colors(term->tl_vterm);
5501#endif
5502
Bram Moolenaar13568252018-03-16 20:46:58 +01005503 /* This may change a string in "argvar". */
5504 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005505 if (term->tl_job != NULL)
5506 ++term->tl_job->jv_refcount;
5507
5508 return term->tl_job != NULL
5509 && term->tl_job->jv_channel != NULL
5510 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5511}
5512
5513 static int
5514create_pty_only(term_T *term, jobopt_T *opt)
5515{
5516 create_vterm(term, term->tl_rows, term->tl_cols);
5517
5518 term->tl_job = job_alloc();
5519 if (term->tl_job == NULL)
5520 return FAIL;
5521 ++term->tl_job->jv_refcount;
5522
5523 /* behave like the job is already finished */
5524 term->tl_job->jv_status = JOB_FINISHED;
5525
5526 return mch_create_pty_channel(term->tl_job, opt);
5527}
5528
5529/*
5530 * Free the terminal emulator part of "term".
5531 */
5532 static void
5533term_free_vterm(term_T *term)
5534{
5535 if (term->tl_vterm != NULL)
5536 vterm_free(term->tl_vterm);
5537 term->tl_vterm = NULL;
5538}
5539
5540/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005541 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005542 */
5543 static void
5544term_report_winsize(term_T *term, int rows, int cols)
5545{
5546 /* Use an ioctl() to report the new window size to the job. */
5547 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5548 {
5549 int fd = -1;
5550 int part;
5551
5552 for (part = PART_OUT; part < PART_COUNT; ++part)
5553 {
5554 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5555 if (isatty(fd))
5556 break;
5557 }
5558 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5559 mch_signal_job(term->tl_job, (char_u *)"winch");
5560 }
5561}
5562
5563# endif
5564
5565#endif /* FEAT_TERMINAL */