blob: 0d2dab8ab74edd5d4c35474f96534a5ac167eaf7 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
39 *
40 * TODO:
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +020041 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
Bram Moolenaar4a696342018-04-05 18:45:26 +020042 * redirection. Probably in call to channel_set_pipes().
Bram Moolenaar802bfb12018-04-15 17:28:13 +020043 * - Win32: Redirecting output does not work, Test_terminal_redir_file()
44 * is disabled.
Bram 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 Moolenaar802bfb12018-04-15 17:28:13 +020047 * - When starting terminal window with shell in terminal, then using :gui to
48 * switch to GUI, shell stops working. Scrollback seems wrong, command
49 * running in shell is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020050 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
51 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020052 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020053 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010054 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaar51b0f372017-11-18 18:52:04 +010055 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * - add test for giving error for invalid 'termsize' value.
57 * - support minimal size when 'termsize' is "rows*cols".
58 * - support minimal size when 'termsize' is empty?
59 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020060 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020061 * - For the GUI fill termios with default values, perhaps like pangoterm:
62 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020063 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020064 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020065 */
66
67#include "vim.h"
68
69#if defined(FEAT_TERMINAL) || defined(PROTO)
70
71#ifndef MIN
72# define MIN(x,y) ((x) < (y) ? (x) : (y))
73#endif
74#ifndef MAX
75# define MAX(x,y) ((x) > (y) ? (x) : (y))
76#endif
77
78#include "libvterm/include/vterm.h"
79
80/* This is VTermScreenCell without the characters, thus much smaller. */
81typedef struct {
82 VTermScreenCellAttrs attrs;
83 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010084 VTermColor fg;
85 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020086} cellattr_T;
87
88typedef struct sb_line_S {
89 int sb_cols; /* can differ per line */
90 cellattr_T *sb_cells; /* allocated */
91 cellattr_T sb_fill_attr; /* for short line */
92} sb_line_T;
93
94/* typedef term_T in structs.h */
95struct terminal_S {
96 term_T *tl_next;
97
98 VTerm *tl_vterm;
99 job_T *tl_job;
100 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100101#if defined(FEAT_GUI)
102 int tl_system; /* when non-zero used for :!cmd output */
103 int tl_toprow; /* row with first line of system terminal */
104#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200105
106 /* Set when setting the size of a vterm, reset after redrawing. */
107 int tl_vterm_size_changed;
108
109 /* used when tl_job is NULL and only a pty was created */
110 int tl_tty_fd;
111 char_u *tl_tty_in;
112 char_u *tl_tty_out;
113
114 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
115 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100116 int tl_finish;
117#define TL_FINISH_UNSET NUL
118#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
119#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
120#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200121 char_u *tl_opencmd;
122 char_u *tl_eof_chars;
123
124#ifdef WIN3264
125 void *tl_winpty_config;
126 void *tl_winpty;
127#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100128#if defined(FEAT_SESSION)
129 char_u *tl_command;
130#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100131 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200132
133 /* last known vterm size */
134 int tl_rows;
135 int tl_cols;
136 /* vterm size does not follow window size */
137 int tl_rows_fixed;
138 int tl_cols_fixed;
139
140 char_u *tl_title; /* NULL or allocated */
141 char_u *tl_status_text; /* NULL or allocated */
142
143 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200144 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200145 int tl_dirty_row_end; /* row below last one to update */
146
147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
149 cellattr_T tl_default_color;
150
Bram Moolenaard96ff162018-02-18 22:13:29 +0100151 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
152 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
153
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200154 VTermPos tl_cursor_pos;
155 int tl_cursor_visible;
156 int tl_cursor_blink;
157 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
158 char_u *tl_cursor_color; /* NULL or allocated */
159
160 int tl_using_altscreen;
161};
162
163#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
164#define TMODE_LOOP 2 /* CTRL-W N used */
165
166/*
167 * List of all active terminals.
168 */
169static term_T *first_term = NULL;
170
171/* Terminal active in terminal_loop(). */
172static term_T *in_terminal_loop = NULL;
173
174#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
175#define KEY_BUF_LEN 200
176
177/*
178 * Functions with separate implementation for MS-Windows and Unix-like systems.
179 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100180static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181static int create_pty_only(term_T *term, jobopt_T *opt);
182static void term_report_winsize(term_T *term, int rows, int cols);
183static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100184#ifdef FEAT_GUI
185static void update_system_term(term_T *term);
186#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100188/* The character that we know (or assume) that the terminal expects for the
189 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200191
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100192/* "Terminal" highlight group colors. */
193static int term_default_cterm_fg = -1;
194static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200195
Bram Moolenaard317b382018-02-08 22:33:31 +0100196/* Store the last set and the desired cursor properties, so that we only update
197 * them when needed. Doing it unnecessary may result in flicker. */
198static char_u *last_set_cursor_color = (char_u *)"";
199static char_u *desired_cursor_color = (char_u *)"";
200static int last_set_cursor_shape = -1;
201static int desired_cursor_shape = -1;
202static int last_set_cursor_blink = -1;
203static int desired_cursor_blink = -1;
204
205
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200206/**************************************
207 * 1. Generic code for all systems.
208 */
209
210/*
211 * Determine the terminal size from 'termsize' and the current window.
212 * Assumes term->tl_rows and term->tl_cols are zero.
213 */
214 static void
215set_term_and_win_size(term_T *term)
216{
Bram Moolenaar13568252018-03-16 20:46:58 +0100217#ifdef FEAT_GUI
218 if (term->tl_system)
219 {
220 /* Use the whole screen for the system command. However, it will start
221 * at the command line and scroll up as needed, using tl_toprow. */
222 term->tl_rows = Rows;
223 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200224 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100225 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100226#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200227 if (*curwin->w_p_tms != NUL)
228 {
229 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
230
231 term->tl_rows = atoi((char *)curwin->w_p_tms);
232 term->tl_cols = atoi((char *)p);
233 }
234 if (term->tl_rows == 0)
235 term->tl_rows = curwin->w_height;
236 else
237 {
238 win_setheight_win(term->tl_rows, curwin);
239 term->tl_rows_fixed = TRUE;
240 }
241 if (term->tl_cols == 0)
242 term->tl_cols = curwin->w_width;
243 else
244 {
245 win_setwidth_win(term->tl_cols, curwin);
246 term->tl_cols_fixed = TRUE;
247 }
248}
249
250/*
251 * Initialize job options for a terminal job.
252 * Caller may overrule some of them.
253 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100254 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200255init_job_options(jobopt_T *opt)
256{
257 clear_job_options(opt);
258
259 opt->jo_mode = MODE_RAW;
260 opt->jo_out_mode = MODE_RAW;
261 opt->jo_err_mode = MODE_RAW;
262 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
263}
264
265/*
266 * Set job options mandatory for a terminal job.
267 */
268 static void
269setup_job_options(jobopt_T *opt, int rows, int cols)
270{
271 if (!(opt->jo_set & JO_OUT_IO))
272 {
273 /* Connect stdout to the terminal. */
274 opt->jo_io[PART_OUT] = JIO_BUFFER;
275 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
276 opt->jo_modifiable[PART_OUT] = 0;
277 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
278 }
279
280 if (!(opt->jo_set & JO_ERR_IO))
281 {
282 /* Connect stderr to the terminal. */
283 opt->jo_io[PART_ERR] = JIO_BUFFER;
284 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
285 opt->jo_modifiable[PART_ERR] = 0;
286 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
287 }
288
289 opt->jo_pty = TRUE;
290 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
291 opt->jo_term_rows = rows;
292 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
293 opt->jo_term_cols = cols;
294}
295
296/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100297 * Close a terminal buffer (and its window). Used when creating the terminal
298 * fails.
299 */
300 static void
301term_close_buffer(buf_T *buf, buf_T *old_curbuf)
302{
303 free_terminal(buf);
304 if (old_curbuf != NULL)
305 {
306 --curbuf->b_nwindows;
307 curbuf = old_curbuf;
308 curwin->w_buffer = curbuf;
309 ++curbuf->b_nwindows;
310 }
311
312 /* Wiping out the buffer will also close the window and call
313 * free_terminal(). */
314 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
315}
316
317/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200318 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100319 * Use either "argvar" or "argv", the other must be NULL.
320 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
321 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200322 * Returns NULL when failed.
323 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100324 buf_T *
325term_start(
326 typval_T *argvar,
327 char **argv,
328 jobopt_T *opt,
329 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200330{
331 exarg_T split_ea;
332 win_T *old_curwin = curwin;
333 term_T *term;
334 buf_T *old_curbuf = NULL;
335 int res;
336 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100337 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200338
339 if (check_restricted() || check_secure())
340 return NULL;
341
342 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
343 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
344 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
345 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
346 {
347 EMSG(_(e_invarg));
348 return NULL;
349 }
350
351 term = (term_T *)alloc_clear(sizeof(term_T));
352 if (term == NULL)
353 return NULL;
354 term->tl_dirty_row_end = MAX_ROW;
355 term->tl_cursor_visible = TRUE;
356 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
357 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100358#ifdef FEAT_GUI
359 term->tl_system = (flags & TERM_START_SYSTEM);
360#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200361 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
362
363 vim_memset(&split_ea, 0, sizeof(split_ea));
364 if (opt->jo_curwin)
365 {
366 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100367 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200368 {
369 no_write_message();
370 vim_free(term);
371 return NULL;
372 }
373 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100374 ECMD_HIDE
375 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
376 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200377 {
378 vim_free(term);
379 return NULL;
380 }
381 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100382 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200383 {
384 buf_T *buf;
385
386 /* Create a new buffer without a window. Make it the current buffer for
387 * a moment to be able to do the initialisations. */
388 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
389 BLN_NEW | BLN_LISTED);
390 if (buf == NULL || ml_open(buf) == FAIL)
391 {
392 vim_free(term);
393 return NULL;
394 }
395 old_curbuf = curbuf;
396 --curbuf->b_nwindows;
397 curbuf = buf;
398 curwin->w_buffer = buf;
399 ++curbuf->b_nwindows;
400 }
401 else
402 {
403 /* Open a new window or tab. */
404 split_ea.cmdidx = CMD_new;
405 split_ea.cmd = (char_u *)"new";
406 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100407 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200408 {
409 split_ea.line2 = opt->jo_term_rows;
410 split_ea.addr_count = 1;
411 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200413 {
414 split_ea.line2 = opt->jo_term_cols;
415 split_ea.addr_count = 1;
416 }
417
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100418 if (vertical)
419 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200420 ex_splitview(&split_ea);
421 if (curwin == old_curwin)
422 {
423 /* split failed */
424 vim_free(term);
425 return NULL;
426 }
427 }
428 term->tl_buffer = curbuf;
429 curbuf->b_term = term;
430
431 if (!opt->jo_hidden)
432 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100433 /* Only one size was taken care of with :new, do the other one. With
434 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100435 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200436 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200438 win_setwidth(opt->jo_term_cols);
439 }
440
441 /* Link the new terminal in the list of active terminals. */
442 term->tl_next = first_term;
443 first_term = term;
444
445 if (opt->jo_term_name != NULL)
446 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100447 else if (argv != NULL)
448 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 else
450 {
451 int i;
452 size_t len;
453 char_u *cmd, *p;
454
455 if (argvar->v_type == VAR_STRING)
456 {
457 cmd = argvar->vval.v_string;
458 if (cmd == NULL)
459 cmd = (char_u *)"";
460 else if (STRCMP(cmd, "NONE") == 0)
461 cmd = (char_u *)"pty";
462 }
463 else if (argvar->v_type != VAR_LIST
464 || argvar->vval.v_list == NULL
465 || argvar->vval.v_list->lv_len < 1
466 || (cmd = get_tv_string_chk(
467 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
468 cmd = (char_u*)"";
469
470 len = STRLEN(cmd) + 10;
471 p = alloc((int)len);
472
473 for (i = 0; p != NULL; ++i)
474 {
475 /* Prepend a ! to the command name to avoid the buffer name equals
476 * the executable, otherwise ":w!" would overwrite it. */
477 if (i == 0)
478 vim_snprintf((char *)p, len, "!%s", cmd);
479 else
480 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
481 if (buflist_findname(p) == NULL)
482 {
483 vim_free(curbuf->b_ffname);
484 curbuf->b_ffname = p;
485 break;
486 }
487 }
488 }
489 curbuf->b_fname = curbuf->b_ffname;
490
491 if (opt->jo_term_opencmd != NULL)
492 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
493
494 if (opt->jo_eof_chars != NULL)
495 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
496
497 set_string_option_direct((char_u *)"buftype", -1,
498 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
499
500 /* Mark the buffer as not modifiable. It can only be made modifiable after
501 * the job finished. */
502 curbuf->b_p_ma = FALSE;
503
504 set_term_and_win_size(term);
505 setup_job_options(opt, term->tl_rows, term->tl_cols);
506
Bram Moolenaar13568252018-03-16 20:46:58 +0100507 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100508 return curbuf;
509
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100510#if defined(FEAT_SESSION)
511 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100512 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100513 {
514 term->tl_command = vim_strsave((char_u *)"NONE");
515 }
516 else if (argvar->v_type == VAR_STRING)
517 {
518 char_u *cmd = argvar->vval.v_string;
519
520 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
521 term->tl_command = vim_strsave(cmd);
522 }
523 else if (argvar->v_type == VAR_LIST
524 && argvar->vval.v_list != NULL
525 && argvar->vval.v_list->lv_len > 0)
526 {
527 garray_T ga;
528 listitem_T *item;
529
530 ga_init2(&ga, 1, 100);
531 for (item = argvar->vval.v_list->lv_first;
532 item != NULL; item = item->li_next)
533 {
534 char_u *s = get_tv_string_chk(&item->li_tv);
535 char_u *p;
536
537 if (s == NULL)
538 break;
539 p = vim_strsave_fnameescape(s, FALSE);
540 if (p == NULL)
541 break;
542 ga_concat(&ga, p);
543 vim_free(p);
544 ga_append(&ga, ' ');
545 }
546 if (item == NULL)
547 {
548 ga_append(&ga, NUL);
549 term->tl_command = ga.ga_data;
550 }
551 else
552 ga_clear(&ga);
553 }
554#endif
555
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100556 if (opt->jo_term_kill != NULL)
557 {
558 char_u *p = skiptowhite(opt->jo_term_kill);
559
560 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
561 }
562
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200563 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100564 if (argv == NULL
565 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566 && argvar->vval.v_string != NULL
567 && STRCMP(argvar->vval.v_string, "NONE") == 0)
568 res = create_pty_only(term, opt);
569 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100570 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571
572 newbuf = curbuf;
573 if (res == OK)
574 {
575 /* Get and remember the size we ended up with. Update the pty. */
576 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
577 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100578#ifdef FEAT_GUI
579 if (term->tl_system)
580 {
581 /* display first line below typed command */
582 term->tl_toprow = msg_row + 1;
583 term->tl_dirty_row_end = 0;
584 }
585#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200586
587 /* Make sure we don't get stuck on sending keys to the job, it leads to
588 * a deadlock if the job is waiting for Vim to read. */
589 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
590
Bram Moolenaar13568252018-03-16 20:46:58 +0100591 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100592 {
593 ++curbuf->b_locked;
594 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
595 --curbuf->b_locked;
596 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100597 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598 {
599 --curbuf->b_nwindows;
600 curbuf = old_curbuf;
601 curwin->w_buffer = curbuf;
602 ++curbuf->b_nwindows;
603 }
604 }
605 else
606 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100607 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200608 return NULL;
609 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100610
Bram Moolenaar13568252018-03-16 20:46:58 +0100611 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200612 return newbuf;
613}
614
615/*
616 * ":terminal": open a terminal window and execute a job in it.
617 */
618 void
619ex_terminal(exarg_T *eap)
620{
621 typval_T argvar[2];
622 jobopt_T opt;
623 char_u *cmd;
624 char_u *tofree = NULL;
625
626 init_job_options(&opt);
627
628 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100629 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200630 {
631 char_u *p, *ep;
632
633 cmd += 2;
634 p = skiptowhite(cmd);
635 ep = vim_strchr(cmd, '=');
636 if (ep != NULL && ep < p)
637 p = ep;
638
639 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
640 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100641 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
642 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200643 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
644 opt.jo_term_finish = 'o';
645 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
646 opt.jo_curwin = 1;
647 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
648 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100649 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
650 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100651 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
652 && ep != NULL)
653 {
654 opt.jo_set2 |= JO2_TERM_KILL;
655 opt.jo_term_kill = ep + 1;
656 p = skiptowhite(cmd);
657 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
659 && ep != NULL && isdigit(ep[1]))
660 {
661 opt.jo_set2 |= JO2_TERM_ROWS;
662 opt.jo_term_rows = atoi((char *)ep + 1);
663 p = skiptowhite(cmd);
664 }
665 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
666 && ep != NULL && isdigit(ep[1]))
667 {
668 opt.jo_set2 |= JO2_TERM_COLS;
669 opt.jo_term_cols = atoi((char *)ep + 1);
670 p = skiptowhite(cmd);
671 }
672 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
673 && ep != NULL)
674 {
675 char_u *buf = NULL;
676 char_u *keys;
677
678 p = skiptowhite(cmd);
679 *p = NUL;
680 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
681 opt.jo_set2 |= JO2_EOF_CHARS;
682 opt.jo_eof_chars = vim_strsave(keys);
683 vim_free(buf);
684 *p = ' ';
685 }
686 else
687 {
688 if (*p)
689 *p = NUL;
690 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100691 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200692 }
693 cmd = skipwhite(p);
694 }
695 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100696 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200697 /* Make a copy of 'shell', an autocommand may change the option. */
698 tofree = cmd = vim_strsave(p_sh);
699
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100700 /* default to close when the shell exits */
701 if (opt.jo_term_finish == NUL)
702 opt.jo_term_finish = 'c';
703 }
704
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200705 if (eap->addr_count > 0)
706 {
707 /* Write lines from current buffer to the job. */
708 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
709 opt.jo_io[PART_IN] = JIO_BUFFER;
710 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
711 opt.jo_in_top = eap->line1;
712 opt.jo_in_bot = eap->line2;
713 }
714
715 argvar[0].v_type = VAR_STRING;
716 argvar[0].vval.v_string = cmd;
717 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100718 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100720
721theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200722 vim_free(opt.jo_eof_chars);
723}
724
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100725#if defined(FEAT_SESSION) || defined(PROTO)
726/*
727 * Write a :terminal command to the session file to restore the terminal in
728 * window "wp".
729 * Return FAIL if writing fails.
730 */
731 int
732term_write_session(FILE *fd, win_T *wp)
733{
734 term_T *term = wp->w_buffer->b_term;
735
736 /* Create the terminal and run the command. This is not without
737 * risk, but let's assume the user only creates a session when this
738 * will be OK. */
739 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
740 term->tl_cols, term->tl_rows) < 0)
741 return FAIL;
742 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
743 return FAIL;
744
745 return put_eol(fd);
746}
747
748/*
749 * Return TRUE if "buf" has a terminal that should be restored.
750 */
751 int
752term_should_restore(buf_T *buf)
753{
754 term_T *term = buf->b_term;
755
756 return term != NULL && (term->tl_command == NULL
757 || STRCMP(term->tl_command, "NONE") != 0);
758}
759#endif
760
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200761/*
762 * Free the scrollback buffer for "term".
763 */
764 static void
765free_scrollback(term_T *term)
766{
767 int i;
768
769 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
770 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
771 ga_clear(&term->tl_scrollback);
772}
773
774/*
775 * Free a terminal and everything it refers to.
776 * Kills the job if there is one.
777 * Called when wiping out a buffer.
778 */
779 void
780free_terminal(buf_T *buf)
781{
782 term_T *term = buf->b_term;
783 term_T *tp;
784
785 if (term == NULL)
786 return;
787 if (first_term == term)
788 first_term = term->tl_next;
789 else
790 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
791 if (tp->tl_next == term)
792 {
793 tp->tl_next = term->tl_next;
794 break;
795 }
796
797 if (term->tl_job != NULL)
798 {
799 if (term->tl_job->jv_status != JOB_ENDED
800 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100801 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200802 job_stop(term->tl_job, NULL, "kill");
803 job_unref(term->tl_job);
804 }
805
806 free_scrollback(term);
807
808 term_free_vterm(term);
809 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100810#ifdef FEAT_SESSION
811 vim_free(term->tl_command);
812#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100813 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200814 vim_free(term->tl_status_text);
815 vim_free(term->tl_opencmd);
816 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100817 if (desired_cursor_color == term->tl_cursor_color)
818 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 vim_free(term->tl_cursor_color);
820 vim_free(term);
821 buf->b_term = NULL;
822 if (in_terminal_loop == term)
823 in_terminal_loop = NULL;
824}
825
826/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100827 * Get the part that is connected to the tty. Normally this is PART_IN, but
828 * when writing buffer lines to the job it can be another. This makes it
829 * possible to do "1,5term vim -".
830 */
831 static ch_part_T
832get_tty_part(term_T *term)
833{
834#ifdef UNIX
835 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
836 int i;
837
838 for (i = 0; i < 3; ++i)
839 {
840 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
841
842 if (isatty(fd))
843 return parts[i];
844 }
845#endif
846 return PART_IN;
847}
848
849/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200850 * Write job output "msg[len]" to the vterm.
851 */
852 static void
853term_write_job_output(term_T *term, char_u *msg, size_t len)
854{
855 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100856 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200857
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100858 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200859
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100860 /* flush vterm buffer when vterm responded to control sequence */
861 if (prevlen != vterm_output_get_buffer_current(vterm))
862 {
863 char buf[KEY_BUF_LEN];
864 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
865
866 if (curlen > 0)
867 channel_send(term->tl_job->jv_channel, get_tty_part(term),
868 (char_u *)buf, (int)curlen, NULL);
869 }
870
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200871 /* this invokes the damage callbacks */
872 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
873}
874
875 static void
876update_cursor(term_T *term, int redraw)
877{
878 if (term->tl_normal_mode)
879 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100880#ifdef FEAT_GUI
881 if (term->tl_system)
882 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
883 term->tl_cursor_pos.col);
884 else
885#endif
886 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887 if (redraw)
888 {
889 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
890 cursor_on();
891 out_flush();
892#ifdef FEAT_GUI
893 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100894 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200895 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100896 gui_mch_flush();
897 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898#endif
899 }
900}
901
902/*
903 * Invoked when "msg" output from a job was received. Write it to the terminal
904 * of "buffer".
905 */
906 void
907write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
908{
909 size_t len = STRLEN(msg);
910 term_T *term = buffer->b_term;
911
912 if (term->tl_vterm == NULL)
913 {
914 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
915 return;
916 }
917 ch_log(channel, "writing %d bytes to terminal", (int)len);
918 term_write_job_output(term, msg, len);
919
Bram Moolenaar13568252018-03-16 20:46:58 +0100920#ifdef FEAT_GUI
921 if (term->tl_system)
922 {
923 /* show system output, scrolling up the screen as needed */
924 update_system_term(term);
925 update_cursor(term, TRUE);
926 }
927 else
928#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200929 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
930 * contents, thus no screen update is needed. */
931 if (!term->tl_normal_mode)
932 {
933 /* TODO: only update once in a while. */
934 ch_log(term->tl_job->jv_channel, "updating screen");
935 if (buffer == curbuf)
936 {
937 update_screen(0);
938 update_cursor(term, TRUE);
939 }
940 else
941 redraw_after_callback(TRUE);
942 }
943}
944
945/*
946 * Send a mouse position and click to the vterm
947 */
948 static int
949term_send_mouse(VTerm *vterm, int button, int pressed)
950{
951 VTermModifier mod = VTERM_MOD_NONE;
952
953 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200954 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100955 if (button != 0)
956 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200957 return TRUE;
958}
959
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100960static int enter_mouse_col = -1;
961static int enter_mouse_row = -1;
962
963/*
964 * Handle a mouse click, drag or release.
965 * Return TRUE when a mouse event is sent to the terminal.
966 */
967 static int
968term_mouse_click(VTerm *vterm, int key)
969{
970#if defined(FEAT_CLIPBOARD)
971 /* For modeless selection mouse drag and release events are ignored, unless
972 * they are preceded with a mouse down event */
973 static int ignore_drag_release = TRUE;
974 VTermMouseState mouse_state;
975
976 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
977 if (mouse_state.flags == 0)
978 {
979 /* Terminal is not using the mouse, use modeless selection. */
980 switch (key)
981 {
982 case K_LEFTDRAG:
983 case K_LEFTRELEASE:
984 case K_RIGHTDRAG:
985 case K_RIGHTRELEASE:
986 /* Ignore drag and release events when the button-down wasn't
987 * seen before. */
988 if (ignore_drag_release)
989 {
990 int save_mouse_col, save_mouse_row;
991
992 if (enter_mouse_col < 0)
993 break;
994
995 /* mouse click in the window gave us focus, handle that
996 * click now */
997 save_mouse_col = mouse_col;
998 save_mouse_row = mouse_row;
999 mouse_col = enter_mouse_col;
1000 mouse_row = enter_mouse_row;
1001 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1002 mouse_col = save_mouse_col;
1003 mouse_row = save_mouse_row;
1004 }
1005 /* FALLTHROUGH */
1006 case K_LEFTMOUSE:
1007 case K_RIGHTMOUSE:
1008 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1009 ignore_drag_release = TRUE;
1010 else
1011 ignore_drag_release = FALSE;
1012 /* Should we call mouse_has() here? */
1013 if (clip_star.available)
1014 {
1015 int button, is_click, is_drag;
1016
1017 button = get_mouse_button(KEY2TERMCAP1(key),
1018 &is_click, &is_drag);
1019 if (mouse_model_popup() && button == MOUSE_LEFT
1020 && (mod_mask & MOD_MASK_SHIFT))
1021 {
1022 /* Translate shift-left to right button. */
1023 button = MOUSE_RIGHT;
1024 mod_mask &= ~MOD_MASK_SHIFT;
1025 }
1026 clip_modeless(button, is_click, is_drag);
1027 }
1028 break;
1029
1030 case K_MIDDLEMOUSE:
1031 if (clip_star.available)
1032 insert_reg('*', TRUE);
1033 break;
1034 }
1035 enter_mouse_col = -1;
1036 return FALSE;
1037 }
1038#endif
1039 enter_mouse_col = -1;
1040
1041 switch (key)
1042 {
1043 case K_LEFTMOUSE:
1044 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1045 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1046 case K_LEFTRELEASE:
1047 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1048 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1049 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1050 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1051 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1052 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1053 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1054 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1055 }
1056 return TRUE;
1057}
1058
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001059/*
1060 * Convert typed key "c" into bytes to send to the job.
1061 * Return the number of bytes in "buf".
1062 */
1063 static int
1064term_convert_key(term_T *term, int c, char *buf)
1065{
1066 VTerm *vterm = term->tl_vterm;
1067 VTermKey key = VTERM_KEY_NONE;
1068 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001069 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001070
1071 switch (c)
1072 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001073 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1074
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001075 /* don't use VTERM_KEY_BACKSPACE, it always
1076 * becomes 0x7f DEL */
1077 case K_BS: c = term_backspace_char; break;
1078
1079 case ESC: key = VTERM_KEY_ESCAPE; break;
1080 case K_DEL: key = VTERM_KEY_DEL; break;
1081 case K_DOWN: key = VTERM_KEY_DOWN; break;
1082 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1083 key = VTERM_KEY_DOWN; break;
1084 case K_END: key = VTERM_KEY_END; break;
1085 case K_S_END: mod = VTERM_MOD_SHIFT;
1086 key = VTERM_KEY_END; break;
1087 case K_C_END: mod = VTERM_MOD_CTRL;
1088 key = VTERM_KEY_END; break;
1089 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1090 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1091 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1092 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1093 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1094 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1095 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1096 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1097 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1098 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1099 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1100 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1101 case K_HOME: key = VTERM_KEY_HOME; break;
1102 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1103 key = VTERM_KEY_HOME; break;
1104 case K_C_HOME: mod = VTERM_MOD_CTRL;
1105 key = VTERM_KEY_HOME; break;
1106 case K_INS: key = VTERM_KEY_INS; break;
1107 case K_K0: key = VTERM_KEY_KP_0; break;
1108 case K_K1: key = VTERM_KEY_KP_1; break;
1109 case K_K2: key = VTERM_KEY_KP_2; break;
1110 case K_K3: key = VTERM_KEY_KP_3; break;
1111 case K_K4: key = VTERM_KEY_KP_4; break;
1112 case K_K5: key = VTERM_KEY_KP_5; break;
1113 case K_K6: key = VTERM_KEY_KP_6; break;
1114 case K_K7: key = VTERM_KEY_KP_7; break;
1115 case K_K8: key = VTERM_KEY_KP_8; break;
1116 case K_K9: key = VTERM_KEY_KP_9; break;
1117 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1118 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1119 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1120 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1121 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1122 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1123 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1124 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1125 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1126 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1127 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1128 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1129 case K_LEFT: key = VTERM_KEY_LEFT; break;
1130 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1131 key = VTERM_KEY_LEFT; break;
1132 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1133 key = VTERM_KEY_LEFT; break;
1134 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1135 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1136 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1137 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1138 key = VTERM_KEY_RIGHT; break;
1139 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1140 key = VTERM_KEY_RIGHT; break;
1141 case K_UP: key = VTERM_KEY_UP; break;
1142 case K_S_UP: mod = VTERM_MOD_SHIFT;
1143 key = VTERM_KEY_UP; break;
1144 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001145 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1146 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001147
Bram Moolenaara42ad572017-11-16 13:08:04 +01001148 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1149 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001150 case K_MOUSELEFT: /* TODO */ return 0;
1151 case K_MOUSERIGHT: /* TODO */ return 0;
1152
1153 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001154 case K_LEFTMOUSE_NM:
1155 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001156 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001157 case K_LEFTRELEASE_NM:
1158 case K_MOUSEMOVE:
1159 case K_MIDDLEMOUSE:
1160 case K_MIDDLEDRAG:
1161 case K_MIDDLERELEASE:
1162 case K_RIGHTMOUSE:
1163 case K_RIGHTDRAG:
1164 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1165 return 0;
1166 other = TRUE;
1167 break;
1168
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001169 case K_X1MOUSE: /* TODO */ return 0;
1170 case K_X1DRAG: /* TODO */ return 0;
1171 case K_X1RELEASE: /* TODO */ return 0;
1172 case K_X2MOUSE: /* TODO */ return 0;
1173 case K_X2DRAG: /* TODO */ return 0;
1174 case K_X2RELEASE: /* TODO */ return 0;
1175
1176 case K_IGNORE: return 0;
1177 case K_NOP: return 0;
1178 case K_UNDO: return 0;
1179 case K_HELP: return 0;
1180 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1181 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1182 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1183 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1184 case K_SELECT: return 0;
1185#ifdef FEAT_GUI
1186 case K_VER_SCROLLBAR: return 0;
1187 case K_HOR_SCROLLBAR: return 0;
1188#endif
1189#ifdef FEAT_GUI_TABLINE
1190 case K_TABLINE: return 0;
1191 case K_TABMENU: return 0;
1192#endif
1193#ifdef FEAT_NETBEANS_INTG
1194 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1195#endif
1196#ifdef FEAT_DND
1197 case K_DROP: return 0;
1198#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001199 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001200 case K_PS: vterm_keyboard_start_paste(vterm);
1201 other = TRUE;
1202 break;
1203 case K_PE: vterm_keyboard_end_paste(vterm);
1204 other = TRUE;
1205 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001206 }
1207
1208 /*
1209 * Convert special keys to vterm keys:
1210 * - Write keys to vterm: vterm_keyboard_key()
1211 * - Write output to channel.
1212 * TODO: use mod_mask
1213 */
1214 if (key != VTERM_KEY_NONE)
1215 /* Special key, let vterm convert it. */
1216 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001217 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001218 /* Normal character, let vterm convert it. */
1219 vterm_keyboard_unichar(vterm, c, mod);
1220
1221 /* Read back the converted escape sequence. */
1222 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1223}
1224
1225/*
1226 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001227 * If "check_job_status" is TRUE update the job status.
1228 */
1229 static int
1230term_job_running_check(term_T *term, int check_job_status)
1231{
1232 /* Also consider the job finished when the channel is closed, to avoid a
1233 * race condition when updating the title. */
1234 if (term != NULL
1235 && term->tl_job != NULL
1236 && channel_is_open(term->tl_job->jv_channel))
1237 {
1238 if (check_job_status)
1239 job_status(term->tl_job);
1240 return (term->tl_job->jv_status == JOB_STARTED
1241 || term->tl_job->jv_channel->ch_keep_open);
1242 }
1243 return FALSE;
1244}
1245
1246/*
1247 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001248 */
1249 int
1250term_job_running(term_T *term)
1251{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001252 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001253}
1254
1255/*
1256 * Return TRUE if "term" has an active channel and used ":term NONE".
1257 */
1258 int
1259term_none_open(term_T *term)
1260{
1261 /* Also consider the job finished when the channel is closed, to avoid a
1262 * race condition when updating the title. */
1263 return term != NULL
1264 && term->tl_job != NULL
1265 && channel_is_open(term->tl_job->jv_channel)
1266 && term->tl_job->jv_channel->ch_keep_open;
1267}
1268
1269/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001270 * Used when exiting: kill the job in "buf" if so desired.
1271 * Return OK when the job finished.
1272 * Return FAIL when the job is still running.
1273 */
1274 int
1275term_try_stop_job(buf_T *buf)
1276{
1277 int count;
1278 char *how = (char *)buf->b_term->tl_kill;
1279
1280#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1281 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1282 {
1283 char_u buff[DIALOG_MSG_SIZE];
1284 int ret;
1285
1286 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1287 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1288 if (ret == VIM_YES)
1289 how = "kill";
1290 else if (ret == VIM_CANCEL)
1291 return FAIL;
1292 }
1293#endif
1294 if (how == NULL || *how == NUL)
1295 return FAIL;
1296
1297 job_stop(buf->b_term->tl_job, NULL, how);
1298
1299 /* wait for up to a second for the job to die */
1300 for (count = 0; count < 100; ++count)
1301 {
1302 /* buffer, terminal and job may be cleaned up while waiting */
1303 if (!buf_valid(buf)
1304 || buf->b_term == NULL
1305 || buf->b_term->tl_job == NULL)
1306 return OK;
1307
1308 /* call job_status() to update jv_status */
1309 job_status(buf->b_term->tl_job);
1310 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1311 return OK;
1312 ui_delay(10L, FALSE);
1313 mch_check_messages();
1314 parse_queued_messages();
1315 }
1316 return FAIL;
1317}
1318
1319/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001320 * Add the last line of the scrollback buffer to the buffer in the window.
1321 */
1322 static void
1323add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1324{
1325 buf_T *buf = term->tl_buffer;
1326 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1327 linenr_T lnum = buf->b_ml.ml_line_count;
1328
1329#ifdef WIN3264
1330 if (!enc_utf8 && enc_codepage > 0)
1331 {
1332 WCHAR *ret = NULL;
1333 int length = 0;
1334
1335 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1336 &ret, &length);
1337 if (ret != NULL)
1338 {
1339 WideCharToMultiByte_alloc(enc_codepage, 0,
1340 ret, length, (char **)&text, &len, 0, 0);
1341 vim_free(ret);
1342 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1343 vim_free(text);
1344 }
1345 }
1346 else
1347#endif
1348 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1349 if (empty)
1350 {
1351 /* Delete the empty line that was in the empty buffer. */
1352 curbuf = buf;
1353 ml_delete(1, FALSE);
1354 curbuf = curwin->w_buffer;
1355 }
1356}
1357
1358 static void
1359cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1360{
1361 attr->width = cell->width;
1362 attr->attrs = cell->attrs;
1363 attr->fg = cell->fg;
1364 attr->bg = cell->bg;
1365}
1366
1367 static int
1368equal_celattr(cellattr_T *a, cellattr_T *b)
1369{
1370 /* Comparing the colors should be sufficient. */
1371 return a->fg.red == b->fg.red
1372 && a->fg.green == b->fg.green
1373 && a->fg.blue == b->fg.blue
1374 && a->bg.red == b->bg.red
1375 && a->bg.green == b->bg.green
1376 && a->bg.blue == b->bg.blue;
1377}
1378
Bram Moolenaard96ff162018-02-18 22:13:29 +01001379/*
1380 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1381 * line at this position. Otherwise at the end.
1382 */
1383 static int
1384add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1385{
1386 if (ga_grow(&term->tl_scrollback, 1) == OK)
1387 {
1388 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1389 + term->tl_scrollback.ga_len;
1390
1391 if (lnum > 0)
1392 {
1393 int i;
1394
1395 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1396 {
1397 *line = *(line - 1);
1398 --line;
1399 }
1400 }
1401 line->sb_cols = 0;
1402 line->sb_cells = NULL;
1403 line->sb_fill_attr = *fill_attr;
1404 ++term->tl_scrollback.ga_len;
1405 return OK;
1406 }
1407 return FALSE;
1408}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001409
1410/*
1411 * Add the current lines of the terminal to scrollback and to the buffer.
1412 * Called after the job has ended and when switching to Terminal-Normal mode.
1413 */
1414 static void
1415move_terminal_to_buffer(term_T *term)
1416{
1417 win_T *wp;
1418 int len;
1419 int lines_skipped = 0;
1420 VTermPos pos;
1421 VTermScreenCell cell;
1422 cellattr_T fill_attr, new_fill_attr;
1423 cellattr_T *p;
1424 VTermScreen *screen;
1425
1426 if (term->tl_vterm == NULL)
1427 return;
1428 screen = vterm_obtain_screen(term->tl_vterm);
1429 fill_attr = new_fill_attr = term->tl_default_color;
1430
1431 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1432 {
1433 len = 0;
1434 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1435 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1436 && cell.chars[0] != NUL)
1437 {
1438 len = pos.col + 1;
1439 new_fill_attr = term->tl_default_color;
1440 }
1441 else
1442 /* Assume the last attr is the filler attr. */
1443 cell2cellattr(&cell, &new_fill_attr);
1444
1445 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1446 ++lines_skipped;
1447 else
1448 {
1449 while (lines_skipped > 0)
1450 {
1451 /* Line was skipped, add an empty line. */
1452 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001453 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001454 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001455 }
1456
1457 if (len == 0)
1458 p = NULL;
1459 else
1460 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1461 if ((p != NULL || len == 0)
1462 && ga_grow(&term->tl_scrollback, 1) == OK)
1463 {
1464 garray_T ga;
1465 int width;
1466 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1467 + term->tl_scrollback.ga_len;
1468
1469 ga_init2(&ga, 1, 100);
1470 for (pos.col = 0; pos.col < len; pos.col += width)
1471 {
1472 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1473 {
1474 width = 1;
1475 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1476 if (ga_grow(&ga, 1) == OK)
1477 ga.ga_len += utf_char2bytes(' ',
1478 (char_u *)ga.ga_data + ga.ga_len);
1479 }
1480 else
1481 {
1482 width = cell.width;
1483
1484 cell2cellattr(&cell, &p[pos.col]);
1485
1486 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1487 {
1488 int i;
1489 int c;
1490
1491 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1492 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1493 (char_u *)ga.ga_data + ga.ga_len);
1494 }
1495 }
1496 }
1497 line->sb_cols = len;
1498 line->sb_cells = p;
1499 line->sb_fill_attr = new_fill_attr;
1500 fill_attr = new_fill_attr;
1501 ++term->tl_scrollback.ga_len;
1502
1503 if (ga_grow(&ga, 1) == FAIL)
1504 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1505 else
1506 {
1507 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1508 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1509 }
1510 ga_clear(&ga);
1511 }
1512 else
1513 vim_free(p);
1514 }
1515 }
1516
1517 /* Obtain the current background color. */
1518 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1519 &term->tl_default_color.fg, &term->tl_default_color.bg);
1520
1521 FOR_ALL_WINDOWS(wp)
1522 {
1523 if (wp->w_buffer == term->tl_buffer)
1524 {
1525 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1526 wp->w_cursor.col = 0;
1527 wp->w_valid = 0;
1528 if (wp->w_cursor.lnum >= wp->w_height)
1529 {
1530 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1531
1532 if (wp->w_topline < min_topline)
1533 wp->w_topline = min_topline;
1534 }
1535 redraw_win_later(wp, NOT_VALID);
1536 }
1537 }
1538}
1539
1540 static void
1541set_terminal_mode(term_T *term, int normal_mode)
1542{
1543 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001544 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001545 if (term->tl_buffer == curbuf)
1546 maketitle();
1547}
1548
1549/*
1550 * Called after the job if finished and Terminal mode is not active:
1551 * Move the vterm contents into the scrollback buffer and free the vterm.
1552 */
1553 static void
1554cleanup_vterm(term_T *term)
1555{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001556 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001557 move_terminal_to_buffer(term);
1558 term_free_vterm(term);
1559 set_terminal_mode(term, FALSE);
1560}
1561
1562/*
1563 * Switch from Terminal-Job mode to Terminal-Normal mode.
1564 * Suspends updating the terminal window.
1565 */
1566 static void
1567term_enter_normal_mode(void)
1568{
1569 term_T *term = curbuf->b_term;
1570
1571 /* Append the current terminal contents to the buffer. */
1572 move_terminal_to_buffer(term);
1573
1574 set_terminal_mode(term, TRUE);
1575
1576 /* Move the window cursor to the position of the cursor in the
1577 * terminal. */
1578 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1579 + term->tl_cursor_pos.row + 1;
1580 check_cursor();
1581 coladvance(term->tl_cursor_pos.col);
1582
1583 /* Display the same lines as in the terminal. */
1584 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1585}
1586
1587/*
1588 * Returns TRUE if the current window contains a terminal and we are in
1589 * Terminal-Normal mode.
1590 */
1591 int
1592term_in_normal_mode(void)
1593{
1594 term_T *term = curbuf->b_term;
1595
1596 return term != NULL && term->tl_normal_mode;
1597}
1598
1599/*
1600 * Switch from Terminal-Normal mode to Terminal-Job mode.
1601 * Restores updating the terminal window.
1602 */
1603 void
1604term_enter_job_mode()
1605{
1606 term_T *term = curbuf->b_term;
1607 sb_line_T *line;
1608 garray_T *gap;
1609
1610 /* Remove the terminal contents from the scrollback and the buffer. */
1611 gap = &term->tl_scrollback;
1612 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1613 && gap->ga_len > 0)
1614 {
1615 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1616 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1617 vim_free(line->sb_cells);
1618 --gap->ga_len;
1619 }
1620 check_cursor();
1621
1622 set_terminal_mode(term, FALSE);
1623
1624 if (term->tl_channel_closed)
1625 cleanup_vterm(term);
1626 redraw_buf_and_status_later(curbuf, NOT_VALID);
1627}
1628
1629/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001630 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001631 * Note: while waiting a terminal may be closed and freed if the channel is
1632 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001633 */
1634 static int
1635term_vgetc()
1636{
1637 int c;
1638 int save_State = State;
1639
1640 State = TERMINAL;
1641 got_int = FALSE;
1642#ifdef WIN3264
1643 ctrl_break_was_pressed = FALSE;
1644#endif
1645 c = vgetc();
1646 got_int = FALSE;
1647 State = save_State;
1648 return c;
1649}
1650
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001651static int mouse_was_outside = FALSE;
1652
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654 * Send keys to terminal.
1655 * Return FAIL when the key needs to be handled in Normal mode.
1656 * Return OK when the key was dropped or sent to the terminal.
1657 */
1658 int
1659send_keys_to_term(term_T *term, int c, int typed)
1660{
1661 char msg[KEY_BUF_LEN];
1662 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001663 int dragging_outside = FALSE;
1664
1665 /* Catch keys that need to be handled as in Normal mode. */
1666 switch (c)
1667 {
1668 case NUL:
1669 case K_ZERO:
1670 if (typed)
1671 stuffcharReadbuff(c);
1672 return FAIL;
1673
1674 case K_IGNORE:
1675 return FAIL;
1676
1677 case K_LEFTDRAG:
1678 case K_MIDDLEDRAG:
1679 case K_RIGHTDRAG:
1680 case K_X1DRAG:
1681 case K_X2DRAG:
1682 dragging_outside = mouse_was_outside;
1683 /* FALLTHROUGH */
1684 case K_LEFTMOUSE:
1685 case K_LEFTMOUSE_NM:
1686 case K_LEFTRELEASE:
1687 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001688 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001689 case K_MIDDLEMOUSE:
1690 case K_MIDDLERELEASE:
1691 case K_RIGHTMOUSE:
1692 case K_RIGHTRELEASE:
1693 case K_X1MOUSE:
1694 case K_X1RELEASE:
1695 case K_X2MOUSE:
1696 case K_X2RELEASE:
1697
1698 case K_MOUSEUP:
1699 case K_MOUSEDOWN:
1700 case K_MOUSELEFT:
1701 case K_MOUSERIGHT:
1702 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001703 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001704 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001705 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706 || dragging_outside)
1707 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001708 /* click or scroll outside the current window or on status line
1709 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001710 if (typed)
1711 {
1712 stuffcharReadbuff(c);
1713 mouse_was_outside = TRUE;
1714 }
1715 return FAIL;
1716 }
1717 }
1718 if (typed)
1719 mouse_was_outside = FALSE;
1720
1721 /* Convert the typed key to a sequence of bytes for the job. */
1722 len = term_convert_key(term, c, msg);
1723 if (len > 0)
1724 /* TODO: if FAIL is returned, stop? */
1725 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1726 (char_u *)msg, (int)len, NULL);
1727
1728 return OK;
1729}
1730
1731 static void
1732position_cursor(win_T *wp, VTermPos *pos)
1733{
1734 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1735 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1736 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1737}
1738
1739/*
1740 * Handle CTRL-W "": send register contents to the job.
1741 */
1742 static void
1743term_paste_register(int prev_c UNUSED)
1744{
1745 int c;
1746 list_T *l;
1747 listitem_T *item;
1748 long reglen = 0;
1749 int type;
1750
1751#ifdef FEAT_CMDL_INFO
1752 if (add_to_showcmd(prev_c))
1753 if (add_to_showcmd('"'))
1754 out_flush();
1755#endif
1756 c = term_vgetc();
1757#ifdef FEAT_CMDL_INFO
1758 clear_showcmd();
1759#endif
1760 if (!term_use_loop())
1761 /* job finished while waiting for a character */
1762 return;
1763
1764 /* CTRL-W "= prompt for expression to evaluate. */
1765 if (c == '=' && get_expr_register() != '=')
1766 return;
1767 if (!term_use_loop())
1768 /* job finished while waiting for a character */
1769 return;
1770
1771 l = (list_T *)get_reg_contents(c, GREG_LIST);
1772 if (l != NULL)
1773 {
1774 type = get_reg_type(c, &reglen);
1775 for (item = l->lv_first; item != NULL; item = item->li_next)
1776 {
1777 char_u *s = get_tv_string(&item->li_tv);
1778#ifdef WIN3264
1779 char_u *tmp = s;
1780
1781 if (!enc_utf8 && enc_codepage > 0)
1782 {
1783 WCHAR *ret = NULL;
1784 int length = 0;
1785
1786 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1787 (int)STRLEN(s), &ret, &length);
1788 if (ret != NULL)
1789 {
1790 WideCharToMultiByte_alloc(CP_UTF8, 0,
1791 ret, length, (char **)&s, &length, 0, 0);
1792 vim_free(ret);
1793 }
1794 }
1795#endif
1796 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1797 s, (int)STRLEN(s), NULL);
1798#ifdef WIN3264
1799 if (tmp != s)
1800 vim_free(s);
1801#endif
1802
1803 if (item->li_next != NULL || type == MLINE)
1804 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1805 (char_u *)"\r", 1, NULL);
1806 }
1807 list_free(l);
1808 }
1809}
1810
1811#if defined(FEAT_GUI) || defined(PROTO)
1812/*
1813 * Return TRUE when the cursor of the terminal should be displayed.
1814 */
1815 int
1816terminal_is_active()
1817{
1818 return in_terminal_loop != NULL;
1819}
1820
1821 cursorentry_T *
1822term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1823{
1824 term_T *term = in_terminal_loop;
1825 static cursorentry_T entry;
1826
1827 vim_memset(&entry, 0, sizeof(entry));
1828 entry.shape = entry.mshape =
1829 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1830 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1831 SHAPE_BLOCK;
1832 entry.percentage = 20;
1833 if (term->tl_cursor_blink)
1834 {
1835 entry.blinkwait = 700;
1836 entry.blinkon = 400;
1837 entry.blinkoff = 250;
1838 }
1839 *fg = gui.back_pixel;
1840 if (term->tl_cursor_color == NULL)
1841 *bg = gui.norm_pixel;
1842 else
1843 *bg = color_name2handle(term->tl_cursor_color);
1844 entry.name = "n";
1845 entry.used_for = SHAPE_CURSOR;
1846
1847 return &entry;
1848}
1849#endif
1850
Bram Moolenaard317b382018-02-08 22:33:31 +01001851 static void
1852may_output_cursor_props(void)
1853{
1854 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1855 || last_set_cursor_shape != desired_cursor_shape
1856 || last_set_cursor_blink != desired_cursor_blink)
1857 {
1858 last_set_cursor_color = desired_cursor_color;
1859 last_set_cursor_shape = desired_cursor_shape;
1860 last_set_cursor_blink = desired_cursor_blink;
1861 term_cursor_color(desired_cursor_color);
1862 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1863 /* this will restore the initial cursor style, if possible */
1864 ui_cursor_shape_forced(TRUE);
1865 else
1866 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1867 }
1868}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001869
Bram Moolenaard317b382018-02-08 22:33:31 +01001870/*
1871 * Set the cursor color and shape, if not last set to these.
1872 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873 static void
1874may_set_cursor_props(term_T *term)
1875{
1876#ifdef FEAT_GUI
1877 /* For the GUI the cursor properties are obtained with
1878 * term_get_cursor_shape(). */
1879 if (gui.in_use)
1880 return;
1881#endif
1882 if (in_terminal_loop == term)
1883 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001885 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001887 desired_cursor_color = (char_u *)"";
1888 desired_cursor_shape = term->tl_cursor_shape;
1889 desired_cursor_blink = term->tl_cursor_blink;
1890 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001891 }
1892}
1893
Bram Moolenaard317b382018-02-08 22:33:31 +01001894/*
1895 * Reset the desired cursor properties and restore them when needed.
1896 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001898prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899{
1900#ifdef FEAT_GUI
1901 if (gui.in_use)
1902 return;
1903#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001904 desired_cursor_color = (char_u *)"";
1905 desired_cursor_shape = -1;
1906 desired_cursor_blink = -1;
1907 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001908}
1909
1910/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001911 * Returns TRUE if the current window contains a terminal and we are sending
1912 * keys to the job.
1913 * If "check_job_status" is TRUE update the job status.
1914 */
1915 static int
1916term_use_loop_check(int check_job_status)
1917{
1918 term_T *term = curbuf->b_term;
1919
1920 return term != NULL
1921 && !term->tl_normal_mode
1922 && term->tl_vterm != NULL
1923 && term_job_running_check(term, check_job_status);
1924}
1925
1926/*
1927 * Returns TRUE if the current window contains a terminal and we are sending
1928 * keys to the job.
1929 */
1930 int
1931term_use_loop(void)
1932{
1933 return term_use_loop_check(FALSE);
1934}
1935
1936/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001937 * Called when entering a window with the mouse. If this is a terminal window
1938 * we may want to change state.
1939 */
1940 void
1941term_win_entered()
1942{
1943 term_T *term = curbuf->b_term;
1944
1945 if (term != NULL)
1946 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001947 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001948 {
1949 reset_VIsual_and_resel();
1950 if (State & INSERT)
1951 stop_insert_mode = TRUE;
1952 }
1953 mouse_was_outside = FALSE;
1954 enter_mouse_col = mouse_col;
1955 enter_mouse_row = mouse_row;
1956 }
1957}
1958
1959/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 * Wait for input and send it to the job.
1961 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1962 * when there is no more typahead.
1963 * Return when the start of a CTRL-W command is typed or anything else that
1964 * should be handled as a Normal mode command.
1965 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1966 * the terminal was closed.
1967 */
1968 int
1969terminal_loop(int blocking)
1970{
1971 int c;
1972 int termkey = 0;
1973 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001974#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001975 int tty_fd = curbuf->b_term->tl_job->jv_channel
1976 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001977#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001978 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979
1980 /* Remember the terminal we are sending keys to. However, the terminal
1981 * might be closed while waiting for a character, e.g. typing "exit" in a
1982 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1983 * stored reference. */
1984 in_terminal_loop = curbuf->b_term;
1985
1986 if (*curwin->w_p_tk != NUL)
1987 termkey = string_to_key(curwin->w_p_tk, TRUE);
1988 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1989 may_set_cursor_props(curbuf->b_term);
1990
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001991 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992 {
Bram Moolenaar13568252018-03-16 20:46:58 +01001993#ifdef FEAT_GUI
1994 if (!curbuf->b_term->tl_system)
1995#endif
1996 /* TODO: skip screen update when handling a sequence of keys. */
1997 /* Repeat redrawing in case a message is received while redrawing.
1998 */
1999 while (must_redraw != 0)
2000 if (update_screen(0) == FAIL)
2001 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002003 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002004
2005 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002006 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002007 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002008 /* Job finished while waiting for a character. Push back the
2009 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002010 if (c != K_IGNORE)
2011 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002012 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002013 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002014 if (c == K_IGNORE)
2015 continue;
2016
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002017#ifdef UNIX
2018 /*
2019 * The shell or another program may change the tty settings. Getting
2020 * them for every typed character is a bit of overhead, but it's needed
2021 * for the first character typed, e.g. when Vim starts in a shell.
2022 */
2023 if (isatty(tty_fd))
2024 {
2025 ttyinfo_T info;
2026
2027 /* Get the current backspace character of the pty. */
2028 if (get_tty_info(tty_fd, &info) == OK)
2029 term_backspace_char = info.backspace;
2030 }
2031#endif
2032
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033#ifdef WIN3264
2034 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2035 * Use CTRL-BREAK to kill the job. */
2036 if (ctrl_break_was_pressed)
2037 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2038#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002039 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2040 * Not in a system terminal. */
2041 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2042#ifdef FEAT_GUI
2043 && !curbuf->b_term->tl_system
2044#endif
2045 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002046 {
2047 int prev_c = c;
2048
2049#ifdef FEAT_CMDL_INFO
2050 if (add_to_showcmd(c))
2051 out_flush();
2052#endif
2053 c = term_vgetc();
2054#ifdef FEAT_CMDL_INFO
2055 clear_showcmd();
2056#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002057 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002058 /* job finished while waiting for a character */
2059 break;
2060
2061 if (prev_c == Ctrl_BSL)
2062 {
2063 if (c == Ctrl_N)
2064 {
2065 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2066 term_enter_normal_mode();
2067 ret = FAIL;
2068 goto theend;
2069 }
2070 /* Send both keys to the terminal. */
2071 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2072 }
2073 else if (c == Ctrl_C)
2074 {
2075 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2076 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2077 }
2078 else if (termkey == 0 && c == '.')
2079 {
2080 /* "CTRL-W .": send CTRL-W to the job */
2081 c = Ctrl_W;
2082 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002083 else if (termkey == 0 && c == Ctrl_BSL)
2084 {
2085 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2086 c = Ctrl_BSL;
2087 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002088 else if (c == 'N')
2089 {
2090 /* CTRL-W N : go to Terminal-Normal mode. */
2091 term_enter_normal_mode();
2092 ret = FAIL;
2093 goto theend;
2094 }
2095 else if (c == '"')
2096 {
2097 term_paste_register(prev_c);
2098 continue;
2099 }
2100 else if (termkey == 0 || c != termkey)
2101 {
2102 stuffcharReadbuff(Ctrl_W);
2103 stuffcharReadbuff(c);
2104 ret = OK;
2105 goto theend;
2106 }
2107 }
2108# ifdef WIN3264
2109 if (!enc_utf8 && has_mbyte && c >= 0x80)
2110 {
2111 WCHAR wc;
2112 char_u mb[3];
2113
2114 mb[0] = (unsigned)c >> 8;
2115 mb[1] = c;
2116 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2117 c = wc;
2118 }
2119# endif
2120 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2121 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002122 if (c == K_MOUSEMOVE)
2123 /* We are sure to come back here, don't reset the cursor color
2124 * and shape to avoid flickering. */
2125 restore_cursor = FALSE;
2126
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002127 ret = OK;
2128 goto theend;
2129 }
2130 }
2131 ret = FAIL;
2132
2133theend:
2134 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002135 if (restore_cursor)
2136 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002137 return ret;
2138}
2139
2140/*
2141 * Called when a job has finished.
2142 * This updates the title and status, but does not close the vterm, because
2143 * there might still be pending output in the channel.
2144 */
2145 void
2146term_job_ended(job_T *job)
2147{
2148 term_T *term;
2149 int did_one = FALSE;
2150
2151 for (term = first_term; term != NULL; term = term->tl_next)
2152 if (term->tl_job == job)
2153 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002154 VIM_CLEAR(term->tl_title);
2155 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 redraw_buf_and_status_later(term->tl_buffer, VALID);
2157 did_one = TRUE;
2158 }
2159 if (did_one)
2160 redraw_statuslines();
2161 if (curbuf->b_term != NULL)
2162 {
2163 if (curbuf->b_term->tl_job == job)
2164 maketitle();
2165 update_cursor(curbuf->b_term, TRUE);
2166 }
2167}
2168
2169 static void
2170may_toggle_cursor(term_T *term)
2171{
2172 if (in_terminal_loop == term)
2173 {
2174 if (term->tl_cursor_visible)
2175 cursor_on();
2176 else
2177 cursor_off();
2178 }
2179}
2180
2181/*
2182 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002183 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 */
2185 static int
2186color2index(VTermColor *color, int fg, int *boldp)
2187{
2188 int red = color->red;
2189 int blue = color->blue;
2190 int green = color->green;
2191
Bram Moolenaar46359e12017-11-29 22:33:38 +01002192 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002193 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002194 /* First 16 colors and default: use the ANSI index, because these
2195 * colors can be redefined. */
2196 if (t_colors >= 16)
2197 return color->ansi_index;
2198 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002199 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002200 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002201 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002202 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2203 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2204 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002205 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002206 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2207 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2208 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2209 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2210 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2211 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2212 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2213 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2214 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2215 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2216 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 }
2218 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002219
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002220 if (t_colors >= 256)
2221 {
2222 if (red == blue && red == green)
2223 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002224 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002225 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002226 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2227 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2228 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 int i;
2230
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002231 if (red < 5)
2232 return 17; /* 00/00/00 */
2233 if (red > 245) /* ff/ff/ff */
2234 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002235 for (i = 0; i < 23; ++i)
2236 if (red < cutoff[i])
2237 return i + 233;
2238 return 256;
2239 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002240 {
2241 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2242 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002243
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002244 /* 216-color cube */
2245 for (ri = 0; ri < 5; ++ri)
2246 if (red < cutoff[ri])
2247 break;
2248 for (gi = 0; gi < 5; ++gi)
2249 if (green < cutoff[gi])
2250 break;
2251 for (bi = 0; bi < 5; ++bi)
2252 if (blue < cutoff[bi])
2253 break;
2254 return 17 + ri * 36 + gi * 6 + bi;
2255 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 }
2257 return 0;
2258}
2259
2260/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002261 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262 */
2263 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002264vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265{
2266 int attr = 0;
2267
2268 if (cellattrs.bold)
2269 attr |= HL_BOLD;
2270 if (cellattrs.underline)
2271 attr |= HL_UNDERLINE;
2272 if (cellattrs.italic)
2273 attr |= HL_ITALIC;
2274 if (cellattrs.strike)
2275 attr |= HL_STRIKETHROUGH;
2276 if (cellattrs.reverse)
2277 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002278 return attr;
2279}
2280
2281/*
2282 * Store Vterm attributes in "cell" from highlight flags.
2283 */
2284 static void
2285hl2vtermAttr(int attr, cellattr_T *cell)
2286{
2287 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2288 if (attr & HL_BOLD)
2289 cell->attrs.bold = 1;
2290 if (attr & HL_UNDERLINE)
2291 cell->attrs.underline = 1;
2292 if (attr & HL_ITALIC)
2293 cell->attrs.italic = 1;
2294 if (attr & HL_STRIKETHROUGH)
2295 cell->attrs.strike = 1;
2296 if (attr & HL_INVERSE)
2297 cell->attrs.reverse = 1;
2298}
2299
2300/*
2301 * Convert the attributes of a vterm cell into an attribute index.
2302 */
2303 static int
2304cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2305{
2306 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002307
2308#ifdef FEAT_GUI
2309 if (gui.in_use)
2310 {
2311 guicolor_T fg, bg;
2312
2313 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2314 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2315 return get_gui_attr_idx(attr, fg, bg);
2316 }
2317 else
2318#endif
2319#ifdef FEAT_TERMGUICOLORS
2320 if (p_tgc)
2321 {
2322 guicolor_T fg, bg;
2323
2324 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2325 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2326
2327 return get_tgc_attr_idx(attr, fg, bg);
2328 }
2329 else
2330#endif
2331 {
2332 int bold = MAYBE;
2333 int fg = color2index(&cellfg, TRUE, &bold);
2334 int bg = color2index(&cellbg, FALSE, &bold);
2335
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002336 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002337 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002338 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002339 if (fg == 0 && term_default_cterm_fg >= 0)
2340 fg = term_default_cterm_fg + 1;
2341 if (bg == 0 && term_default_cterm_bg >= 0)
2342 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002343 }
2344
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002345 /* with 8 colors set the bold attribute to get a bright foreground */
2346 if (bold == TRUE)
2347 attr |= HL_BOLD;
2348 return get_cterm_attr_idx(attr, fg, bg);
2349 }
2350 return 0;
2351}
2352
2353 static int
2354handle_damage(VTermRect rect, void *user)
2355{
2356 term_T *term = (term_T *)user;
2357
2358 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2359 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2360 redraw_buf_later(term->tl_buffer, NOT_VALID);
2361 return 1;
2362}
2363
2364 static int
2365handle_moverect(VTermRect dest, VTermRect src, void *user)
2366{
2367 term_T *term = (term_T *)user;
2368
2369 /* Scrolling up is done much more efficiently by deleting lines instead of
2370 * redrawing the text. */
2371 if (dest.start_col == src.start_col
2372 && dest.end_col == src.end_col
2373 && dest.start_row < src.start_row)
2374 {
2375 win_T *wp;
2376 VTermColor fg, bg;
2377 VTermScreenCellAttrs attr;
2378 int clear_attr;
2379
2380 /* Set the color to clear lines with. */
2381 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2382 &fg, &bg);
2383 vim_memset(&attr, 0, sizeof(attr));
2384 clear_attr = cell2attr(attr, fg, bg);
2385
2386 FOR_ALL_WINDOWS(wp)
2387 {
2388 if (wp->w_buffer == term->tl_buffer)
2389 win_del_lines(wp, dest.start_row,
2390 src.start_row - dest.start_row, FALSE, FALSE,
2391 clear_attr);
2392 }
2393 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002394
2395 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2396 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398 redraw_buf_later(term->tl_buffer, NOT_VALID);
2399 return 1;
2400}
2401
2402 static int
2403handle_movecursor(
2404 VTermPos pos,
2405 VTermPos oldpos UNUSED,
2406 int visible,
2407 void *user)
2408{
2409 term_T *term = (term_T *)user;
2410 win_T *wp;
2411
2412 term->tl_cursor_pos = pos;
2413 term->tl_cursor_visible = visible;
2414
2415 FOR_ALL_WINDOWS(wp)
2416 {
2417 if (wp->w_buffer == term->tl_buffer)
2418 position_cursor(wp, &pos);
2419 }
2420 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2421 {
2422 may_toggle_cursor(term);
2423 update_cursor(term, term->tl_cursor_visible);
2424 }
2425
2426 return 1;
2427}
2428
2429 static int
2430handle_settermprop(
2431 VTermProp prop,
2432 VTermValue *value,
2433 void *user)
2434{
2435 term_T *term = (term_T *)user;
2436
2437 switch (prop)
2438 {
2439 case VTERM_PROP_TITLE:
2440 vim_free(term->tl_title);
2441 /* a blank title isn't useful, make it empty, so that "running" is
2442 * displayed */
2443 if (*skipwhite((char_u *)value->string) == NUL)
2444 term->tl_title = NULL;
2445#ifdef WIN3264
2446 else if (!enc_utf8 && enc_codepage > 0)
2447 {
2448 WCHAR *ret = NULL;
2449 int length = 0;
2450
2451 MultiByteToWideChar_alloc(CP_UTF8, 0,
2452 (char*)value->string, (int)STRLEN(value->string),
2453 &ret, &length);
2454 if (ret != NULL)
2455 {
2456 WideCharToMultiByte_alloc(enc_codepage, 0,
2457 ret, length, (char**)&term->tl_title,
2458 &length, 0, 0);
2459 vim_free(ret);
2460 }
2461 }
2462#endif
2463 else
2464 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002465 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002466 if (term == curbuf->b_term)
2467 maketitle();
2468 break;
2469
2470 case VTERM_PROP_CURSORVISIBLE:
2471 term->tl_cursor_visible = value->boolean;
2472 may_toggle_cursor(term);
2473 out_flush();
2474 break;
2475
2476 case VTERM_PROP_CURSORBLINK:
2477 term->tl_cursor_blink = value->boolean;
2478 may_set_cursor_props(term);
2479 break;
2480
2481 case VTERM_PROP_CURSORSHAPE:
2482 term->tl_cursor_shape = value->number;
2483 may_set_cursor_props(term);
2484 break;
2485
2486 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002487 if (desired_cursor_color == term->tl_cursor_color)
2488 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002489 vim_free(term->tl_cursor_color);
2490 if (*value->string == NUL)
2491 term->tl_cursor_color = NULL;
2492 else
2493 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2494 may_set_cursor_props(term);
2495 break;
2496
2497 case VTERM_PROP_ALTSCREEN:
2498 /* TODO: do anything else? */
2499 term->tl_using_altscreen = value->boolean;
2500 break;
2501
2502 default:
2503 break;
2504 }
2505 /* Always return 1, otherwise vterm doesn't store the value internally. */
2506 return 1;
2507}
2508
2509/*
2510 * The job running in the terminal resized the terminal.
2511 */
2512 static int
2513handle_resize(int rows, int cols, void *user)
2514{
2515 term_T *term = (term_T *)user;
2516 win_T *wp;
2517
2518 term->tl_rows = rows;
2519 term->tl_cols = cols;
2520 if (term->tl_vterm_size_changed)
2521 /* Size was set by vterm_set_size(), don't set the window size. */
2522 term->tl_vterm_size_changed = FALSE;
2523 else
2524 {
2525 FOR_ALL_WINDOWS(wp)
2526 {
2527 if (wp->w_buffer == term->tl_buffer)
2528 {
2529 win_setheight_win(rows, wp);
2530 win_setwidth_win(cols, wp);
2531 }
2532 }
2533 redraw_buf_later(term->tl_buffer, NOT_VALID);
2534 }
2535 return 1;
2536}
2537
2538/*
2539 * Handle a line that is pushed off the top of the screen.
2540 */
2541 static int
2542handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2543{
2544 term_T *term = (term_T *)user;
2545
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002546 /* If the number of lines that are stored goes over 'termscrollback' then
2547 * delete the first 10%. */
Bram Moolenaar8c94a542018-04-15 12:55:13 +02002548 if (term->tl_scrollback.ga_len >= p_tlsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002549 {
2550 int todo = p_tlsl / 10;
2551 int i;
2552
2553 curbuf = term->tl_buffer;
2554 for (i = 0; i < todo; ++i)
2555 {
2556 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2557 ml_delete(1, FALSE);
2558 }
2559 curbuf = curwin->w_buffer;
2560
2561 term->tl_scrollback.ga_len -= todo;
2562 mch_memmove(term->tl_scrollback.ga_data,
2563 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2564 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2565 }
2566
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 if (ga_grow(&term->tl_scrollback, 1) == OK)
2568 {
2569 cellattr_T *p = NULL;
2570 int len = 0;
2571 int i;
2572 int c;
2573 int col;
2574 sb_line_T *line;
2575 garray_T ga;
2576 cellattr_T fill_attr = term->tl_default_color;
2577
2578 /* do not store empty cells at the end */
2579 for (i = 0; i < cols; ++i)
2580 if (cells[i].chars[0] != 0)
2581 len = i + 1;
2582 else
2583 cell2cellattr(&cells[i], &fill_attr);
2584
2585 ga_init2(&ga, 1, 100);
2586 if (len > 0)
2587 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2588 if (p != NULL)
2589 {
2590 for (col = 0; col < len; col += cells[col].width)
2591 {
2592 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2593 {
2594 ga.ga_len = 0;
2595 break;
2596 }
2597 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2598 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2599 (char_u *)ga.ga_data + ga.ga_len);
2600 cell2cellattr(&cells[col], &p[col]);
2601 }
2602 }
2603 if (ga_grow(&ga, 1) == FAIL)
2604 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2605 else
2606 {
2607 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2608 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2609 }
2610 ga_clear(&ga);
2611
2612 line = (sb_line_T *)term->tl_scrollback.ga_data
2613 + term->tl_scrollback.ga_len;
2614 line->sb_cols = len;
2615 line->sb_cells = p;
2616 line->sb_fill_attr = fill_attr;
2617 ++term->tl_scrollback.ga_len;
2618 ++term->tl_scrollback_scrolled;
2619 }
2620 return 0; /* ignored */
2621}
2622
2623static VTermScreenCallbacks screen_callbacks = {
2624 handle_damage, /* damage */
2625 handle_moverect, /* moverect */
2626 handle_movecursor, /* movecursor */
2627 handle_settermprop, /* settermprop */
2628 NULL, /* bell */
2629 handle_resize, /* resize */
2630 handle_pushline, /* sb_pushline */
2631 NULL /* sb_popline */
2632};
2633
2634/*
2635 * Called when a channel has been closed.
2636 * If this was a channel for a terminal window then finish it up.
2637 */
2638 void
2639term_channel_closed(channel_T *ch)
2640{
2641 term_T *term;
2642 int did_one = FALSE;
2643
2644 for (term = first_term; term != NULL; term = term->tl_next)
2645 if (term->tl_job == ch->ch_job)
2646 {
2647 term->tl_channel_closed = TRUE;
2648 did_one = TRUE;
2649
Bram Moolenaard23a8232018-02-10 18:45:26 +01002650 VIM_CLEAR(term->tl_title);
2651 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652
2653 /* Unless in Terminal-Normal mode: clear the vterm. */
2654 if (!term->tl_normal_mode)
2655 {
2656 int fnum = term->tl_buffer->b_fnum;
2657
2658 cleanup_vterm(term);
2659
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002660 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002661 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002662 aco_save_T aco;
2663
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002664 /* ++close or term_finish == "close" */
2665 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002666 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002667 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002668 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002669 break;
2670 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002671 if (term->tl_finish == TL_FINISH_OPEN
2672 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002673 {
2674 char buf[50];
2675
2676 /* TODO: use term_opencmd */
2677 ch_log(NULL, "terminal job finished, opening window");
2678 vim_snprintf(buf, sizeof(buf),
2679 term->tl_opencmd == NULL
2680 ? "botright sbuf %d"
2681 : (char *)term->tl_opencmd, fnum);
2682 do_cmdline_cmd((char_u *)buf);
2683 }
2684 else
2685 ch_log(NULL, "terminal job finished");
2686 }
2687
2688 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2689 }
2690 if (did_one)
2691 {
2692 redraw_statuslines();
2693
2694 /* Need to break out of vgetc(). */
2695 ins_char_typebuf(K_IGNORE);
2696 typebuf_was_filled = TRUE;
2697
2698 term = curbuf->b_term;
2699 if (term != NULL)
2700 {
2701 if (term->tl_job == ch->ch_job)
2702 maketitle();
2703 update_cursor(term, term->tl_cursor_visible);
2704 }
2705 }
2706}
2707
2708/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002709 * Fill one screen line from a line of the terminal.
2710 * Advances "pos" to past the last column.
2711 */
2712 static void
2713term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2714{
2715 int off = screen_get_current_line_off();
2716
2717 for (pos->col = 0; pos->col < max_col; )
2718 {
2719 VTermScreenCell cell;
2720 int c;
2721
2722 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2723 vim_memset(&cell, 0, sizeof(cell));
2724
2725 c = cell.chars[0];
2726 if (c == NUL)
2727 {
2728 ScreenLines[off] = ' ';
2729 if (enc_utf8)
2730 ScreenLinesUC[off] = NUL;
2731 }
2732 else
2733 {
2734 if (enc_utf8)
2735 {
2736 int i;
2737
2738 /* composing chars */
2739 for (i = 0; i < Screen_mco
2740 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2741 {
2742 ScreenLinesC[i][off] = cell.chars[i + 1];
2743 if (cell.chars[i + 1] == 0)
2744 break;
2745 }
2746 if (c >= 0x80 || (Screen_mco > 0
2747 && ScreenLinesC[0][off] != 0))
2748 {
2749 ScreenLines[off] = ' ';
2750 ScreenLinesUC[off] = c;
2751 }
2752 else
2753 {
2754 ScreenLines[off] = c;
2755 ScreenLinesUC[off] = NUL;
2756 }
2757 }
2758#ifdef WIN3264
2759 else if (has_mbyte && c >= 0x80)
2760 {
2761 char_u mb[MB_MAXBYTES+1];
2762 WCHAR wc = c;
2763
2764 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2765 (char*)mb, 2, 0, 0) > 1)
2766 {
2767 ScreenLines[off] = mb[0];
2768 ScreenLines[off + 1] = mb[1];
2769 cell.width = mb_ptr2cells(mb);
2770 }
2771 else
2772 ScreenLines[off] = c;
2773 }
2774#endif
2775 else
2776 ScreenLines[off] = c;
2777 }
2778 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2779
2780 ++pos->col;
2781 ++off;
2782 if (cell.width == 2)
2783 {
2784 if (enc_utf8)
2785 ScreenLinesUC[off] = NUL;
2786
2787 /* don't set the second byte to NUL for a DBCS encoding, it
2788 * has been set above */
2789 if (enc_utf8 || !has_mbyte)
2790 ScreenLines[off] = NUL;
2791
2792 ++pos->col;
2793 ++off;
2794 }
2795 }
2796}
2797
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002798#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002799 static void
2800update_system_term(term_T *term)
2801{
2802 VTermPos pos;
2803 VTermScreen *screen;
2804
2805 if (term->tl_vterm == NULL)
2806 return;
2807 screen = vterm_obtain_screen(term->tl_vterm);
2808
2809 /* Scroll up to make more room for terminal lines if needed. */
2810 while (term->tl_toprow > 0
2811 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2812 {
2813 int save_p_more = p_more;
2814
2815 p_more = FALSE;
2816 msg_row = Rows - 1;
2817 msg_puts((char_u *)"\n");
2818 p_more = save_p_more;
2819 --term->tl_toprow;
2820 }
2821
2822 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2823 && pos.row < Rows; ++pos.row)
2824 {
2825 if (pos.row < term->tl_rows)
2826 {
2827 int max_col = MIN(Columns, term->tl_cols);
2828
2829 term_line2screenline(screen, &pos, max_col);
2830 }
2831 else
2832 pos.col = 0;
2833
2834 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2835 }
2836
2837 term->tl_dirty_row_start = MAX_ROW;
2838 term->tl_dirty_row_end = 0;
2839 update_cursor(term, TRUE);
2840}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002841#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002842
2843/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002844 * Called to update a window that contains an active terminal.
2845 * Returns FAIL when there is no terminal running in this window or in
2846 * Terminal-Normal mode.
2847 */
2848 int
2849term_update_window(win_T *wp)
2850{
2851 term_T *term = wp->w_buffer->b_term;
2852 VTerm *vterm;
2853 VTermScreen *screen;
2854 VTermState *state;
2855 VTermPos pos;
2856
2857 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2858 return FAIL;
2859
2860 vterm = term->tl_vterm;
2861 screen = vterm_obtain_screen(vterm);
2862 state = vterm_obtain_state(vterm);
2863
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002864 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002865 {
2866 term->tl_dirty_row_start = 0;
2867 term->tl_dirty_row_end = MAX_ROW;
2868 }
2869
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002870 /*
2871 * If the window was resized a redraw will be triggered and we get here.
2872 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2873 */
2874 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2875 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2876 {
2877 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2878 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2879 win_T *twp;
2880
2881 FOR_ALL_WINDOWS(twp)
2882 {
2883 /* When more than one window shows the same terminal, use the
2884 * smallest size. */
2885 if (twp->w_buffer == term->tl_buffer)
2886 {
2887 if (!term->tl_rows_fixed && rows > twp->w_height)
2888 rows = twp->w_height;
2889 if (!term->tl_cols_fixed && cols > twp->w_width)
2890 cols = twp->w_width;
2891 }
2892 }
2893
2894 term->tl_vterm_size_changed = TRUE;
2895 vterm_set_size(vterm, rows, cols);
2896 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2897 rows);
2898 term_report_winsize(term, rows, cols);
2899 }
2900
2901 /* The cursor may have been moved when resizing. */
2902 vterm_state_get_cursorpos(state, &pos);
2903 position_cursor(wp, &pos);
2904
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002905 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2906 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002907 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002908 if (pos.row < term->tl_rows)
2909 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002910 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002911
Bram Moolenaar13568252018-03-16 20:46:58 +01002912 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002913 }
2914 else
2915 pos.col = 0;
2916
Bram Moolenaarf118d482018-03-13 13:14:00 +01002917 screen_line(wp->w_winrow + pos.row
2918#ifdef FEAT_MENU
2919 + winbar_height(wp)
2920#endif
2921 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002923 term->tl_dirty_row_start = MAX_ROW;
2924 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925
2926 return OK;
2927}
2928
2929/*
2930 * Return TRUE if "wp" is a terminal window where the job has finished.
2931 */
2932 int
2933term_is_finished(buf_T *buf)
2934{
2935 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2936}
2937
2938/*
2939 * Return TRUE if "wp" is a terminal window where the job has finished or we
2940 * are in Terminal-Normal mode, thus we show the buffer contents.
2941 */
2942 int
2943term_show_buffer(buf_T *buf)
2944{
2945 term_T *term = buf->b_term;
2946
2947 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2948}
2949
2950/*
2951 * The current buffer is going to be changed. If there is terminal
2952 * highlighting remove it now.
2953 */
2954 void
2955term_change_in_curbuf(void)
2956{
2957 term_T *term = curbuf->b_term;
2958
2959 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2960 {
2961 free_scrollback(term);
2962 redraw_buf_later(term->tl_buffer, NOT_VALID);
2963
2964 /* The buffer is now like a normal buffer, it cannot be easily
2965 * abandoned when changed. */
2966 set_string_option_direct((char_u *)"buftype", -1,
2967 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2968 }
2969}
2970
2971/*
2972 * Get the screen attribute for a position in the buffer.
2973 * Use a negative "col" to get the filler background color.
2974 */
2975 int
2976term_get_attr(buf_T *buf, linenr_T lnum, int col)
2977{
2978 term_T *term = buf->b_term;
2979 sb_line_T *line;
2980 cellattr_T *cellattr;
2981
2982 if (lnum > term->tl_scrollback.ga_len)
2983 cellattr = &term->tl_default_color;
2984 else
2985 {
2986 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2987 if (col < 0 || col >= line->sb_cols)
2988 cellattr = &line->sb_fill_attr;
2989 else
2990 cellattr = line->sb_cells + col;
2991 }
2992 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2993}
2994
2995static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002996 { 0, 0, 0, 1}, /* black */
2997 {224, 0, 0, 2}, /* dark red */
2998 { 0, 224, 0, 3}, /* dark green */
2999 {224, 224, 0, 4}, /* dark yellow / brown */
3000 { 0, 0, 224, 5}, /* dark blue */
3001 {224, 0, 224, 6}, /* dark magenta */
3002 { 0, 224, 224, 7}, /* dark cyan */
3003 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003004
Bram Moolenaar46359e12017-11-29 22:33:38 +01003005 {128, 128, 128, 9}, /* dark grey */
3006 {255, 64, 64, 10}, /* light red */
3007 { 64, 255, 64, 11}, /* light green */
3008 {255, 255, 64, 12}, /* yellow */
3009 { 64, 64, 255, 13}, /* light blue */
3010 {255, 64, 255, 14}, /* light magenta */
3011 { 64, 255, 255, 15}, /* light cyan */
3012 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013};
3014
3015static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003016 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017};
3018
3019static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003020 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
3021 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003022};
3023
3024/*
3025 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003026 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003027 */
3028 static void
3029cterm_color2rgb(int nr, VTermColor *rgb)
3030{
3031 int idx;
3032
3033 if (nr < 16)
3034 {
3035 *rgb = ansi_table[nr];
3036 }
3037 else if (nr < 232)
3038 {
3039 /* 216 color cube */
3040 idx = nr - 16;
3041 rgb->blue = cube_value[idx % 6];
3042 rgb->green = cube_value[idx / 6 % 6];
3043 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003044 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003045 }
3046 else if (nr < 256)
3047 {
3048 /* 24 grey scale ramp */
3049 idx = nr - 232;
3050 rgb->blue = grey_ramp[idx];
3051 rgb->green = grey_ramp[idx];
3052 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003053 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003054 }
3055}
3056
3057/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003058 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003059 */
3060 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003061init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003062{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003063 VTermColor *fg, *bg;
3064 int fgval, bgval;
3065 int id;
3066
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003067 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3068 term->tl_default_color.width = 1;
3069 fg = &term->tl_default_color.fg;
3070 bg = &term->tl_default_color.bg;
3071
3072 /* Vterm uses a default black background. Set it to white when
3073 * 'background' is "light". */
3074 if (*p_bg == 'l')
3075 {
3076 fgval = 0;
3077 bgval = 255;
3078 }
3079 else
3080 {
3081 fgval = 255;
3082 bgval = 0;
3083 }
3084 fg->red = fg->green = fg->blue = fgval;
3085 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003086 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087
3088 /* The "Terminal" highlight group overrules the defaults. */
3089 id = syn_name2id((char_u *)"Terminal");
3090
Bram Moolenaar46359e12017-11-29 22:33:38 +01003091 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3093 if (0
3094# ifdef FEAT_GUI
3095 || gui.in_use
3096# endif
3097# ifdef FEAT_TERMGUICOLORS
3098 || p_tgc
3099# endif
3100 )
3101 {
3102 guicolor_T fg_rgb = INVALCOLOR;
3103 guicolor_T bg_rgb = INVALCOLOR;
3104
3105 if (id != 0)
3106 syn_id2colors(id, &fg_rgb, &bg_rgb);
3107
3108# ifdef FEAT_GUI
3109 if (gui.in_use)
3110 {
3111 if (fg_rgb == INVALCOLOR)
3112 fg_rgb = gui.norm_pixel;
3113 if (bg_rgb == INVALCOLOR)
3114 bg_rgb = gui.back_pixel;
3115 }
3116# ifdef FEAT_TERMGUICOLORS
3117 else
3118# endif
3119# endif
3120# ifdef FEAT_TERMGUICOLORS
3121 {
3122 if (fg_rgb == INVALCOLOR)
3123 fg_rgb = cterm_normal_fg_gui_color;
3124 if (bg_rgb == INVALCOLOR)
3125 bg_rgb = cterm_normal_bg_gui_color;
3126 }
3127# endif
3128 if (fg_rgb != INVALCOLOR)
3129 {
3130 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3131
3132 fg->red = (unsigned)(rgb >> 16);
3133 fg->green = (unsigned)(rgb >> 8) & 255;
3134 fg->blue = (unsigned)rgb & 255;
3135 }
3136 if (bg_rgb != INVALCOLOR)
3137 {
3138 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3139
3140 bg->red = (unsigned)(rgb >> 16);
3141 bg->green = (unsigned)(rgb >> 8) & 255;
3142 bg->blue = (unsigned)rgb & 255;
3143 }
3144 }
3145 else
3146#endif
3147 if (id != 0 && t_colors >= 16)
3148 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003149 if (term_default_cterm_fg >= 0)
3150 cterm_color2rgb(term_default_cterm_fg, fg);
3151 if (term_default_cterm_bg >= 0)
3152 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003154 else
3155 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003156#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003157 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003158#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003159
3160 /* In an MS-Windows console we know the normal colors. */
3161 if (cterm_normal_fg_color > 0)
3162 {
3163 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003164# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003165 tmp = fg->red;
3166 fg->red = fg->blue;
3167 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003168# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003169 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003170# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003171 else
3172 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003173# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003174
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003175 if (cterm_normal_bg_color > 0)
3176 {
3177 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003178# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003179 tmp = bg->red;
3180 bg->red = bg->blue;
3181 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003182# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003183 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003184# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003185 else
3186 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003187# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003188 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003189}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003190
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003191#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3192/*
3193 * Set the 16 ANSI colors from array of RGB values
3194 */
3195 static void
3196set_vterm_palette(VTerm *vterm, long_u *rgb)
3197{
3198 int index = 0;
3199 VTermState *state = vterm_obtain_state(vterm);
3200 for (; index < 16; index++)
3201 {
3202 VTermColor color;
3203 color.red = (unsigned)(rgb[index] >> 16);
3204 color.green = (unsigned)(rgb[index] >> 8) & 255;
3205 color.blue = (unsigned)rgb[index] & 255;
3206 vterm_state_set_palette_color(state, index, &color);
3207 }
3208}
3209
3210/*
3211 * Set the ANSI color palette from a list of colors
3212 */
3213 static int
3214set_ansi_colors_list(VTerm *vterm, list_T *list)
3215{
3216 int n = 0;
3217 long_u rgb[16];
3218 listitem_T *li = list->lv_first;
3219
3220 for (; li != NULL && n < 16; li = li->li_next, n++)
3221 {
3222 char_u *color_name;
3223 guicolor_T guicolor;
3224
3225 color_name = get_tv_string_chk(&li->li_tv);
3226 if (color_name == NULL)
3227 return FAIL;
3228
3229 guicolor = GUI_GET_COLOR(color_name);
3230 if (guicolor == INVALCOLOR)
3231 return FAIL;
3232
3233 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3234 }
3235
3236 if (n != 16 || li != NULL)
3237 return FAIL;
3238
3239 set_vterm_palette(vterm, rgb);
3240
3241 return OK;
3242}
3243
3244/*
3245 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3246 */
3247 static void
3248init_vterm_ansi_colors(VTerm *vterm)
3249{
3250 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3251
3252 if (var != NULL
3253 && (var->di_tv.v_type != VAR_LIST
3254 || var->di_tv.vval.v_list == NULL
3255 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3256 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3257}
3258#endif
3259
Bram Moolenaar52acb112018-03-18 19:20:22 +01003260/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003261 * Handles a "drop" command from the job in the terminal.
3262 * "item" is the file name, "item->li_next" may have options.
3263 */
3264 static void
3265handle_drop_command(listitem_T *item)
3266{
3267 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003268 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003269 int bufnr;
3270 win_T *wp;
3271 tabpage_T *tp;
3272 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003273 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003274
3275 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3276 FOR_ALL_TAB_WINDOWS(tp, wp)
3277 {
3278 if (wp->w_buffer->b_fnum == bufnr)
3279 {
3280 /* buffer is in a window already, go there */
3281 goto_tabpage_win(tp, wp);
3282 return;
3283 }
3284 }
3285
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003286 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003287
3288 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3289 && opt_item->li_tv.vval.v_dict != NULL)
3290 {
3291 dict_T *dict = opt_item->li_tv.vval.v_dict;
3292 char_u *p;
3293
3294 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3295 if (p == NULL)
3296 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3297 if (p != NULL)
3298 {
3299 if (check_ff_value(p) == FAIL)
3300 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3301 else
3302 ea.force_ff = *p;
3303 }
3304 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3305 if (p == NULL)
3306 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3307 if (p != NULL)
3308 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003309 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003310 if (ea.cmd != NULL)
3311 {
3312 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3313 ea.force_enc = 11;
3314 tofree = ea.cmd;
3315 }
3316 }
3317
3318 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3319 if (p != NULL)
3320 get_bad_opt(p, &ea);
3321
3322 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3323 ea.force_bin = FORCE_BIN;
3324 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3325 ea.force_bin = FORCE_BIN;
3326 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3327 ea.force_bin = FORCE_NOBIN;
3328 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3329 ea.force_bin = FORCE_NOBIN;
3330 }
3331
3332 /* open in new window, like ":split fname" */
3333 if (ea.cmd == NULL)
3334 ea.cmd = (char_u *)"split";
3335 ea.arg = fname;
3336 ea.cmdidx = CMD_split;
3337 ex_splitview(&ea);
3338
3339 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003340}
3341
3342/*
3343 * Handles a function call from the job running in a terminal.
3344 * "item" is the function name, "item->li_next" has the arguments.
3345 */
3346 static void
3347handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3348{
3349 char_u *func;
3350 typval_T argvars[2];
3351 typval_T rettv;
3352 int doesrange;
3353
3354 if (item->li_next == NULL)
3355 {
3356 ch_log(channel, "Missing function arguments for call");
3357 return;
3358 }
3359 func = get_tv_string(&item->li_tv);
3360
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003361 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003362 {
3363 ch_log(channel, "Invalid function name: %s", func);
3364 return;
3365 }
3366
3367 argvars[0].v_type = VAR_NUMBER;
3368 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3369 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003370 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003371 2, argvars, /* argv_func */ NULL,
3372 /* firstline */ 1, /* lastline */ 1,
3373 &doesrange, /* evaluate */ TRUE,
3374 /* partial */ NULL, /* selfdict */ NULL) == OK)
3375 {
3376 clear_tv(&rettv);
3377 ch_log(channel, "Function %s called", func);
3378 }
3379 else
3380 ch_log(channel, "Calling function %s failed", func);
3381}
3382
3383/*
3384 * Called by libvterm when it cannot recognize an OSC sequence.
3385 * We recognize a terminal API command.
3386 */
3387 static int
3388parse_osc(const char *command, size_t cmdlen, void *user)
3389{
3390 term_T *term = (term_T *)user;
3391 js_read_T reader;
3392 typval_T tv;
3393 channel_T *channel = term->tl_job == NULL ? NULL
3394 : term->tl_job->jv_channel;
3395
3396 /* We recognize only OSC 5 1 ; {command} */
3397 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3398 return 0; /* not handled */
3399
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003400 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003401 if (reader.js_buf == NULL)
3402 return 1;
3403 reader.js_fill = NULL;
3404 reader.js_used = 0;
3405 if (json_decode(&reader, &tv, 0) == OK
3406 && tv.v_type == VAR_LIST
3407 && tv.vval.v_list != NULL)
3408 {
3409 listitem_T *item = tv.vval.v_list->lv_first;
3410
3411 if (item == NULL)
3412 ch_log(channel, "Missing command");
3413 else
3414 {
3415 char_u *cmd = get_tv_string(&item->li_tv);
3416
3417 item = item->li_next;
3418 if (item == NULL)
3419 ch_log(channel, "Missing argument for %s", cmd);
3420 else if (STRCMP(cmd, "drop") == 0)
3421 handle_drop_command(item);
3422 else if (STRCMP(cmd, "call") == 0)
3423 handle_call_command(term, channel, item);
3424 else
3425 ch_log(channel, "Invalid command received: %s", cmd);
3426 }
3427 }
3428 else
3429 ch_log(channel, "Invalid JSON received");
3430
3431 vim_free(reader.js_buf);
3432 clear_tv(&tv);
3433 return 1;
3434}
3435
3436static VTermParserCallbacks parser_fallbacks = {
3437 NULL, /* text */
3438 NULL, /* control */
3439 NULL, /* escape */
3440 NULL, /* csi */
3441 parse_osc, /* osc */
3442 NULL, /* dcs */
3443 NULL /* resize */
3444};
3445
3446/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003447 * Use Vim's allocation functions for vterm so profiling works.
3448 */
3449 static void *
3450vterm_malloc(size_t size, void *data UNUSED)
3451{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003452 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003453}
3454
3455 static void
3456vterm_memfree(void *ptr, void *data UNUSED)
3457{
3458 vim_free(ptr);
3459}
3460
3461static VTermAllocatorFunctions vterm_allocator = {
3462 &vterm_malloc,
3463 &vterm_memfree
3464};
3465
3466/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003467 * Create a new vterm and initialize it.
3468 */
3469 static void
3470create_vterm(term_T *term, int rows, int cols)
3471{
3472 VTerm *vterm;
3473 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003474 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003475 VTermValue value;
3476
Bram Moolenaar756ef112018-04-10 12:04:27 +02003477 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003478 term->tl_vterm = vterm;
3479 screen = vterm_obtain_screen(vterm);
3480 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3481 /* TODO: depends on 'encoding'. */
3482 vterm_set_utf8(vterm, 1);
3483
3484 init_default_colors(term);
3485
3486 vterm_state_set_default_colors(
3487 vterm_obtain_state(vterm),
3488 &term->tl_default_color.fg,
3489 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003490
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003491 if (t_colors >= 16)
3492 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3493
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003494 /* Required to initialize most things. */
3495 vterm_screen_reset(screen, 1 /* hard */);
3496
3497 /* Allow using alternate screen. */
3498 vterm_screen_enable_altscreen(screen, 1);
3499
3500 /* For unix do not use a blinking cursor. In an xterm this causes the
3501 * cursor to blink if it's blinking in the xterm.
3502 * For Windows we respect the system wide setting. */
3503#ifdef WIN3264
3504 if (GetCaretBlinkTime() == INFINITE)
3505 value.boolean = 0;
3506 else
3507 value.boolean = 1;
3508#else
3509 value.boolean = 0;
3510#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003511 state = vterm_obtain_state(vterm);
3512 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3513 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003514}
3515
3516/*
3517 * Return the text to show for the buffer name and status.
3518 */
3519 char_u *
3520term_get_status_text(term_T *term)
3521{
3522 if (term->tl_status_text == NULL)
3523 {
3524 char_u *txt;
3525 size_t len;
3526
3527 if (term->tl_normal_mode)
3528 {
3529 if (term_job_running(term))
3530 txt = (char_u *)_("Terminal");
3531 else
3532 txt = (char_u *)_("Terminal-finished");
3533 }
3534 else if (term->tl_title != NULL)
3535 txt = term->tl_title;
3536 else if (term_none_open(term))
3537 txt = (char_u *)_("active");
3538 else if (term_job_running(term))
3539 txt = (char_u *)_("running");
3540 else
3541 txt = (char_u *)_("finished");
3542 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3543 term->tl_status_text = alloc((int)len);
3544 if (term->tl_status_text != NULL)
3545 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3546 term->tl_buffer->b_fname, txt);
3547 }
3548 return term->tl_status_text;
3549}
3550
3551/*
3552 * Mark references in jobs of terminals.
3553 */
3554 int
3555set_ref_in_term(int copyID)
3556{
3557 int abort = FALSE;
3558 term_T *term;
3559 typval_T tv;
3560
3561 for (term = first_term; term != NULL; term = term->tl_next)
3562 if (term->tl_job != NULL)
3563 {
3564 tv.v_type = VAR_JOB;
3565 tv.vval.v_job = term->tl_job;
3566 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3567 }
3568 return abort;
3569}
3570
3571/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003572 * Cache "Terminal" highlight group colors.
3573 */
3574 void
3575set_terminal_default_colors(int cterm_fg, int cterm_bg)
3576{
3577 term_default_cterm_fg = cterm_fg - 1;
3578 term_default_cterm_bg = cterm_bg - 1;
3579}
3580
3581/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003582 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003583 * Returns NULL when the buffer is not for a terminal window and logs a message
3584 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 */
3586 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003587term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003588{
3589 buf_T *buf;
3590
3591 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3592 ++emsg_off;
3593 buf = get_buf_tv(&argvars[0], FALSE);
3594 --emsg_off;
3595 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003596 {
3597 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003598 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003599 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003600 return buf;
3601}
3602
Bram Moolenaard96ff162018-02-18 22:13:29 +01003603 static int
3604same_color(VTermColor *a, VTermColor *b)
3605{
3606 return a->red == b->red
3607 && a->green == b->green
3608 && a->blue == b->blue
3609 && a->ansi_index == b->ansi_index;
3610}
3611
3612 static void
3613dump_term_color(FILE *fd, VTermColor *color)
3614{
3615 fprintf(fd, "%02x%02x%02x%d",
3616 (int)color->red, (int)color->green, (int)color->blue,
3617 (int)color->ansi_index);
3618}
3619
3620/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003621 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003622 *
3623 * Each screen cell in full is:
3624 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3625 * {characters} is a space for an empty cell
3626 * For a double-width character "+" is changed to "*" and the next cell is
3627 * skipped.
3628 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3629 * when "&" use the same as the previous cell.
3630 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3631 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3632 * {color-idx} is a number from 0 to 255
3633 *
3634 * Screen cell with same width, attributes and color as the previous one:
3635 * |{characters}
3636 *
3637 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3638 *
3639 * Repeating the previous screen cell:
3640 * @{count}
3641 */
3642 void
3643f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3644{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003645 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003646 term_T *term;
3647 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003648 int max_height = 0;
3649 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003650 stat_T st;
3651 FILE *fd;
3652 VTermPos pos;
3653 VTermScreen *screen;
3654 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003655 VTermState *state;
3656 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003657
3658 if (check_restricted() || check_secure())
3659 return;
3660 if (buf == NULL)
3661 return;
3662 term = buf->b_term;
3663
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003664 if (argvars[2].v_type != VAR_UNKNOWN)
3665 {
3666 dict_T *d;
3667
3668 if (argvars[2].v_type != VAR_DICT)
3669 {
3670 EMSG(_(e_dictreq));
3671 return;
3672 }
3673 d = argvars[2].vval.v_dict;
3674 if (d != NULL)
3675 {
3676 max_height = get_dict_number(d, (char_u *)"rows");
3677 max_width = get_dict_number(d, (char_u *)"columns");
3678 }
3679 }
3680
Bram Moolenaard96ff162018-02-18 22:13:29 +01003681 fname = get_tv_string_chk(&argvars[1]);
3682 if (fname == NULL)
3683 return;
3684 if (mch_stat((char *)fname, &st) >= 0)
3685 {
3686 EMSG2(_("E953: File exists: %s"), fname);
3687 return;
3688 }
3689
Bram Moolenaard96ff162018-02-18 22:13:29 +01003690 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3691 {
3692 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3693 return;
3694 }
3695
3696 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3697
3698 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003699 state = vterm_obtain_state(term->tl_vterm);
3700 vterm_state_get_cursorpos(state, &cursor_pos);
3701
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003702 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3703 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003704 {
3705 int repeat = 0;
3706
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003707 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3708 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003709 {
3710 VTermScreenCell cell;
3711 int same_attr;
3712 int same_chars = TRUE;
3713 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003714 int is_cursor_pos = (pos.col == cursor_pos.col
3715 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003716
3717 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3718 vim_memset(&cell, 0, sizeof(cell));
3719
3720 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3721 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003722 int c = cell.chars[i];
3723 int pc = prev_cell.chars[i];
3724
3725 /* For the first character NUL is the same as space. */
3726 if (i == 0)
3727 {
3728 c = (c == NUL) ? ' ' : c;
3729 pc = (pc == NUL) ? ' ' : pc;
3730 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003731 if (cell.chars[i] != prev_cell.chars[i])
3732 same_chars = FALSE;
3733 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3734 break;
3735 }
3736 same_attr = vtermAttr2hl(cell.attrs)
3737 == vtermAttr2hl(prev_cell.attrs)
3738 && same_color(&cell.fg, &prev_cell.fg)
3739 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003740 if (same_chars && cell.width == prev_cell.width && same_attr
3741 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003742 {
3743 ++repeat;
3744 }
3745 else
3746 {
3747 if (repeat > 0)
3748 {
3749 fprintf(fd, "@%d", repeat);
3750 repeat = 0;
3751 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003752 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003753
3754 if (cell.chars[0] == NUL)
3755 fputs(" ", fd);
3756 else
3757 {
3758 char_u charbuf[10];
3759 int len;
3760
3761 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3762 && cell.chars[i] != NUL; ++i)
3763 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003764 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003765 fwrite(charbuf, len, 1, fd);
3766 }
3767 }
3768
3769 /* When only the characters differ we don't write anything, the
3770 * following "|", "@" or NL will indicate using the same
3771 * attributes. */
3772 if (cell.width != prev_cell.width || !same_attr)
3773 {
3774 if (cell.width == 2)
3775 {
3776 fputs("*", fd);
3777 ++pos.col;
3778 }
3779 else
3780 fputs("+", fd);
3781
3782 if (same_attr)
3783 {
3784 fputs("&", fd);
3785 }
3786 else
3787 {
3788 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3789 if (same_color(&cell.fg, &prev_cell.fg))
3790 fputs("&", fd);
3791 else
3792 {
3793 fputs("#", fd);
3794 dump_term_color(fd, &cell.fg);
3795 }
3796 if (same_color(&cell.bg, &prev_cell.bg))
3797 fputs("&", fd);
3798 else
3799 {
3800 fputs("#", fd);
3801 dump_term_color(fd, &cell.bg);
3802 }
3803 }
3804 }
3805
3806 prev_cell = cell;
3807 }
3808 }
3809 if (repeat > 0)
3810 fprintf(fd, "@%d", repeat);
3811 fputs("\n", fd);
3812 }
3813
3814 fclose(fd);
3815}
3816
3817/*
3818 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3819 */
3820 static void
3821dump_is_corrupt(garray_T *gap)
3822{
3823 ga_concat(gap, (char_u *)"CORRUPT");
3824}
3825
3826 static void
3827append_cell(garray_T *gap, cellattr_T *cell)
3828{
3829 if (ga_grow(gap, 1) == OK)
3830 {
3831 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3832 ++gap->ga_len;
3833 }
3834}
3835
3836/*
3837 * Read the dump file from "fd" and append lines to the current buffer.
3838 * Return the cell width of the longest line.
3839 */
3840 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003841read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003842{
3843 int c;
3844 garray_T ga_text;
3845 garray_T ga_cell;
3846 char_u *prev_char = NULL;
3847 int attr = 0;
3848 cellattr_T cell;
3849 term_T *term = curbuf->b_term;
3850 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003851 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003852
3853 ga_init2(&ga_text, 1, 90);
3854 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3855 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003856 cursor_pos->row = -1;
3857 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003858
3859 c = fgetc(fd);
3860 for (;;)
3861 {
3862 if (c == EOF)
3863 break;
3864 if (c == '\n')
3865 {
3866 /* End of a line: append it to the buffer. */
3867 if (ga_text.ga_data == NULL)
3868 dump_is_corrupt(&ga_text);
3869 if (ga_grow(&term->tl_scrollback, 1) == OK)
3870 {
3871 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3872 + term->tl_scrollback.ga_len;
3873
3874 if (max_cells < ga_cell.ga_len)
3875 max_cells = ga_cell.ga_len;
3876 line->sb_cols = ga_cell.ga_len;
3877 line->sb_cells = ga_cell.ga_data;
3878 line->sb_fill_attr = term->tl_default_color;
3879 ++term->tl_scrollback.ga_len;
3880 ga_init(&ga_cell);
3881
3882 ga_append(&ga_text, NUL);
3883 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3884 ga_text.ga_len, FALSE);
3885 }
3886 else
3887 ga_clear(&ga_cell);
3888 ga_text.ga_len = 0;
3889
3890 c = fgetc(fd);
3891 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003892 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003893 {
3894 int prev_len = ga_text.ga_len;
3895
Bram Moolenaar9271d052018-02-25 21:39:46 +01003896 if (c == '>')
3897 {
3898 if (cursor_pos->row != -1)
3899 dump_is_corrupt(&ga_text); /* duplicate cursor */
3900 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3901 cursor_pos->col = ga_cell.ga_len;
3902 }
3903
Bram Moolenaard96ff162018-02-18 22:13:29 +01003904 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3905 c = fgetc(fd);
3906 if (c != EOF)
3907 ga_append(&ga_text, c);
3908 for (;;)
3909 {
3910 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003911 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003912 || c == EOF || c == '\n')
3913 break;
3914 ga_append(&ga_text, c);
3915 }
3916
3917 /* save the character for repeating it */
3918 vim_free(prev_char);
3919 if (ga_text.ga_data != NULL)
3920 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3921 ga_text.ga_len - prev_len);
3922
Bram Moolenaar9271d052018-02-25 21:39:46 +01003923 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003924 {
3925 /* use all attributes from previous cell */
3926 }
3927 else if (c == '+' || c == '*')
3928 {
3929 int is_bg;
3930
3931 cell.width = c == '+' ? 1 : 2;
3932
3933 c = fgetc(fd);
3934 if (c == '&')
3935 {
3936 /* use same attr as previous cell */
3937 c = fgetc(fd);
3938 }
3939 else if (isdigit(c))
3940 {
3941 /* get the decimal attribute */
3942 attr = 0;
3943 while (isdigit(c))
3944 {
3945 attr = attr * 10 + (c - '0');
3946 c = fgetc(fd);
3947 }
3948 hl2vtermAttr(attr, &cell);
3949 }
3950 else
3951 dump_is_corrupt(&ga_text);
3952
3953 /* is_bg == 0: fg, is_bg == 1: bg */
3954 for (is_bg = 0; is_bg <= 1; ++is_bg)
3955 {
3956 if (c == '&')
3957 {
3958 /* use same color as previous cell */
3959 c = fgetc(fd);
3960 }
3961 else if (c == '#')
3962 {
3963 int red, green, blue, index = 0;
3964
3965 c = fgetc(fd);
3966 red = hex2nr(c);
3967 c = fgetc(fd);
3968 red = (red << 4) + hex2nr(c);
3969 c = fgetc(fd);
3970 green = hex2nr(c);
3971 c = fgetc(fd);
3972 green = (green << 4) + hex2nr(c);
3973 c = fgetc(fd);
3974 blue = hex2nr(c);
3975 c = fgetc(fd);
3976 blue = (blue << 4) + hex2nr(c);
3977 c = fgetc(fd);
3978 if (!isdigit(c))
3979 dump_is_corrupt(&ga_text);
3980 while (isdigit(c))
3981 {
3982 index = index * 10 + (c - '0');
3983 c = fgetc(fd);
3984 }
3985
3986 if (is_bg)
3987 {
3988 cell.bg.red = red;
3989 cell.bg.green = green;
3990 cell.bg.blue = blue;
3991 cell.bg.ansi_index = index;
3992 }
3993 else
3994 {
3995 cell.fg.red = red;
3996 cell.fg.green = green;
3997 cell.fg.blue = blue;
3998 cell.fg.ansi_index = index;
3999 }
4000 }
4001 else
4002 dump_is_corrupt(&ga_text);
4003 }
4004 }
4005 else
4006 dump_is_corrupt(&ga_text);
4007
4008 append_cell(&ga_cell, &cell);
4009 }
4010 else if (c == '@')
4011 {
4012 if (prev_char == NULL)
4013 dump_is_corrupt(&ga_text);
4014 else
4015 {
4016 int count = 0;
4017
4018 /* repeat previous character, get the count */
4019 for (;;)
4020 {
4021 c = fgetc(fd);
4022 if (!isdigit(c))
4023 break;
4024 count = count * 10 + (c - '0');
4025 }
4026
4027 while (count-- > 0)
4028 {
4029 ga_concat(&ga_text, prev_char);
4030 append_cell(&ga_cell, &cell);
4031 }
4032 }
4033 }
4034 else
4035 {
4036 dump_is_corrupt(&ga_text);
4037 c = fgetc(fd);
4038 }
4039 }
4040
4041 if (ga_text.ga_len > 0)
4042 {
4043 /* trailing characters after last NL */
4044 dump_is_corrupt(&ga_text);
4045 ga_append(&ga_text, NUL);
4046 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4047 ga_text.ga_len, FALSE);
4048 }
4049
4050 ga_clear(&ga_text);
4051 vim_free(prev_char);
4052
4053 return max_cells;
4054}
4055
4056/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004057 * Return an allocated string with at least "text_width" "=" characters and
4058 * "fname" inserted in the middle.
4059 */
4060 static char_u *
4061get_separator(int text_width, char_u *fname)
4062{
4063 int width = MAX(text_width, curwin->w_width);
4064 char_u *textline;
4065 int fname_size;
4066 char_u *p = fname;
4067 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004068 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004069
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004070 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004071 if (textline == NULL)
4072 return NULL;
4073
4074 fname_size = vim_strsize(fname);
4075 if (fname_size < width - 8)
4076 {
4077 /* enough room, don't use the full window width */
4078 width = MAX(text_width, fname_size + 8);
4079 }
4080 else if (fname_size > width - 8)
4081 {
4082 /* full name doesn't fit, use only the tail */
4083 p = gettail(fname);
4084 fname_size = vim_strsize(p);
4085 }
4086 /* skip characters until the name fits */
4087 while (fname_size > width - 8)
4088 {
4089 p += (*mb_ptr2len)(p);
4090 fname_size = vim_strsize(p);
4091 }
4092
4093 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4094 textline[i] = '=';
4095 textline[i++] = ' ';
4096
4097 STRCPY(textline + i, p);
4098 off = STRLEN(textline);
4099 textline[off] = ' ';
4100 for (i = 1; i < (width - fname_size) / 2; ++i)
4101 textline[off + i] = '=';
4102 textline[off + i] = NUL;
4103
4104 return textline;
4105}
4106
4107/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004108 * Common for "term_dumpdiff()" and "term_dumpload()".
4109 */
4110 static void
4111term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4112{
4113 jobopt_T opt;
4114 buf_T *buf;
4115 char_u buf1[NUMBUFLEN];
4116 char_u buf2[NUMBUFLEN];
4117 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004118 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004119 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004120 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004121 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004122 char_u *textline = NULL;
4123
4124 /* First open the files. If this fails bail out. */
4125 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4126 if (do_diff)
4127 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4128 if (fname1 == NULL || (do_diff && fname2 == NULL))
4129 {
4130 EMSG(_(e_invarg));
4131 return;
4132 }
4133 fd1 = mch_fopen((char *)fname1, READBIN);
4134 if (fd1 == NULL)
4135 {
4136 EMSG2(_(e_notread), fname1);
4137 return;
4138 }
4139 if (do_diff)
4140 {
4141 fd2 = mch_fopen((char *)fname2, READBIN);
4142 if (fd2 == NULL)
4143 {
4144 fclose(fd1);
4145 EMSG2(_(e_notread), fname2);
4146 return;
4147 }
4148 }
4149
4150 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004151 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4152 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4153 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4154 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4155 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004156
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004157 if (opt.jo_term_name == NULL)
4158 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004159 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004160
Bram Moolenaarb571c632018-03-21 22:27:59 +01004161 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004162 if (fname_tofree != NULL)
4163 {
4164 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4165 opt.jo_term_name = fname_tofree;
4166 }
4167 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004168
Bram Moolenaar13568252018-03-16 20:46:58 +01004169 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004170 if (buf != NULL && buf->b_term != NULL)
4171 {
4172 int i;
4173 linenr_T bot_lnum;
4174 linenr_T lnum;
4175 term_T *term = buf->b_term;
4176 int width;
4177 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004178 VTermPos cursor_pos1;
4179 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004180
Bram Moolenaar52acb112018-03-18 19:20:22 +01004181 init_default_colors(term);
4182
Bram Moolenaard96ff162018-02-18 22:13:29 +01004183 rettv->vval.v_number = buf->b_fnum;
4184
4185 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004186 width = read_dump_file(fd1, &cursor_pos1);
4187
4188 /* position the cursor */
4189 if (cursor_pos1.row >= 0)
4190 {
4191 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4192 coladvance(cursor_pos1.col);
4193 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004194
4195 /* Delete the empty line that was in the empty buffer. */
4196 ml_delete(1, FALSE);
4197
4198 /* For term_dumpload() we are done here. */
4199 if (!do_diff)
4200 goto theend;
4201
4202 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4203
Bram Moolenaar4a696342018-04-05 18:45:26 +02004204 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004205 if (textline == NULL)
4206 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004207 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4208 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4209 vim_free(textline);
4210
4211 textline = get_separator(width, fname2);
4212 if (textline == NULL)
4213 goto theend;
4214 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4215 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004216 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004217
4218 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004219 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004220 if (width2 > width)
4221 {
4222 vim_free(textline);
4223 textline = alloc(width2 + 1);
4224 if (textline == NULL)
4225 goto theend;
4226 width = width2;
4227 textline[width] = NUL;
4228 }
4229 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4230
4231 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4232 {
4233 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4234 {
4235 /* bottom part has fewer rows, fill with "-" */
4236 for (i = 0; i < width; ++i)
4237 textline[i] = '-';
4238 }
4239 else
4240 {
4241 char_u *line1;
4242 char_u *line2;
4243 char_u *p1;
4244 char_u *p2;
4245 int col;
4246 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4247 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4248 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4249 ->sb_cells;
4250
4251 /* Make a copy, getting the second line will invalidate it. */
4252 line1 = vim_strsave(ml_get(lnum));
4253 if (line1 == NULL)
4254 break;
4255 p1 = line1;
4256
4257 line2 = ml_get(lnum + bot_lnum);
4258 p2 = line2;
4259 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4260 {
4261 int len1 = utfc_ptr2len(p1);
4262 int len2 = utfc_ptr2len(p2);
4263
4264 textline[col] = ' ';
4265 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004266 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004267 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004268 else if (lnum == cursor_pos1.row + 1
4269 && col == cursor_pos1.col
4270 && (cursor_pos1.row != cursor_pos2.row
4271 || cursor_pos1.col != cursor_pos2.col))
4272 /* cursor in first but not in second */
4273 textline[col] = '>';
4274 else if (lnum == cursor_pos2.row + 1
4275 && col == cursor_pos2.col
4276 && (cursor_pos1.row != cursor_pos2.row
4277 || cursor_pos1.col != cursor_pos2.col))
4278 /* cursor in second but not in first */
4279 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004280 else if (cellattr1 != NULL && cellattr2 != NULL)
4281 {
4282 if ((cellattr1 + col)->width
4283 != (cellattr2 + col)->width)
4284 textline[col] = 'w';
4285 else if (!same_color(&(cellattr1 + col)->fg,
4286 &(cellattr2 + col)->fg))
4287 textline[col] = 'f';
4288 else if (!same_color(&(cellattr1 + col)->bg,
4289 &(cellattr2 + col)->bg))
4290 textline[col] = 'b';
4291 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4292 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4293 textline[col] = 'a';
4294 }
4295 p1 += len1;
4296 p2 += len2;
4297 /* TODO: handle different width */
4298 }
4299 vim_free(line1);
4300
4301 while (col < width)
4302 {
4303 if (*p1 == NUL && *p2 == NUL)
4304 textline[col] = '?';
4305 else if (*p1 == NUL)
4306 {
4307 textline[col] = '+';
4308 p2 += utfc_ptr2len(p2);
4309 }
4310 else
4311 {
4312 textline[col] = '-';
4313 p1 += utfc_ptr2len(p1);
4314 }
4315 ++col;
4316 }
4317 }
4318 if (add_empty_scrollback(term, &term->tl_default_color,
4319 term->tl_top_diff_rows) == OK)
4320 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4321 ++bot_lnum;
4322 }
4323
4324 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4325 {
4326 /* bottom part has more rows, fill with "+" */
4327 for (i = 0; i < width; ++i)
4328 textline[i] = '+';
4329 if (add_empty_scrollback(term, &term->tl_default_color,
4330 term->tl_top_diff_rows) == OK)
4331 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4332 ++lnum;
4333 ++bot_lnum;
4334 }
4335
4336 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004337
4338 /* looks better without wrapping */
4339 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004340 }
4341
4342theend:
4343 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004344 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004345 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004346 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004347 fclose(fd2);
4348}
4349
4350/*
4351 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4352 * bottom files.
4353 * Return FAIL when this is not possible.
4354 */
4355 int
4356term_swap_diff()
4357{
4358 term_T *term = curbuf->b_term;
4359 linenr_T line_count;
4360 linenr_T top_rows;
4361 linenr_T bot_rows;
4362 linenr_T bot_start;
4363 linenr_T lnum;
4364 char_u *p;
4365 sb_line_T *sb_line;
4366
4367 if (term == NULL
4368 || !term_is_finished(curbuf)
4369 || term->tl_top_diff_rows == 0
4370 || term->tl_scrollback.ga_len == 0)
4371 return FAIL;
4372
4373 line_count = curbuf->b_ml.ml_line_count;
4374 top_rows = term->tl_top_diff_rows;
4375 bot_rows = term->tl_bot_diff_rows;
4376 bot_start = line_count - bot_rows;
4377 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4378
4379 /* move lines from top to above the bottom part */
4380 for (lnum = 1; lnum <= top_rows; ++lnum)
4381 {
4382 p = vim_strsave(ml_get(1));
4383 if (p == NULL)
4384 return OK;
4385 ml_append(bot_start, p, 0, FALSE);
4386 ml_delete(1, FALSE);
4387 vim_free(p);
4388 }
4389
4390 /* move lines from bottom to the top */
4391 for (lnum = 1; lnum <= bot_rows; ++lnum)
4392 {
4393 p = vim_strsave(ml_get(bot_start + lnum));
4394 if (p == NULL)
4395 return OK;
4396 ml_delete(bot_start + lnum, FALSE);
4397 ml_append(lnum - 1, p, 0, FALSE);
4398 vim_free(p);
4399 }
4400
4401 if (top_rows == bot_rows)
4402 {
4403 /* rows counts are equal, can swap cell properties */
4404 for (lnum = 0; lnum < top_rows; ++lnum)
4405 {
4406 sb_line_T temp;
4407
4408 temp = *(sb_line + lnum);
4409 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4410 *(sb_line + bot_start + lnum) = temp;
4411 }
4412 }
4413 else
4414 {
4415 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4416 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4417
4418 /* need to copy cell properties into temp memory */
4419 if (temp != NULL)
4420 {
4421 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4422 mch_memmove(term->tl_scrollback.ga_data,
4423 temp + bot_start,
4424 sizeof(sb_line_T) * bot_rows);
4425 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4426 temp + top_rows,
4427 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4428 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4429 + line_count - top_rows,
4430 temp,
4431 sizeof(sb_line_T) * top_rows);
4432 vim_free(temp);
4433 }
4434 }
4435
4436 term->tl_top_diff_rows = bot_rows;
4437 term->tl_bot_diff_rows = top_rows;
4438
4439 update_screen(NOT_VALID);
4440 return OK;
4441}
4442
4443/*
4444 * "term_dumpdiff(filename, filename, options)" function
4445 */
4446 void
4447f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4448{
4449 term_load_dump(argvars, rettv, TRUE);
4450}
4451
4452/*
4453 * "term_dumpload(filename, options)" function
4454 */
4455 void
4456f_term_dumpload(typval_T *argvars, typval_T *rettv)
4457{
4458 term_load_dump(argvars, rettv, FALSE);
4459}
4460
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004461/*
4462 * "term_getaltscreen(buf)" function
4463 */
4464 void
4465f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4466{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004467 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004468
4469 if (buf == NULL)
4470 return;
4471 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4472}
4473
4474/*
4475 * "term_getattr(attr, name)" function
4476 */
4477 void
4478f_term_getattr(typval_T *argvars, typval_T *rettv)
4479{
4480 int attr;
4481 size_t i;
4482 char_u *name;
4483
4484 static struct {
4485 char *name;
4486 int attr;
4487 } attrs[] = {
4488 {"bold", HL_BOLD},
4489 {"italic", HL_ITALIC},
4490 {"underline", HL_UNDERLINE},
4491 {"strike", HL_STRIKETHROUGH},
4492 {"reverse", HL_INVERSE},
4493 };
4494
4495 attr = get_tv_number(&argvars[0]);
4496 name = get_tv_string_chk(&argvars[1]);
4497 if (name == NULL)
4498 return;
4499
4500 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4501 if (STRCMP(name, attrs[i].name) == 0)
4502 {
4503 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4504 break;
4505 }
4506}
4507
4508/*
4509 * "term_getcursor(buf)" function
4510 */
4511 void
4512f_term_getcursor(typval_T *argvars, typval_T *rettv)
4513{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004514 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004515 term_T *term;
4516 list_T *l;
4517 dict_T *d;
4518
4519 if (rettv_list_alloc(rettv) == FAIL)
4520 return;
4521 if (buf == NULL)
4522 return;
4523 term = buf->b_term;
4524
4525 l = rettv->vval.v_list;
4526 list_append_number(l, term->tl_cursor_pos.row + 1);
4527 list_append_number(l, term->tl_cursor_pos.col + 1);
4528
4529 d = dict_alloc();
4530 if (d != NULL)
4531 {
4532 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4533 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4534 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4535 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4536 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4537 ? (char_u *)"" : term->tl_cursor_color);
4538 list_append_dict(l, d);
4539 }
4540}
4541
4542/*
4543 * "term_getjob(buf)" function
4544 */
4545 void
4546f_term_getjob(typval_T *argvars, typval_T *rettv)
4547{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004548 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004549
4550 rettv->v_type = VAR_JOB;
4551 rettv->vval.v_job = NULL;
4552 if (buf == NULL)
4553 return;
4554
4555 rettv->vval.v_job = buf->b_term->tl_job;
4556 if (rettv->vval.v_job != NULL)
4557 ++rettv->vval.v_job->jv_refcount;
4558}
4559
4560 static int
4561get_row_number(typval_T *tv, term_T *term)
4562{
4563 if (tv->v_type == VAR_STRING
4564 && tv->vval.v_string != NULL
4565 && STRCMP(tv->vval.v_string, ".") == 0)
4566 return term->tl_cursor_pos.row;
4567 return (int)get_tv_number(tv) - 1;
4568}
4569
4570/*
4571 * "term_getline(buf, row)" function
4572 */
4573 void
4574f_term_getline(typval_T *argvars, typval_T *rettv)
4575{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004576 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004577 term_T *term;
4578 int row;
4579
4580 rettv->v_type = VAR_STRING;
4581 if (buf == NULL)
4582 return;
4583 term = buf->b_term;
4584 row = get_row_number(&argvars[1], term);
4585
4586 if (term->tl_vterm == NULL)
4587 {
4588 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4589
4590 /* vterm is finished, get the text from the buffer */
4591 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4592 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4593 }
4594 else
4595 {
4596 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4597 VTermRect rect;
4598 int len;
4599 char_u *p;
4600
4601 if (row < 0 || row >= term->tl_rows)
4602 return;
4603 len = term->tl_cols * MB_MAXBYTES + 1;
4604 p = alloc(len);
4605 if (p == NULL)
4606 return;
4607 rettv->vval.v_string = p;
4608
4609 rect.start_col = 0;
4610 rect.end_col = term->tl_cols;
4611 rect.start_row = row;
4612 rect.end_row = row + 1;
4613 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4614 }
4615}
4616
4617/*
4618 * "term_getscrolled(buf)" function
4619 */
4620 void
4621f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4622{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004623 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004624
4625 if (buf == NULL)
4626 return;
4627 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4628}
4629
4630/*
4631 * "term_getsize(buf)" function
4632 */
4633 void
4634f_term_getsize(typval_T *argvars, typval_T *rettv)
4635{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004636 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004637 list_T *l;
4638
4639 if (rettv_list_alloc(rettv) == FAIL)
4640 return;
4641 if (buf == NULL)
4642 return;
4643
4644 l = rettv->vval.v_list;
4645 list_append_number(l, buf->b_term->tl_rows);
4646 list_append_number(l, buf->b_term->tl_cols);
4647}
4648
4649/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004650 * "term_setsize(buf, rows, cols)" function
4651 */
4652 void
4653f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4654{
4655 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4656 term_T *term;
4657 varnumber_T rows, cols;
4658
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004659 if (buf == NULL)
4660 {
4661 EMSG(_("E955: Not a terminal buffer"));
4662 return;
4663 }
4664 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004665 return;
4666 term = buf->b_term;
4667 rows = get_tv_number(&argvars[1]);
4668 rows = rows <= 0 ? term->tl_rows : rows;
4669 cols = get_tv_number(&argvars[2]);
4670 cols = cols <= 0 ? term->tl_cols : cols;
4671 vterm_set_size(term->tl_vterm, rows, cols);
4672 /* handle_resize() will resize the windows */
4673
4674 /* Get and remember the size we ended up with. Update the pty. */
4675 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4676 term_report_winsize(term, term->tl_rows, term->tl_cols);
4677}
4678
4679/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004680 * "term_getstatus(buf)" function
4681 */
4682 void
4683f_term_getstatus(typval_T *argvars, typval_T *rettv)
4684{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004685 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004686 term_T *term;
4687 char_u val[100];
4688
4689 rettv->v_type = VAR_STRING;
4690 if (buf == NULL)
4691 return;
4692 term = buf->b_term;
4693
4694 if (term_job_running(term))
4695 STRCPY(val, "running");
4696 else
4697 STRCPY(val, "finished");
4698 if (term->tl_normal_mode)
4699 STRCAT(val, ",normal");
4700 rettv->vval.v_string = vim_strsave(val);
4701}
4702
4703/*
4704 * "term_gettitle(buf)" function
4705 */
4706 void
4707f_term_gettitle(typval_T *argvars, typval_T *rettv)
4708{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004709 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004710
4711 rettv->v_type = VAR_STRING;
4712 if (buf == NULL)
4713 return;
4714
4715 if (buf->b_term->tl_title != NULL)
4716 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4717}
4718
4719/*
4720 * "term_gettty(buf)" function
4721 */
4722 void
4723f_term_gettty(typval_T *argvars, typval_T *rettv)
4724{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004725 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004726 char_u *p;
4727 int num = 0;
4728
4729 rettv->v_type = VAR_STRING;
4730 if (buf == NULL)
4731 return;
4732 if (argvars[1].v_type != VAR_UNKNOWN)
4733 num = get_tv_number(&argvars[1]);
4734
4735 switch (num)
4736 {
4737 case 0:
4738 if (buf->b_term->tl_job != NULL)
4739 p = buf->b_term->tl_job->jv_tty_out;
4740 else
4741 p = buf->b_term->tl_tty_out;
4742 break;
4743 case 1:
4744 if (buf->b_term->tl_job != NULL)
4745 p = buf->b_term->tl_job->jv_tty_in;
4746 else
4747 p = buf->b_term->tl_tty_in;
4748 break;
4749 default:
4750 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4751 return;
4752 }
4753 if (p != NULL)
4754 rettv->vval.v_string = vim_strsave(p);
4755}
4756
4757/*
4758 * "term_list()" function
4759 */
4760 void
4761f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4762{
4763 term_T *tp;
4764 list_T *l;
4765
4766 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4767 return;
4768
4769 l = rettv->vval.v_list;
4770 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4771 if (tp != NULL && tp->tl_buffer != NULL)
4772 if (list_append_number(l,
4773 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4774 return;
4775}
4776
4777/*
4778 * "term_scrape(buf, row)" function
4779 */
4780 void
4781f_term_scrape(typval_T *argvars, typval_T *rettv)
4782{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004783 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004784 VTermScreen *screen = NULL;
4785 VTermPos pos;
4786 list_T *l;
4787 term_T *term;
4788 char_u *p;
4789 sb_line_T *line;
4790
4791 if (rettv_list_alloc(rettv) == FAIL)
4792 return;
4793 if (buf == NULL)
4794 return;
4795 term = buf->b_term;
4796
4797 l = rettv->vval.v_list;
4798 pos.row = get_row_number(&argvars[1], term);
4799
4800 if (term->tl_vterm != NULL)
4801 {
4802 screen = vterm_obtain_screen(term->tl_vterm);
4803 p = NULL;
4804 line = NULL;
4805 }
4806 else
4807 {
4808 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4809
4810 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4811 return;
4812 p = ml_get_buf(buf, lnum + 1, FALSE);
4813 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4814 }
4815
4816 for (pos.col = 0; pos.col < term->tl_cols; )
4817 {
4818 dict_T *dcell;
4819 int width;
4820 VTermScreenCellAttrs attrs;
4821 VTermColor fg, bg;
4822 char_u rgb[8];
4823 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4824 int off = 0;
4825 int i;
4826
4827 if (screen == NULL)
4828 {
4829 cellattr_T *cellattr;
4830 int len;
4831
4832 /* vterm has finished, get the cell from scrollback */
4833 if (pos.col >= line->sb_cols)
4834 break;
4835 cellattr = line->sb_cells + pos.col;
4836 width = cellattr->width;
4837 attrs = cellattr->attrs;
4838 fg = cellattr->fg;
4839 bg = cellattr->bg;
4840 len = MB_PTR2LEN(p);
4841 mch_memmove(mbs, p, len);
4842 mbs[len] = NUL;
4843 p += len;
4844 }
4845 else
4846 {
4847 VTermScreenCell cell;
4848 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4849 break;
4850 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4851 {
4852 if (cell.chars[i] == 0)
4853 break;
4854 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4855 }
4856 mbs[off] = NUL;
4857 width = cell.width;
4858 attrs = cell.attrs;
4859 fg = cell.fg;
4860 bg = cell.bg;
4861 }
4862 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004863 if (dcell == NULL)
4864 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004865 list_append_dict(l, dcell);
4866
4867 dict_add_nr_str(dcell, "chars", 0, mbs);
4868
4869 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4870 fg.red, fg.green, fg.blue);
4871 dict_add_nr_str(dcell, "fg", 0, rgb);
4872 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4873 bg.red, bg.green, bg.blue);
4874 dict_add_nr_str(dcell, "bg", 0, rgb);
4875
4876 dict_add_nr_str(dcell, "attr",
4877 cell2attr(attrs, fg, bg), NULL);
4878 dict_add_nr_str(dcell, "width", width, NULL);
4879
4880 ++pos.col;
4881 if (width == 2)
4882 ++pos.col;
4883 }
4884}
4885
4886/*
4887 * "term_sendkeys(buf, keys)" function
4888 */
4889 void
4890f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4891{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004892 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004893 char_u *msg;
4894 term_T *term;
4895
4896 rettv->v_type = VAR_UNKNOWN;
4897 if (buf == NULL)
4898 return;
4899
4900 msg = get_tv_string_chk(&argvars[1]);
4901 if (msg == NULL)
4902 return;
4903 term = buf->b_term;
4904 if (term->tl_vterm == NULL)
4905 return;
4906
4907 while (*msg != NUL)
4908 {
4909 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004910 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004911 }
4912}
4913
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004914#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4915/*
4916 * "term_getansicolors(buf)" function
4917 */
4918 void
4919f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4920{
4921 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4922 term_T *term;
4923 VTermState *state;
4924 VTermColor color;
4925 char_u hexbuf[10];
4926 int index;
4927 list_T *list;
4928
4929 if (rettv_list_alloc(rettv) == FAIL)
4930 return;
4931
4932 if (buf == NULL)
4933 return;
4934 term = buf->b_term;
4935 if (term->tl_vterm == NULL)
4936 return;
4937
4938 list = rettv->vval.v_list;
4939 state = vterm_obtain_state(term->tl_vterm);
4940 for (index = 0; index < 16; index++)
4941 {
4942 vterm_state_get_palette_color(state, index, &color);
4943 sprintf((char *)hexbuf, "#%02x%02x%02x",
4944 color.red, color.green, color.blue);
4945 if (list_append_string(list, hexbuf, 7) == FAIL)
4946 return;
4947 }
4948}
4949
4950/*
4951 * "term_setansicolors(buf, list)" function
4952 */
4953 void
4954f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4955{
4956 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4957 term_T *term;
4958
4959 if (buf == NULL)
4960 return;
4961 term = buf->b_term;
4962 if (term->tl_vterm == NULL)
4963 return;
4964
4965 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4966 {
4967 EMSG(_(e_listreq));
4968 return;
4969 }
4970
4971 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
4972 EMSG(_(e_invarg));
4973}
4974#endif
4975
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004976/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004977 * "term_setrestore(buf, command)" function
4978 */
4979 void
4980f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4981{
4982#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004983 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004984 term_T *term;
4985 char_u *cmd;
4986
4987 if (buf == NULL)
4988 return;
4989 term = buf->b_term;
4990 vim_free(term->tl_command);
4991 cmd = get_tv_string_chk(&argvars[1]);
4992 if (cmd != NULL)
4993 term->tl_command = vim_strsave(cmd);
4994 else
4995 term->tl_command = NULL;
4996#endif
4997}
4998
4999/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005000 * "term_setkill(buf, how)" function
5001 */
5002 void
5003f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5004{
5005 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5006 term_T *term;
5007 char_u *how;
5008
5009 if (buf == NULL)
5010 return;
5011 term = buf->b_term;
5012 vim_free(term->tl_kill);
5013 how = get_tv_string_chk(&argvars[1]);
5014 if (how != NULL)
5015 term->tl_kill = vim_strsave(how);
5016 else
5017 term->tl_kill = NULL;
5018}
5019
5020/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005021 * "term_start(command, options)" function
5022 */
5023 void
5024f_term_start(typval_T *argvars, typval_T *rettv)
5025{
5026 jobopt_T opt;
5027 buf_T *buf;
5028
5029 init_job_options(&opt);
5030 if (argvars[1].v_type != VAR_UNKNOWN
5031 && get_job_options(&argvars[1], &opt,
5032 JO_TIMEOUT_ALL + JO_STOPONEXIT
5033 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5034 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5035 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5036 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005037 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005038 + JO2_NORESTORE + JO2_TERM_KILL
5039 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005040 return;
5041
Bram Moolenaar13568252018-03-16 20:46:58 +01005042 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005043
5044 if (buf != NULL && buf->b_term != NULL)
5045 rettv->vval.v_number = buf->b_fnum;
5046}
5047
5048/*
5049 * "term_wait" function
5050 */
5051 void
5052f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5053{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005054 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005055
5056 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005057 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005058 if (buf->b_term->tl_job == NULL)
5059 {
5060 ch_log(NULL, "term_wait(): no job to wait for");
5061 return;
5062 }
5063 if (buf->b_term->tl_job->jv_channel == NULL)
5064 /* channel is closed, nothing to do */
5065 return;
5066
5067 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005068 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005069 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5070 {
5071 /* The job is dead, keep reading channel I/O until the channel is
5072 * closed. buf->b_term may become NULL if the terminal was closed while
5073 * waiting. */
5074 ch_log(NULL, "term_wait(): waiting for channel to close");
5075 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5076 {
5077 mch_check_messages();
5078 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005079 if (!buf_valid(buf))
5080 /* If the terminal is closed when the channel is closed the
5081 * buffer disappears. */
5082 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005083 ui_delay(10L, FALSE);
5084 }
5085 mch_check_messages();
5086 parse_queued_messages();
5087 }
5088 else
5089 {
5090 long wait = 10L;
5091
5092 mch_check_messages();
5093 parse_queued_messages();
5094
5095 /* Wait for some time for any channel I/O. */
5096 if (argvars[1].v_type != VAR_UNKNOWN)
5097 wait = get_tv_number(&argvars[1]);
5098 ui_delay(wait, TRUE);
5099 mch_check_messages();
5100
5101 /* Flushing messages on channels is hopefully sufficient.
5102 * TODO: is there a better way? */
5103 parse_queued_messages();
5104 }
5105}
5106
5107/*
5108 * Called when a channel has sent all the lines to a terminal.
5109 * Send a CTRL-D to mark the end of the text.
5110 */
5111 void
5112term_send_eof(channel_T *ch)
5113{
5114 term_T *term;
5115
5116 for (term = first_term; term != NULL; term = term->tl_next)
5117 if (term->tl_job == ch->ch_job)
5118 {
5119 if (term->tl_eof_chars != NULL)
5120 {
5121 channel_send(ch, PART_IN, term->tl_eof_chars,
5122 (int)STRLEN(term->tl_eof_chars), NULL);
5123 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5124 }
5125# ifdef WIN3264
5126 else
5127 /* Default: CTRL-D */
5128 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5129# endif
5130 }
5131}
5132
5133# if defined(WIN3264) || defined(PROTO)
5134
5135/**************************************
5136 * 2. MS-Windows implementation.
5137 */
5138
5139# ifndef PROTO
5140
5141#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5142#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005143#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005144
5145void* (*winpty_config_new)(UINT64, void*);
5146void* (*winpty_open)(void*, void*);
5147void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5148BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5149void (*winpty_config_set_mouse_mode)(void*, int);
5150void (*winpty_config_set_initial_size)(void*, int, int);
5151LPCWSTR (*winpty_conin_name)(void*);
5152LPCWSTR (*winpty_conout_name)(void*);
5153LPCWSTR (*winpty_conerr_name)(void*);
5154void (*winpty_free)(void*);
5155void (*winpty_config_free)(void*);
5156void (*winpty_spawn_config_free)(void*);
5157void (*winpty_error_free)(void*);
5158LPCWSTR (*winpty_error_msg)(void*);
5159BOOL (*winpty_set_size)(void*, int, int, void*);
5160HANDLE (*winpty_agent_process)(void*);
5161
5162#define WINPTY_DLL "winpty.dll"
5163
5164static HINSTANCE hWinPtyDLL = NULL;
5165# endif
5166
5167 static int
5168dyn_winpty_init(int verbose)
5169{
5170 int i;
5171 static struct
5172 {
5173 char *name;
5174 FARPROC *ptr;
5175 } winpty_entry[] =
5176 {
5177 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5178 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5179 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5180 {"winpty_config_set_mouse_mode",
5181 (FARPROC*)&winpty_config_set_mouse_mode},
5182 {"winpty_config_set_initial_size",
5183 (FARPROC*)&winpty_config_set_initial_size},
5184 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5185 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5186 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5187 {"winpty_free", (FARPROC*)&winpty_free},
5188 {"winpty_open", (FARPROC*)&winpty_open},
5189 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5190 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5191 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5192 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5193 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5194 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5195 {NULL, NULL}
5196 };
5197
5198 /* No need to initialize twice. */
5199 if (hWinPtyDLL)
5200 return OK;
5201 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5202 * winpty.dll. */
5203 if (*p_winptydll != NUL)
5204 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5205 if (!hWinPtyDLL)
5206 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5207 if (!hWinPtyDLL)
5208 {
5209 if (verbose)
5210 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5211 : (char_u *)WINPTY_DLL);
5212 return FAIL;
5213 }
5214 for (i = 0; winpty_entry[i].name != NULL
5215 && winpty_entry[i].ptr != NULL; ++i)
5216 {
5217 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5218 winpty_entry[i].name)) == NULL)
5219 {
5220 if (verbose)
5221 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5222 return FAIL;
5223 }
5224 }
5225
5226 return OK;
5227}
5228
5229/*
5230 * Create a new terminal of "rows" by "cols" cells.
5231 * Store a reference in "term".
5232 * Return OK or FAIL.
5233 */
5234 static int
5235term_and_job_init(
5236 term_T *term,
5237 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005238 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005239 jobopt_T *opt)
5240{
5241 WCHAR *cmd_wchar = NULL;
5242 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005243 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005244 channel_T *channel = NULL;
5245 job_T *job = NULL;
5246 DWORD error;
5247 HANDLE jo = NULL;
5248 HANDLE child_process_handle;
5249 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005250 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005251 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005252 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005253 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005254
5255 if (dyn_winpty_init(TRUE) == FAIL)
5256 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005257 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5258 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005259
5260 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005261 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005262 cmd = argvar->vval.v_string;
5263 }
5264 else if (argvar->v_type == VAR_LIST)
5265 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005266 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005267 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005268 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005269 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005270 if (cmd == NULL || *cmd == NUL)
5271 {
5272 EMSG(_(e_invarg));
5273 goto failed;
5274 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005275
5276 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005277 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005278 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005279 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005280 if (opt->jo_cwd != NULL)
5281 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005282
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005283 win32_build_env(opt->jo_env, &ga_env, TRUE);
5284 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005285
5286 job = job_alloc();
5287 if (job == NULL)
5288 goto failed;
5289
5290 channel = add_channel();
5291 if (channel == NULL)
5292 goto failed;
5293
5294 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5295 if (term->tl_winpty_config == NULL)
5296 goto failed;
5297
5298 winpty_config_set_mouse_mode(term->tl_winpty_config,
5299 WINPTY_MOUSE_MODE_FORCE);
5300 winpty_config_set_initial_size(term->tl_winpty_config,
5301 term->tl_cols, term->tl_rows);
5302 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5303 if (term->tl_winpty == NULL)
5304 goto failed;
5305
5306 spawn_config = winpty_spawn_config_new(
5307 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5308 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5309 NULL,
5310 cmd_wchar,
5311 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005312 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005313 &winpty_err);
5314 if (spawn_config == NULL)
5315 goto failed;
5316
5317 channel = add_channel();
5318 if (channel == NULL)
5319 goto failed;
5320
5321 job = job_alloc();
5322 if (job == NULL)
5323 goto failed;
5324
5325 if (opt->jo_set & JO_IN_BUF)
5326 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5327
5328 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5329 &child_thread_handle, &error, &winpty_err))
5330 goto failed;
5331
5332 channel_set_pipes(channel,
5333 (sock_T)CreateFileW(
5334 winpty_conin_name(term->tl_winpty),
5335 GENERIC_WRITE, 0, NULL,
5336 OPEN_EXISTING, 0, NULL),
5337 (sock_T)CreateFileW(
5338 winpty_conout_name(term->tl_winpty),
5339 GENERIC_READ, 0, NULL,
5340 OPEN_EXISTING, 0, NULL),
5341 (sock_T)CreateFileW(
5342 winpty_conerr_name(term->tl_winpty),
5343 GENERIC_READ, 0, NULL,
5344 OPEN_EXISTING, 0, NULL));
5345
5346 /* Write lines with CR instead of NL. */
5347 channel->ch_write_text_mode = TRUE;
5348
5349 jo = CreateJobObject(NULL, NULL);
5350 if (jo == NULL)
5351 goto failed;
5352
5353 if (!AssignProcessToJobObject(jo, child_process_handle))
5354 {
5355 /* Failed, switch the way to terminate process with TerminateProcess. */
5356 CloseHandle(jo);
5357 jo = NULL;
5358 }
5359
5360 winpty_spawn_config_free(spawn_config);
5361 vim_free(cmd_wchar);
5362 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005363 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005364
5365 create_vterm(term, term->tl_rows, term->tl_cols);
5366
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005367#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5368 if (opt->jo_set2 & JO2_ANSI_COLORS)
5369 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5370 else
5371 init_vterm_ansi_colors(term->tl_vterm);
5372#endif
5373
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005374 channel_set_job(channel, job, opt);
5375 job_set_options(job, opt);
5376
5377 job->jv_channel = channel;
5378 job->jv_proc_info.hProcess = child_process_handle;
5379 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5380 job->jv_job_object = jo;
5381 job->jv_status = JOB_STARTED;
5382 job->jv_tty_in = utf16_to_enc(
5383 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5384 job->jv_tty_out = utf16_to_enc(
5385 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5386 ++job->jv_refcount;
5387 term->tl_job = job;
5388
5389 return OK;
5390
5391failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005392 ga_clear(&ga_cmd);
5393 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005394 vim_free(cmd_wchar);
5395 vim_free(cwd_wchar);
5396 if (spawn_config != NULL)
5397 winpty_spawn_config_free(spawn_config);
5398 if (channel != NULL)
5399 channel_clear(channel);
5400 if (job != NULL)
5401 {
5402 job->jv_channel = NULL;
5403 job_cleanup(job);
5404 }
5405 term->tl_job = NULL;
5406 if (jo != NULL)
5407 CloseHandle(jo);
5408 if (term->tl_winpty != NULL)
5409 winpty_free(term->tl_winpty);
5410 term->tl_winpty = NULL;
5411 if (term->tl_winpty_config != NULL)
5412 winpty_config_free(term->tl_winpty_config);
5413 term->tl_winpty_config = NULL;
5414 if (winpty_err != NULL)
5415 {
5416 char_u *msg = utf16_to_enc(
5417 (short_u *)winpty_error_msg(winpty_err), NULL);
5418
5419 EMSG(msg);
5420 winpty_error_free(winpty_err);
5421 }
5422 return FAIL;
5423}
5424
5425 static int
5426create_pty_only(term_T *term, jobopt_T *options)
5427{
5428 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5429 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5430 char in_name[80], out_name[80];
5431 channel_T *channel = NULL;
5432
5433 create_vterm(term, term->tl_rows, term->tl_cols);
5434
5435 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5436 GetCurrentProcessId(),
5437 curbuf->b_fnum);
5438 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5439 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5440 PIPE_UNLIMITED_INSTANCES,
5441 0, 0, NMPWAIT_NOWAIT, NULL);
5442 if (hPipeIn == INVALID_HANDLE_VALUE)
5443 goto failed;
5444
5445 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5446 GetCurrentProcessId(),
5447 curbuf->b_fnum);
5448 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5449 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5450 PIPE_UNLIMITED_INSTANCES,
5451 0, 0, 0, NULL);
5452 if (hPipeOut == INVALID_HANDLE_VALUE)
5453 goto failed;
5454
5455 ConnectNamedPipe(hPipeIn, NULL);
5456 ConnectNamedPipe(hPipeOut, NULL);
5457
5458 term->tl_job = job_alloc();
5459 if (term->tl_job == NULL)
5460 goto failed;
5461 ++term->tl_job->jv_refcount;
5462
5463 /* behave like the job is already finished */
5464 term->tl_job->jv_status = JOB_FINISHED;
5465
5466 channel = add_channel();
5467 if (channel == NULL)
5468 goto failed;
5469 term->tl_job->jv_channel = channel;
5470 channel->ch_keep_open = TRUE;
5471 channel->ch_named_pipe = TRUE;
5472
5473 channel_set_pipes(channel,
5474 (sock_T)hPipeIn,
5475 (sock_T)hPipeOut,
5476 (sock_T)hPipeOut);
5477 channel_set_job(channel, term->tl_job, options);
5478 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5479 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5480
5481 return OK;
5482
5483failed:
5484 if (hPipeIn != NULL)
5485 CloseHandle(hPipeIn);
5486 if (hPipeOut != NULL)
5487 CloseHandle(hPipeOut);
5488 return FAIL;
5489}
5490
5491/*
5492 * Free the terminal emulator part of "term".
5493 */
5494 static void
5495term_free_vterm(term_T *term)
5496{
5497 if (term->tl_winpty != NULL)
5498 winpty_free(term->tl_winpty);
5499 term->tl_winpty = NULL;
5500 if (term->tl_winpty_config != NULL)
5501 winpty_config_free(term->tl_winpty_config);
5502 term->tl_winpty_config = NULL;
5503 if (term->tl_vterm != NULL)
5504 vterm_free(term->tl_vterm);
5505 term->tl_vterm = NULL;
5506}
5507
5508/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005509 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005510 */
5511 static void
5512term_report_winsize(term_T *term, int rows, int cols)
5513{
5514 if (term->tl_winpty)
5515 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5516}
5517
5518 int
5519terminal_enabled(void)
5520{
5521 return dyn_winpty_init(FALSE) == OK;
5522}
5523
5524# else
5525
5526/**************************************
5527 * 3. Unix-like implementation.
5528 */
5529
5530/*
5531 * Create a new terminal of "rows" by "cols" cells.
5532 * Start job for "cmd".
5533 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005534 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005535 * Return OK or FAIL.
5536 */
5537 static int
5538term_and_job_init(
5539 term_T *term,
5540 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005541 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005542 jobopt_T *opt)
5543{
5544 create_vterm(term, term->tl_rows, term->tl_cols);
5545
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005546#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5547 if (opt->jo_set2 & JO2_ANSI_COLORS)
5548 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5549 else
5550 init_vterm_ansi_colors(term->tl_vterm);
5551#endif
5552
Bram Moolenaar13568252018-03-16 20:46:58 +01005553 /* This may change a string in "argvar". */
5554 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005555 if (term->tl_job != NULL)
5556 ++term->tl_job->jv_refcount;
5557
5558 return term->tl_job != NULL
5559 && term->tl_job->jv_channel != NULL
5560 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5561}
5562
5563 static int
5564create_pty_only(term_T *term, jobopt_T *opt)
5565{
5566 create_vterm(term, term->tl_rows, term->tl_cols);
5567
5568 term->tl_job = job_alloc();
5569 if (term->tl_job == NULL)
5570 return FAIL;
5571 ++term->tl_job->jv_refcount;
5572
5573 /* behave like the job is already finished */
5574 term->tl_job->jv_status = JOB_FINISHED;
5575
5576 return mch_create_pty_channel(term->tl_job, opt);
5577}
5578
5579/*
5580 * Free the terminal emulator part of "term".
5581 */
5582 static void
5583term_free_vterm(term_T *term)
5584{
5585 if (term->tl_vterm != NULL)
5586 vterm_free(term->tl_vterm);
5587 term->tl_vterm = NULL;
5588}
5589
5590/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005591 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005592 */
5593 static void
5594term_report_winsize(term_T *term, int rows, int cols)
5595{
5596 /* Use an ioctl() to report the new window size to the job. */
5597 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5598 {
5599 int fd = -1;
5600 int part;
5601
5602 for (part = PART_OUT; part < PART_COUNT; ++part)
5603 {
5604 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5605 if (isatty(fd))
5606 break;
5607 }
5608 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5609 mch_signal_job(term->tl_job, (char_u *)"winch");
5610 }
5611}
5612
5613# endif
5614
5615#endif /* FEAT_TERMINAL */