blob: ff76ca1c6c2ab8e567b6981fdacc2e1a0bb572ef [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 Moolenaar6d150f72018-04-21 20:03:20 +020045 * - Add test for 'termwinkey'.
46 * - libvterm: bringg back using // comments and trailing comma in enum
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 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaara997b452018-04-17 23:24:06 +020051 * - handle_moverect() scrolls one line at a time. Postpone scrolling, count
52 * the number of lines, until a redraw happens. Then if scrolling many lines
53 * a redraw is faster.
Bram Moolenaar498c2562018-04-15 23:45:15 +020054 * - Copy text in the vterm to the Vim buffer once in a while, so that
55 * completion works.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020056 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020057 * - For the GUI fill termios with default values, perhaps like pangoterm:
58 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020059 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020061 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
62 * "run". Everything else works, including communication channel. Not
63 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020064 */
65
66#include "vim.h"
67
68#if defined(FEAT_TERMINAL) || defined(PROTO)
69
70#ifndef MIN
71# define MIN(x,y) ((x) < (y) ? (x) : (y))
72#endif
73#ifndef MAX
74# define MAX(x,y) ((x) > (y) ? (x) : (y))
75#endif
76
77#include "libvterm/include/vterm.h"
78
79/* This is VTermScreenCell without the characters, thus much smaller. */
80typedef struct {
81 VTermScreenCellAttrs attrs;
82 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010083 VTermColor fg;
84 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020085} cellattr_T;
86
87typedef struct sb_line_S {
88 int sb_cols; /* can differ per line */
89 cellattr_T *sb_cells; /* allocated */
90 cellattr_T sb_fill_attr; /* for short line */
91} sb_line_T;
92
93/* typedef term_T in structs.h */
94struct terminal_S {
95 term_T *tl_next;
96
97 VTerm *tl_vterm;
98 job_T *tl_job;
99 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +0100100#if defined(FEAT_GUI)
101 int tl_system; /* when non-zero used for :!cmd output */
102 int tl_toprow; /* row with first line of system terminal */
103#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200104
105 /* Set when setting the size of a vterm, reset after redrawing. */
106 int tl_vterm_size_changed;
107
108 /* used when tl_job is NULL and only a pty was created */
109 int tl_tty_fd;
110 char_u *tl_tty_in;
111 char_u *tl_tty_out;
112
113 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
114 int tl_channel_closed;
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100115 int tl_finish;
116#define TL_FINISH_UNSET NUL
117#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
118#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
119#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200120 char_u *tl_opencmd;
121 char_u *tl_eof_chars;
122
123#ifdef WIN3264
124 void *tl_winpty_config;
125 void *tl_winpty;
126#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100127#if defined(FEAT_SESSION)
128 char_u *tl_command;
129#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100130 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131
132 /* last known vterm size */
133 int tl_rows;
134 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200135
136 char_u *tl_title; /* NULL or allocated */
137 char_u *tl_status_text; /* NULL or allocated */
138
139 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200140 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200141 int tl_dirty_row_end; /* row below last one to update */
142
143 garray_T tl_scrollback;
144 int tl_scrollback_scrolled;
145 cellattr_T tl_default_color;
146
Bram Moolenaard96ff162018-02-18 22:13:29 +0100147 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
148 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
149
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200150 VTermPos tl_cursor_pos;
151 int tl_cursor_visible;
152 int tl_cursor_blink;
153 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
154 char_u *tl_cursor_color; /* NULL or allocated */
155
156 int tl_using_altscreen;
157};
158
159#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
160#define TMODE_LOOP 2 /* CTRL-W N used */
161
162/*
163 * List of all active terminals.
164 */
165static term_T *first_term = NULL;
166
167/* Terminal active in terminal_loop(). */
168static term_T *in_terminal_loop = NULL;
169
170#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
171#define KEY_BUF_LEN 200
172
173/*
174 * Functions with separate implementation for MS-Windows and Unix-like systems.
175 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100176static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200177static int create_pty_only(term_T *term, jobopt_T *opt);
178static void term_report_winsize(term_T *term, int rows, int cols);
179static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100180#ifdef FEAT_GUI
181static void update_system_term(term_T *term);
182#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200183
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100184/* The character that we know (or assume) that the terminal expects for the
185 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100188/* "Terminal" highlight group colors. */
189static int term_default_cterm_fg = -1;
190static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200191
Bram Moolenaard317b382018-02-08 22:33:31 +0100192/* Store the last set and the desired cursor properties, so that we only update
193 * them when needed. Doing it unnecessary may result in flicker. */
194static char_u *last_set_cursor_color = (char_u *)"";
195static char_u *desired_cursor_color = (char_u *)"";
196static int last_set_cursor_shape = -1;
197static int desired_cursor_shape = -1;
198static int last_set_cursor_blink = -1;
199static int desired_cursor_blink = -1;
200
201
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200202/**************************************
203 * 1. Generic code for all systems.
204 */
205
206/*
Bram Moolenaar498c2562018-04-15 23:45:15 +0200207 * Parse 'termsize' and set "rows" and "cols" for the terminal size in the
208 * current window.
209 * Sets "rows" and/or "cols" to zero when it should follow the window size.
210 * Return TRUE if the size is the minimum size: "24*80".
211 */
212 static int
213parse_termsize(win_T *wp, int *rows, int *cols)
214{
215 int minsize = FALSE;
216
217 *rows = 0;
218 *cols = 0;
219
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200220 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200221 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200222 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200223
224 /* Syntax of value was already checked when it's set. */
225 if (p == NULL)
226 {
227 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200228 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200229 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200230 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200231 *cols = atoi((char *)p + 1);
232 }
233 return minsize;
234}
235
236/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200237 * Determine the terminal size from 'termsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200238 */
239 static void
240set_term_and_win_size(term_T *term)
241{
Bram Moolenaar13568252018-03-16 20:46:58 +0100242#ifdef FEAT_GUI
243 if (term->tl_system)
244 {
245 /* Use the whole screen for the system command. However, it will start
246 * at the command line and scroll up as needed, using tl_toprow. */
247 term->tl_rows = Rows;
248 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200249 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100250 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100251#endif
Bram Moolenaar498c2562018-04-15 23:45:15 +0200252 if (parse_termsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200253 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200254 if (term->tl_rows != 0)
255 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
256 if (term->tl_cols != 0)
257 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200258 }
259 if (term->tl_rows == 0)
260 term->tl_rows = curwin->w_height;
261 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200262 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200263 if (term->tl_cols == 0)
264 term->tl_cols = curwin->w_width;
265 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200266 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200267}
268
269/*
270 * Initialize job options for a terminal job.
271 * Caller may overrule some of them.
272 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100273 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200274init_job_options(jobopt_T *opt)
275{
276 clear_job_options(opt);
277
278 opt->jo_mode = MODE_RAW;
279 opt->jo_out_mode = MODE_RAW;
280 opt->jo_err_mode = MODE_RAW;
281 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
282}
283
284/*
285 * Set job options mandatory for a terminal job.
286 */
287 static void
288setup_job_options(jobopt_T *opt, int rows, int cols)
289{
290 if (!(opt->jo_set & JO_OUT_IO))
291 {
292 /* Connect stdout to the terminal. */
293 opt->jo_io[PART_OUT] = JIO_BUFFER;
294 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
295 opt->jo_modifiable[PART_OUT] = 0;
296 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
297 }
298
299 if (!(opt->jo_set & JO_ERR_IO))
300 {
301 /* Connect stderr to the terminal. */
302 opt->jo_io[PART_ERR] = JIO_BUFFER;
303 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
304 opt->jo_modifiable[PART_ERR] = 0;
305 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
306 }
307
308 opt->jo_pty = TRUE;
309 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
310 opt->jo_term_rows = rows;
311 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
312 opt->jo_term_cols = cols;
313}
314
315/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100316 * Close a terminal buffer (and its window). Used when creating the terminal
317 * fails.
318 */
319 static void
320term_close_buffer(buf_T *buf, buf_T *old_curbuf)
321{
322 free_terminal(buf);
323 if (old_curbuf != NULL)
324 {
325 --curbuf->b_nwindows;
326 curbuf = old_curbuf;
327 curwin->w_buffer = curbuf;
328 ++curbuf->b_nwindows;
329 }
330
331 /* Wiping out the buffer will also close the window and call
332 * free_terminal(). */
333 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
334}
335
336/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200337 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100338 * Use either "argvar" or "argv", the other must be NULL.
339 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
340 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200341 * Returns NULL when failed.
342 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100343 buf_T *
344term_start(
345 typval_T *argvar,
346 char **argv,
347 jobopt_T *opt,
348 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200349{
350 exarg_T split_ea;
351 win_T *old_curwin = curwin;
352 term_T *term;
353 buf_T *old_curbuf = NULL;
354 int res;
355 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100356 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200357
358 if (check_restricted() || check_secure())
359 return NULL;
360
361 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
362 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
363 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
364 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
365 {
366 EMSG(_(e_invarg));
367 return NULL;
368 }
369
370 term = (term_T *)alloc_clear(sizeof(term_T));
371 if (term == NULL)
372 return NULL;
373 term->tl_dirty_row_end = MAX_ROW;
374 term->tl_cursor_visible = TRUE;
375 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
376 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100377#ifdef FEAT_GUI
378 term->tl_system = (flags & TERM_START_SYSTEM);
379#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200380 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
381
382 vim_memset(&split_ea, 0, sizeof(split_ea));
383 if (opt->jo_curwin)
384 {
385 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100386 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200387 {
388 no_write_message();
389 vim_free(term);
390 return NULL;
391 }
392 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100393 ECMD_HIDE
394 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
395 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200396 {
397 vim_free(term);
398 return NULL;
399 }
400 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100401 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200402 {
403 buf_T *buf;
404
405 /* Create a new buffer without a window. Make it the current buffer for
406 * a moment to be able to do the initialisations. */
407 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
408 BLN_NEW | BLN_LISTED);
409 if (buf == NULL || ml_open(buf) == FAIL)
410 {
411 vim_free(term);
412 return NULL;
413 }
414 old_curbuf = curbuf;
415 --curbuf->b_nwindows;
416 curbuf = buf;
417 curwin->w_buffer = buf;
418 ++curbuf->b_nwindows;
419 }
420 else
421 {
422 /* Open a new window or tab. */
423 split_ea.cmdidx = CMD_new;
424 split_ea.cmd = (char_u *)"new";
425 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100426 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200427 {
428 split_ea.line2 = opt->jo_term_rows;
429 split_ea.addr_count = 1;
430 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100431 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200432 {
433 split_ea.line2 = opt->jo_term_cols;
434 split_ea.addr_count = 1;
435 }
436
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100437 if (vertical)
438 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200439 ex_splitview(&split_ea);
440 if (curwin == old_curwin)
441 {
442 /* split failed */
443 vim_free(term);
444 return NULL;
445 }
446 }
447 term->tl_buffer = curbuf;
448 curbuf->b_term = term;
449
450 if (!opt->jo_hidden)
451 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100452 /* Only one size was taken care of with :new, do the other one. With
453 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100454 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200455 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100456 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200457 win_setwidth(opt->jo_term_cols);
458 }
459
460 /* Link the new terminal in the list of active terminals. */
461 term->tl_next = first_term;
462 first_term = term;
463
464 if (opt->jo_term_name != NULL)
465 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100466 else if (argv != NULL)
467 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200468 else
469 {
470 int i;
471 size_t len;
472 char_u *cmd, *p;
473
474 if (argvar->v_type == VAR_STRING)
475 {
476 cmd = argvar->vval.v_string;
477 if (cmd == NULL)
478 cmd = (char_u *)"";
479 else if (STRCMP(cmd, "NONE") == 0)
480 cmd = (char_u *)"pty";
481 }
482 else if (argvar->v_type != VAR_LIST
483 || argvar->vval.v_list == NULL
484 || argvar->vval.v_list->lv_len < 1
485 || (cmd = get_tv_string_chk(
486 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
487 cmd = (char_u*)"";
488
489 len = STRLEN(cmd) + 10;
490 p = alloc((int)len);
491
492 for (i = 0; p != NULL; ++i)
493 {
494 /* Prepend a ! to the command name to avoid the buffer name equals
495 * the executable, otherwise ":w!" would overwrite it. */
496 if (i == 0)
497 vim_snprintf((char *)p, len, "!%s", cmd);
498 else
499 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
500 if (buflist_findname(p) == NULL)
501 {
502 vim_free(curbuf->b_ffname);
503 curbuf->b_ffname = p;
504 break;
505 }
506 }
507 }
508 curbuf->b_fname = curbuf->b_ffname;
509
510 if (opt->jo_term_opencmd != NULL)
511 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
512
513 if (opt->jo_eof_chars != NULL)
514 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
515
516 set_string_option_direct((char_u *)"buftype", -1,
517 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
518
519 /* Mark the buffer as not modifiable. It can only be made modifiable after
520 * the job finished. */
521 curbuf->b_p_ma = FALSE;
522
523 set_term_and_win_size(term);
524 setup_job_options(opt, term->tl_rows, term->tl_cols);
525
Bram Moolenaar13568252018-03-16 20:46:58 +0100526 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100527 return curbuf;
528
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100529#if defined(FEAT_SESSION)
530 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100531 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100532 {
533 term->tl_command = vim_strsave((char_u *)"NONE");
534 }
535 else if (argvar->v_type == VAR_STRING)
536 {
537 char_u *cmd = argvar->vval.v_string;
538
539 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
540 term->tl_command = vim_strsave(cmd);
541 }
542 else if (argvar->v_type == VAR_LIST
543 && argvar->vval.v_list != NULL
544 && argvar->vval.v_list->lv_len > 0)
545 {
546 garray_T ga;
547 listitem_T *item;
548
549 ga_init2(&ga, 1, 100);
550 for (item = argvar->vval.v_list->lv_first;
551 item != NULL; item = item->li_next)
552 {
553 char_u *s = get_tv_string_chk(&item->li_tv);
554 char_u *p;
555
556 if (s == NULL)
557 break;
558 p = vim_strsave_fnameescape(s, FALSE);
559 if (p == NULL)
560 break;
561 ga_concat(&ga, p);
562 vim_free(p);
563 ga_append(&ga, ' ');
564 }
565 if (item == NULL)
566 {
567 ga_append(&ga, NUL);
568 term->tl_command = ga.ga_data;
569 }
570 else
571 ga_clear(&ga);
572 }
573#endif
574
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100575 if (opt->jo_term_kill != NULL)
576 {
577 char_u *p = skiptowhite(opt->jo_term_kill);
578
579 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
580 }
581
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200582 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100583 if (argv == NULL
584 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200585 && argvar->vval.v_string != NULL
586 && STRCMP(argvar->vval.v_string, "NONE") == 0)
587 res = create_pty_only(term, opt);
588 else
Bram Moolenaar13568252018-03-16 20:46:58 +0100589 res = term_and_job_init(term, argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200590
591 newbuf = curbuf;
592 if (res == OK)
593 {
594 /* Get and remember the size we ended up with. Update the pty. */
595 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
596 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100597#ifdef FEAT_GUI
598 if (term->tl_system)
599 {
600 /* display first line below typed command */
601 term->tl_toprow = msg_row + 1;
602 term->tl_dirty_row_end = 0;
603 }
604#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200605
606 /* Make sure we don't get stuck on sending keys to the job, it leads to
607 * a deadlock if the job is waiting for Vim to read. */
608 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
609
Bram Moolenaar13568252018-03-16 20:46:58 +0100610 if (old_curbuf == NULL)
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100611 {
612 ++curbuf->b_locked;
613 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
614 --curbuf->b_locked;
615 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100616 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200617 {
618 --curbuf->b_nwindows;
619 curbuf = old_curbuf;
620 curwin->w_buffer = curbuf;
621 ++curbuf->b_nwindows;
622 }
623 }
624 else
625 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100626 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200627 return NULL;
628 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100629
Bram Moolenaar13568252018-03-16 20:46:58 +0100630 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200631 return newbuf;
632}
633
634/*
635 * ":terminal": open a terminal window and execute a job in it.
636 */
637 void
638ex_terminal(exarg_T *eap)
639{
640 typval_T argvar[2];
641 jobopt_T opt;
642 char_u *cmd;
643 char_u *tofree = NULL;
644
645 init_job_options(&opt);
646
647 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100648 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200649 {
650 char_u *p, *ep;
651
652 cmd += 2;
653 p = skiptowhite(cmd);
654 ep = vim_strchr(cmd, '=');
655 if (ep != NULL && ep < p)
656 p = ep;
657
658 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
659 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100660 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
661 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200662 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
663 opt.jo_term_finish = 'o';
664 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
665 opt.jo_curwin = 1;
666 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
667 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100668 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
669 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100670 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
671 && ep != NULL)
672 {
673 opt.jo_set2 |= JO2_TERM_KILL;
674 opt.jo_term_kill = ep + 1;
675 p = skiptowhite(cmd);
676 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200677 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
678 && ep != NULL && isdigit(ep[1]))
679 {
680 opt.jo_set2 |= JO2_TERM_ROWS;
681 opt.jo_term_rows = atoi((char *)ep + 1);
682 p = skiptowhite(cmd);
683 }
684 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
685 && ep != NULL && isdigit(ep[1]))
686 {
687 opt.jo_set2 |= JO2_TERM_COLS;
688 opt.jo_term_cols = atoi((char *)ep + 1);
689 p = skiptowhite(cmd);
690 }
691 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
692 && ep != NULL)
693 {
694 char_u *buf = NULL;
695 char_u *keys;
696
697 p = skiptowhite(cmd);
698 *p = NUL;
699 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
700 opt.jo_set2 |= JO2_EOF_CHARS;
701 opt.jo_eof_chars = vim_strsave(keys);
702 vim_free(buf);
703 *p = ' ';
704 }
705 else
706 {
707 if (*p)
708 *p = NUL;
709 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100710 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 }
712 cmd = skipwhite(p);
713 }
714 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100715 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200716 /* Make a copy of 'shell', an autocommand may change the option. */
717 tofree = cmd = vim_strsave(p_sh);
718
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100719 /* default to close when the shell exits */
720 if (opt.jo_term_finish == NUL)
721 opt.jo_term_finish = 'c';
722 }
723
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724 if (eap->addr_count > 0)
725 {
726 /* Write lines from current buffer to the job. */
727 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
728 opt.jo_io[PART_IN] = JIO_BUFFER;
729 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
730 opt.jo_in_top = eap->line1;
731 opt.jo_in_bot = eap->line2;
732 }
733
734 argvar[0].v_type = VAR_STRING;
735 argvar[0].vval.v_string = cmd;
736 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100737 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100739
740theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200741 vim_free(opt.jo_eof_chars);
742}
743
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100744#if defined(FEAT_SESSION) || defined(PROTO)
745/*
746 * Write a :terminal command to the session file to restore the terminal in
747 * window "wp".
748 * Return FAIL if writing fails.
749 */
750 int
751term_write_session(FILE *fd, win_T *wp)
752{
753 term_T *term = wp->w_buffer->b_term;
754
755 /* Create the terminal and run the command. This is not without
756 * risk, but let's assume the user only creates a session when this
757 * will be OK. */
758 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
759 term->tl_cols, term->tl_rows) < 0)
760 return FAIL;
761 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
762 return FAIL;
763
764 return put_eol(fd);
765}
766
767/*
768 * Return TRUE if "buf" has a terminal that should be restored.
769 */
770 int
771term_should_restore(buf_T *buf)
772{
773 term_T *term = buf->b_term;
774
775 return term != NULL && (term->tl_command == NULL
776 || STRCMP(term->tl_command, "NONE") != 0);
777}
778#endif
779
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200780/*
781 * Free the scrollback buffer for "term".
782 */
783 static void
784free_scrollback(term_T *term)
785{
786 int i;
787
788 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
789 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
790 ga_clear(&term->tl_scrollback);
791}
792
793/*
794 * Free a terminal and everything it refers to.
795 * Kills the job if there is one.
796 * Called when wiping out a buffer.
797 */
798 void
799free_terminal(buf_T *buf)
800{
801 term_T *term = buf->b_term;
802 term_T *tp;
803
804 if (term == NULL)
805 return;
806 if (first_term == term)
807 first_term = term->tl_next;
808 else
809 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
810 if (tp->tl_next == term)
811 {
812 tp->tl_next = term->tl_next;
813 break;
814 }
815
816 if (term->tl_job != NULL)
817 {
818 if (term->tl_job->jv_status != JOB_ENDED
819 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100820 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 job_stop(term->tl_job, NULL, "kill");
822 job_unref(term->tl_job);
823 }
824
825 free_scrollback(term);
826
827 term_free_vterm(term);
828 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100829#ifdef FEAT_SESSION
830 vim_free(term->tl_command);
831#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100832 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 vim_free(term->tl_status_text);
834 vim_free(term->tl_opencmd);
835 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100836 if (desired_cursor_color == term->tl_cursor_color)
837 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 vim_free(term->tl_cursor_color);
839 vim_free(term);
840 buf->b_term = NULL;
841 if (in_terminal_loop == term)
842 in_terminal_loop = NULL;
843}
844
845/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100846 * Get the part that is connected to the tty. Normally this is PART_IN, but
847 * when writing buffer lines to the job it can be another. This makes it
848 * possible to do "1,5term vim -".
849 */
850 static ch_part_T
851get_tty_part(term_T *term)
852{
853#ifdef UNIX
854 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
855 int i;
856
857 for (i = 0; i < 3; ++i)
858 {
859 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
860
861 if (isatty(fd))
862 return parts[i];
863 }
864#endif
865 return PART_IN;
866}
867
868/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200869 * Write job output "msg[len]" to the vterm.
870 */
871 static void
872term_write_job_output(term_T *term, char_u *msg, size_t len)
873{
874 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100875 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200876
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100877 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200878
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100879 /* flush vterm buffer when vterm responded to control sequence */
880 if (prevlen != vterm_output_get_buffer_current(vterm))
881 {
882 char buf[KEY_BUF_LEN];
883 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
884
885 if (curlen > 0)
886 channel_send(term->tl_job->jv_channel, get_tty_part(term),
887 (char_u *)buf, (int)curlen, NULL);
888 }
889
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200890 /* this invokes the damage callbacks */
891 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
892}
893
894 static void
895update_cursor(term_T *term, int redraw)
896{
897 if (term->tl_normal_mode)
898 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100899#ifdef FEAT_GUI
900 if (term->tl_system)
901 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
902 term->tl_cursor_pos.col);
903 else
904#endif
905 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200906 if (redraw)
907 {
908 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
909 cursor_on();
910 out_flush();
911#ifdef FEAT_GUI
912 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100913 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200914 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100915 gui_mch_flush();
916 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200917#endif
918 }
919}
920
921/*
922 * Invoked when "msg" output from a job was received. Write it to the terminal
923 * of "buffer".
924 */
925 void
926write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
927{
928 size_t len = STRLEN(msg);
929 term_T *term = buffer->b_term;
930
931 if (term->tl_vterm == NULL)
932 {
933 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
934 return;
935 }
936 ch_log(channel, "writing %d bytes to terminal", (int)len);
937 term_write_job_output(term, msg, len);
938
Bram Moolenaar13568252018-03-16 20:46:58 +0100939#ifdef FEAT_GUI
940 if (term->tl_system)
941 {
942 /* show system output, scrolling up the screen as needed */
943 update_system_term(term);
944 update_cursor(term, TRUE);
945 }
946 else
947#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200948 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
949 * contents, thus no screen update is needed. */
950 if (!term->tl_normal_mode)
951 {
952 /* TODO: only update once in a while. */
953 ch_log(term->tl_job->jv_channel, "updating screen");
954 if (buffer == curbuf)
955 {
956 update_screen(0);
957 update_cursor(term, TRUE);
958 }
959 else
960 redraw_after_callback(TRUE);
961 }
962}
963
964/*
965 * Send a mouse position and click to the vterm
966 */
967 static int
968term_send_mouse(VTerm *vterm, int button, int pressed)
969{
970 VTermModifier mod = VTERM_MOD_NONE;
971
972 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200973 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100974 if (button != 0)
975 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200976 return TRUE;
977}
978
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100979static int enter_mouse_col = -1;
980static int enter_mouse_row = -1;
981
982/*
983 * Handle a mouse click, drag or release.
984 * Return TRUE when a mouse event is sent to the terminal.
985 */
986 static int
987term_mouse_click(VTerm *vterm, int key)
988{
989#if defined(FEAT_CLIPBOARD)
990 /* For modeless selection mouse drag and release events are ignored, unless
991 * they are preceded with a mouse down event */
992 static int ignore_drag_release = TRUE;
993 VTermMouseState mouse_state;
994
995 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
996 if (mouse_state.flags == 0)
997 {
998 /* Terminal is not using the mouse, use modeless selection. */
999 switch (key)
1000 {
1001 case K_LEFTDRAG:
1002 case K_LEFTRELEASE:
1003 case K_RIGHTDRAG:
1004 case K_RIGHTRELEASE:
1005 /* Ignore drag and release events when the button-down wasn't
1006 * seen before. */
1007 if (ignore_drag_release)
1008 {
1009 int save_mouse_col, save_mouse_row;
1010
1011 if (enter_mouse_col < 0)
1012 break;
1013
1014 /* mouse click in the window gave us focus, handle that
1015 * click now */
1016 save_mouse_col = mouse_col;
1017 save_mouse_row = mouse_row;
1018 mouse_col = enter_mouse_col;
1019 mouse_row = enter_mouse_row;
1020 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1021 mouse_col = save_mouse_col;
1022 mouse_row = save_mouse_row;
1023 }
1024 /* FALLTHROUGH */
1025 case K_LEFTMOUSE:
1026 case K_RIGHTMOUSE:
1027 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1028 ignore_drag_release = TRUE;
1029 else
1030 ignore_drag_release = FALSE;
1031 /* Should we call mouse_has() here? */
1032 if (clip_star.available)
1033 {
1034 int button, is_click, is_drag;
1035
1036 button = get_mouse_button(KEY2TERMCAP1(key),
1037 &is_click, &is_drag);
1038 if (mouse_model_popup() && button == MOUSE_LEFT
1039 && (mod_mask & MOD_MASK_SHIFT))
1040 {
1041 /* Translate shift-left to right button. */
1042 button = MOUSE_RIGHT;
1043 mod_mask &= ~MOD_MASK_SHIFT;
1044 }
1045 clip_modeless(button, is_click, is_drag);
1046 }
1047 break;
1048
1049 case K_MIDDLEMOUSE:
1050 if (clip_star.available)
1051 insert_reg('*', TRUE);
1052 break;
1053 }
1054 enter_mouse_col = -1;
1055 return FALSE;
1056 }
1057#endif
1058 enter_mouse_col = -1;
1059
1060 switch (key)
1061 {
1062 case K_LEFTMOUSE:
1063 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1064 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1065 case K_LEFTRELEASE:
1066 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1067 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1068 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1069 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1070 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1071 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1072 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1073 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1074 }
1075 return TRUE;
1076}
1077
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001078/*
1079 * Convert typed key "c" into bytes to send to the job.
1080 * Return the number of bytes in "buf".
1081 */
1082 static int
1083term_convert_key(term_T *term, int c, char *buf)
1084{
1085 VTerm *vterm = term->tl_vterm;
1086 VTermKey key = VTERM_KEY_NONE;
1087 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001088 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001089
1090 switch (c)
1091 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001092 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1093
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001094 /* don't use VTERM_KEY_BACKSPACE, it always
1095 * becomes 0x7f DEL */
1096 case K_BS: c = term_backspace_char; break;
1097
1098 case ESC: key = VTERM_KEY_ESCAPE; break;
1099 case K_DEL: key = VTERM_KEY_DEL; break;
1100 case K_DOWN: key = VTERM_KEY_DOWN; break;
1101 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1102 key = VTERM_KEY_DOWN; break;
1103 case K_END: key = VTERM_KEY_END; break;
1104 case K_S_END: mod = VTERM_MOD_SHIFT;
1105 key = VTERM_KEY_END; break;
1106 case K_C_END: mod = VTERM_MOD_CTRL;
1107 key = VTERM_KEY_END; break;
1108 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1109 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1110 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1111 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1112 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1113 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1114 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1115 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1116 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1117 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1118 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1119 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1120 case K_HOME: key = VTERM_KEY_HOME; break;
1121 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1122 key = VTERM_KEY_HOME; break;
1123 case K_C_HOME: mod = VTERM_MOD_CTRL;
1124 key = VTERM_KEY_HOME; break;
1125 case K_INS: key = VTERM_KEY_INS; break;
1126 case K_K0: key = VTERM_KEY_KP_0; break;
1127 case K_K1: key = VTERM_KEY_KP_1; break;
1128 case K_K2: key = VTERM_KEY_KP_2; break;
1129 case K_K3: key = VTERM_KEY_KP_3; break;
1130 case K_K4: key = VTERM_KEY_KP_4; break;
1131 case K_K5: key = VTERM_KEY_KP_5; break;
1132 case K_K6: key = VTERM_KEY_KP_6; break;
1133 case K_K7: key = VTERM_KEY_KP_7; break;
1134 case K_K8: key = VTERM_KEY_KP_8; break;
1135 case K_K9: key = VTERM_KEY_KP_9; break;
1136 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1137 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1138 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1139 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1140 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1141 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1142 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1143 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1144 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1145 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1146 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1147 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1148 case K_LEFT: key = VTERM_KEY_LEFT; break;
1149 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1150 key = VTERM_KEY_LEFT; break;
1151 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1152 key = VTERM_KEY_LEFT; break;
1153 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1154 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1155 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1156 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1157 key = VTERM_KEY_RIGHT; break;
1158 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1159 key = VTERM_KEY_RIGHT; break;
1160 case K_UP: key = VTERM_KEY_UP; break;
1161 case K_S_UP: mod = VTERM_MOD_SHIFT;
1162 key = VTERM_KEY_UP; break;
1163 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001164 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1165 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001166
Bram Moolenaara42ad572017-11-16 13:08:04 +01001167 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1168 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001169 case K_MOUSELEFT: /* TODO */ return 0;
1170 case K_MOUSERIGHT: /* TODO */ return 0;
1171
1172 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001173 case K_LEFTMOUSE_NM:
1174 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001175 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001176 case K_LEFTRELEASE_NM:
1177 case K_MOUSEMOVE:
1178 case K_MIDDLEMOUSE:
1179 case K_MIDDLEDRAG:
1180 case K_MIDDLERELEASE:
1181 case K_RIGHTMOUSE:
1182 case K_RIGHTDRAG:
1183 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1184 return 0;
1185 other = TRUE;
1186 break;
1187
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001188 case K_X1MOUSE: /* TODO */ return 0;
1189 case K_X1DRAG: /* TODO */ return 0;
1190 case K_X1RELEASE: /* TODO */ return 0;
1191 case K_X2MOUSE: /* TODO */ return 0;
1192 case K_X2DRAG: /* TODO */ return 0;
1193 case K_X2RELEASE: /* TODO */ return 0;
1194
1195 case K_IGNORE: return 0;
1196 case K_NOP: return 0;
1197 case K_UNDO: return 0;
1198 case K_HELP: return 0;
1199 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1200 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1201 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1202 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1203 case K_SELECT: return 0;
1204#ifdef FEAT_GUI
1205 case K_VER_SCROLLBAR: return 0;
1206 case K_HOR_SCROLLBAR: return 0;
1207#endif
1208#ifdef FEAT_GUI_TABLINE
1209 case K_TABLINE: return 0;
1210 case K_TABMENU: return 0;
1211#endif
1212#ifdef FEAT_NETBEANS_INTG
1213 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1214#endif
1215#ifdef FEAT_DND
1216 case K_DROP: return 0;
1217#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001218 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001219 case K_PS: vterm_keyboard_start_paste(vterm);
1220 other = TRUE;
1221 break;
1222 case K_PE: vterm_keyboard_end_paste(vterm);
1223 other = TRUE;
1224 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001225 }
1226
1227 /*
1228 * Convert special keys to vterm keys:
1229 * - Write keys to vterm: vterm_keyboard_key()
1230 * - Write output to channel.
1231 * TODO: use mod_mask
1232 */
1233 if (key != VTERM_KEY_NONE)
1234 /* Special key, let vterm convert it. */
1235 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001236 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001237 /* Normal character, let vterm convert it. */
1238 vterm_keyboard_unichar(vterm, c, mod);
1239
1240 /* Read back the converted escape sequence. */
1241 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1242}
1243
1244/*
1245 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001246 * If "check_job_status" is TRUE update the job status.
1247 */
1248 static int
1249term_job_running_check(term_T *term, int check_job_status)
1250{
1251 /* Also consider the job finished when the channel is closed, to avoid a
1252 * race condition when updating the title. */
1253 if (term != NULL
1254 && term->tl_job != NULL
1255 && channel_is_open(term->tl_job->jv_channel))
1256 {
1257 if (check_job_status)
1258 job_status(term->tl_job);
1259 return (term->tl_job->jv_status == JOB_STARTED
1260 || term->tl_job->jv_channel->ch_keep_open);
1261 }
1262 return FALSE;
1263}
1264
1265/*
1266 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001267 */
1268 int
1269term_job_running(term_T *term)
1270{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001271 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001272}
1273
1274/*
1275 * Return TRUE if "term" has an active channel and used ":term NONE".
1276 */
1277 int
1278term_none_open(term_T *term)
1279{
1280 /* Also consider the job finished when the channel is closed, to avoid a
1281 * race condition when updating the title. */
1282 return term != NULL
1283 && term->tl_job != NULL
1284 && channel_is_open(term->tl_job->jv_channel)
1285 && term->tl_job->jv_channel->ch_keep_open;
1286}
1287
1288/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001289 * Used when exiting: kill the job in "buf" if so desired.
1290 * Return OK when the job finished.
1291 * Return FAIL when the job is still running.
1292 */
1293 int
1294term_try_stop_job(buf_T *buf)
1295{
1296 int count;
1297 char *how = (char *)buf->b_term->tl_kill;
1298
1299#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1300 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1301 {
1302 char_u buff[DIALOG_MSG_SIZE];
1303 int ret;
1304
1305 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1306 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1307 if (ret == VIM_YES)
1308 how = "kill";
1309 else if (ret == VIM_CANCEL)
1310 return FAIL;
1311 }
1312#endif
1313 if (how == NULL || *how == NUL)
1314 return FAIL;
1315
1316 job_stop(buf->b_term->tl_job, NULL, how);
1317
1318 /* wait for up to a second for the job to die */
1319 for (count = 0; count < 100; ++count)
1320 {
1321 /* buffer, terminal and job may be cleaned up while waiting */
1322 if (!buf_valid(buf)
1323 || buf->b_term == NULL
1324 || buf->b_term->tl_job == NULL)
1325 return OK;
1326
1327 /* call job_status() to update jv_status */
1328 job_status(buf->b_term->tl_job);
1329 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1330 return OK;
1331 ui_delay(10L, FALSE);
1332 mch_check_messages();
1333 parse_queued_messages();
1334 }
1335 return FAIL;
1336}
1337
1338/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001339 * Add the last line of the scrollback buffer to the buffer in the window.
1340 */
1341 static void
1342add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1343{
1344 buf_T *buf = term->tl_buffer;
1345 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1346 linenr_T lnum = buf->b_ml.ml_line_count;
1347
1348#ifdef WIN3264
1349 if (!enc_utf8 && enc_codepage > 0)
1350 {
1351 WCHAR *ret = NULL;
1352 int length = 0;
1353
1354 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1355 &ret, &length);
1356 if (ret != NULL)
1357 {
1358 WideCharToMultiByte_alloc(enc_codepage, 0,
1359 ret, length, (char **)&text, &len, 0, 0);
1360 vim_free(ret);
1361 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1362 vim_free(text);
1363 }
1364 }
1365 else
1366#endif
1367 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1368 if (empty)
1369 {
1370 /* Delete the empty line that was in the empty buffer. */
1371 curbuf = buf;
1372 ml_delete(1, FALSE);
1373 curbuf = curwin->w_buffer;
1374 }
1375}
1376
1377 static void
1378cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1379{
1380 attr->width = cell->width;
1381 attr->attrs = cell->attrs;
1382 attr->fg = cell->fg;
1383 attr->bg = cell->bg;
1384}
1385
1386 static int
1387equal_celattr(cellattr_T *a, cellattr_T *b)
1388{
1389 /* Comparing the colors should be sufficient. */
1390 return a->fg.red == b->fg.red
1391 && a->fg.green == b->fg.green
1392 && a->fg.blue == b->fg.blue
1393 && a->bg.red == b->bg.red
1394 && a->bg.green == b->bg.green
1395 && a->bg.blue == b->bg.blue;
1396}
1397
Bram Moolenaard96ff162018-02-18 22:13:29 +01001398/*
1399 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1400 * line at this position. Otherwise at the end.
1401 */
1402 static int
1403add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1404{
1405 if (ga_grow(&term->tl_scrollback, 1) == OK)
1406 {
1407 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1408 + term->tl_scrollback.ga_len;
1409
1410 if (lnum > 0)
1411 {
1412 int i;
1413
1414 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1415 {
1416 *line = *(line - 1);
1417 --line;
1418 }
1419 }
1420 line->sb_cols = 0;
1421 line->sb_cells = NULL;
1422 line->sb_fill_attr = *fill_attr;
1423 ++term->tl_scrollback.ga_len;
1424 return OK;
1425 }
1426 return FALSE;
1427}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001428
1429/*
1430 * Add the current lines of the terminal to scrollback and to the buffer.
1431 * Called after the job has ended and when switching to Terminal-Normal mode.
1432 */
1433 static void
1434move_terminal_to_buffer(term_T *term)
1435{
1436 win_T *wp;
1437 int len;
1438 int lines_skipped = 0;
1439 VTermPos pos;
1440 VTermScreenCell cell;
1441 cellattr_T fill_attr, new_fill_attr;
1442 cellattr_T *p;
1443 VTermScreen *screen;
1444
1445 if (term->tl_vterm == NULL)
1446 return;
1447 screen = vterm_obtain_screen(term->tl_vterm);
1448 fill_attr = new_fill_attr = term->tl_default_color;
1449
1450 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1451 {
1452 len = 0;
1453 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1454 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1455 && cell.chars[0] != NUL)
1456 {
1457 len = pos.col + 1;
1458 new_fill_attr = term->tl_default_color;
1459 }
1460 else
1461 /* Assume the last attr is the filler attr. */
1462 cell2cellattr(&cell, &new_fill_attr);
1463
1464 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1465 ++lines_skipped;
1466 else
1467 {
1468 while (lines_skipped > 0)
1469 {
1470 /* Line was skipped, add an empty line. */
1471 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001472 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001473 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001474 }
1475
1476 if (len == 0)
1477 p = NULL;
1478 else
1479 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1480 if ((p != NULL || len == 0)
1481 && ga_grow(&term->tl_scrollback, 1) == OK)
1482 {
1483 garray_T ga;
1484 int width;
1485 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1486 + term->tl_scrollback.ga_len;
1487
1488 ga_init2(&ga, 1, 100);
1489 for (pos.col = 0; pos.col < len; pos.col += width)
1490 {
1491 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1492 {
1493 width = 1;
1494 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1495 if (ga_grow(&ga, 1) == OK)
1496 ga.ga_len += utf_char2bytes(' ',
1497 (char_u *)ga.ga_data + ga.ga_len);
1498 }
1499 else
1500 {
1501 width = cell.width;
1502
1503 cell2cellattr(&cell, &p[pos.col]);
1504
1505 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1506 {
1507 int i;
1508 int c;
1509
1510 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1511 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1512 (char_u *)ga.ga_data + ga.ga_len);
1513 }
1514 }
1515 }
1516 line->sb_cols = len;
1517 line->sb_cells = p;
1518 line->sb_fill_attr = new_fill_attr;
1519 fill_attr = new_fill_attr;
1520 ++term->tl_scrollback.ga_len;
1521
1522 if (ga_grow(&ga, 1) == FAIL)
1523 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1524 else
1525 {
1526 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1527 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1528 }
1529 ga_clear(&ga);
1530 }
1531 else
1532 vim_free(p);
1533 }
1534 }
1535
1536 /* Obtain the current background color. */
1537 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1538 &term->tl_default_color.fg, &term->tl_default_color.bg);
1539
1540 FOR_ALL_WINDOWS(wp)
1541 {
1542 if (wp->w_buffer == term->tl_buffer)
1543 {
1544 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1545 wp->w_cursor.col = 0;
1546 wp->w_valid = 0;
1547 if (wp->w_cursor.lnum >= wp->w_height)
1548 {
1549 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1550
1551 if (wp->w_topline < min_topline)
1552 wp->w_topline = min_topline;
1553 }
1554 redraw_win_later(wp, NOT_VALID);
1555 }
1556 }
1557}
1558
1559 static void
1560set_terminal_mode(term_T *term, int normal_mode)
1561{
1562 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001563 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001564 if (term->tl_buffer == curbuf)
1565 maketitle();
1566}
1567
1568/*
1569 * Called after the job if finished and Terminal mode is not active:
1570 * Move the vterm contents into the scrollback buffer and free the vterm.
1571 */
1572 static void
1573cleanup_vterm(term_T *term)
1574{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001575 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576 move_terminal_to_buffer(term);
1577 term_free_vterm(term);
1578 set_terminal_mode(term, FALSE);
1579}
1580
1581/*
1582 * Switch from Terminal-Job mode to Terminal-Normal mode.
1583 * Suspends updating the terminal window.
1584 */
1585 static void
1586term_enter_normal_mode(void)
1587{
1588 term_T *term = curbuf->b_term;
1589
1590 /* Append the current terminal contents to the buffer. */
1591 move_terminal_to_buffer(term);
1592
1593 set_terminal_mode(term, TRUE);
1594
1595 /* Move the window cursor to the position of the cursor in the
1596 * terminal. */
1597 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1598 + term->tl_cursor_pos.row + 1;
1599 check_cursor();
1600 coladvance(term->tl_cursor_pos.col);
1601
1602 /* Display the same lines as in the terminal. */
1603 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1604}
1605
1606/*
1607 * Returns TRUE if the current window contains a terminal and we are in
1608 * Terminal-Normal mode.
1609 */
1610 int
1611term_in_normal_mode(void)
1612{
1613 term_T *term = curbuf->b_term;
1614
1615 return term != NULL && term->tl_normal_mode;
1616}
1617
1618/*
1619 * Switch from Terminal-Normal mode to Terminal-Job mode.
1620 * Restores updating the terminal window.
1621 */
1622 void
1623term_enter_job_mode()
1624{
1625 term_T *term = curbuf->b_term;
1626 sb_line_T *line;
1627 garray_T *gap;
1628
1629 /* Remove the terminal contents from the scrollback and the buffer. */
1630 gap = &term->tl_scrollback;
1631 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1632 && gap->ga_len > 0)
1633 {
1634 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1635 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1636 vim_free(line->sb_cells);
1637 --gap->ga_len;
1638 }
1639 check_cursor();
1640
1641 set_terminal_mode(term, FALSE);
1642
1643 if (term->tl_channel_closed)
1644 cleanup_vterm(term);
1645 redraw_buf_and_status_later(curbuf, NOT_VALID);
1646}
1647
1648/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001649 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 * Note: while waiting a terminal may be closed and freed if the channel is
1651 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001652 */
1653 static int
1654term_vgetc()
1655{
1656 int c;
1657 int save_State = State;
1658
1659 State = TERMINAL;
1660 got_int = FALSE;
1661#ifdef WIN3264
1662 ctrl_break_was_pressed = FALSE;
1663#endif
1664 c = vgetc();
1665 got_int = FALSE;
1666 State = save_State;
1667 return c;
1668}
1669
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001670static int mouse_was_outside = FALSE;
1671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001672/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673 * Send keys to terminal.
1674 * Return FAIL when the key needs to be handled in Normal mode.
1675 * Return OK when the key was dropped or sent to the terminal.
1676 */
1677 int
1678send_keys_to_term(term_T *term, int c, int typed)
1679{
1680 char msg[KEY_BUF_LEN];
1681 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001682 int dragging_outside = FALSE;
1683
1684 /* Catch keys that need to be handled as in Normal mode. */
1685 switch (c)
1686 {
1687 case NUL:
1688 case K_ZERO:
1689 if (typed)
1690 stuffcharReadbuff(c);
1691 return FAIL;
1692
1693 case K_IGNORE:
1694 return FAIL;
1695
1696 case K_LEFTDRAG:
1697 case K_MIDDLEDRAG:
1698 case K_RIGHTDRAG:
1699 case K_X1DRAG:
1700 case K_X2DRAG:
1701 dragging_outside = mouse_was_outside;
1702 /* FALLTHROUGH */
1703 case K_LEFTMOUSE:
1704 case K_LEFTMOUSE_NM:
1705 case K_LEFTRELEASE:
1706 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001707 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001708 case K_MIDDLEMOUSE:
1709 case K_MIDDLERELEASE:
1710 case K_RIGHTMOUSE:
1711 case K_RIGHTRELEASE:
1712 case K_X1MOUSE:
1713 case K_X1RELEASE:
1714 case K_X2MOUSE:
1715 case K_X2RELEASE:
1716
1717 case K_MOUSEUP:
1718 case K_MOUSEDOWN:
1719 case K_MOUSELEFT:
1720 case K_MOUSERIGHT:
1721 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001722 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001723 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001724 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001725 || dragging_outside)
1726 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001727 /* click or scroll outside the current window or on status line
1728 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001729 if (typed)
1730 {
1731 stuffcharReadbuff(c);
1732 mouse_was_outside = TRUE;
1733 }
1734 return FAIL;
1735 }
1736 }
1737 if (typed)
1738 mouse_was_outside = FALSE;
1739
1740 /* Convert the typed key to a sequence of bytes for the job. */
1741 len = term_convert_key(term, c, msg);
1742 if (len > 0)
1743 /* TODO: if FAIL is returned, stop? */
1744 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1745 (char_u *)msg, (int)len, NULL);
1746
1747 return OK;
1748}
1749
1750 static void
1751position_cursor(win_T *wp, VTermPos *pos)
1752{
1753 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1754 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1755 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1756}
1757
1758/*
1759 * Handle CTRL-W "": send register contents to the job.
1760 */
1761 static void
1762term_paste_register(int prev_c UNUSED)
1763{
1764 int c;
1765 list_T *l;
1766 listitem_T *item;
1767 long reglen = 0;
1768 int type;
1769
1770#ifdef FEAT_CMDL_INFO
1771 if (add_to_showcmd(prev_c))
1772 if (add_to_showcmd('"'))
1773 out_flush();
1774#endif
1775 c = term_vgetc();
1776#ifdef FEAT_CMDL_INFO
1777 clear_showcmd();
1778#endif
1779 if (!term_use_loop())
1780 /* job finished while waiting for a character */
1781 return;
1782
1783 /* CTRL-W "= prompt for expression to evaluate. */
1784 if (c == '=' && get_expr_register() != '=')
1785 return;
1786 if (!term_use_loop())
1787 /* job finished while waiting for a character */
1788 return;
1789
1790 l = (list_T *)get_reg_contents(c, GREG_LIST);
1791 if (l != NULL)
1792 {
1793 type = get_reg_type(c, &reglen);
1794 for (item = l->lv_first; item != NULL; item = item->li_next)
1795 {
1796 char_u *s = get_tv_string(&item->li_tv);
1797#ifdef WIN3264
1798 char_u *tmp = s;
1799
1800 if (!enc_utf8 && enc_codepage > 0)
1801 {
1802 WCHAR *ret = NULL;
1803 int length = 0;
1804
1805 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1806 (int)STRLEN(s), &ret, &length);
1807 if (ret != NULL)
1808 {
1809 WideCharToMultiByte_alloc(CP_UTF8, 0,
1810 ret, length, (char **)&s, &length, 0, 0);
1811 vim_free(ret);
1812 }
1813 }
1814#endif
1815 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1816 s, (int)STRLEN(s), NULL);
1817#ifdef WIN3264
1818 if (tmp != s)
1819 vim_free(s);
1820#endif
1821
1822 if (item->li_next != NULL || type == MLINE)
1823 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1824 (char_u *)"\r", 1, NULL);
1825 }
1826 list_free(l);
1827 }
1828}
1829
1830#if defined(FEAT_GUI) || defined(PROTO)
1831/*
1832 * Return TRUE when the cursor of the terminal should be displayed.
1833 */
1834 int
1835terminal_is_active()
1836{
1837 return in_terminal_loop != NULL;
1838}
1839
1840 cursorentry_T *
1841term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1842{
1843 term_T *term = in_terminal_loop;
1844 static cursorentry_T entry;
1845
1846 vim_memset(&entry, 0, sizeof(entry));
1847 entry.shape = entry.mshape =
1848 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1849 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1850 SHAPE_BLOCK;
1851 entry.percentage = 20;
1852 if (term->tl_cursor_blink)
1853 {
1854 entry.blinkwait = 700;
1855 entry.blinkon = 400;
1856 entry.blinkoff = 250;
1857 }
1858 *fg = gui.back_pixel;
1859 if (term->tl_cursor_color == NULL)
1860 *bg = gui.norm_pixel;
1861 else
1862 *bg = color_name2handle(term->tl_cursor_color);
1863 entry.name = "n";
1864 entry.used_for = SHAPE_CURSOR;
1865
1866 return &entry;
1867}
1868#endif
1869
Bram Moolenaard317b382018-02-08 22:33:31 +01001870 static void
1871may_output_cursor_props(void)
1872{
1873 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1874 || last_set_cursor_shape != desired_cursor_shape
1875 || last_set_cursor_blink != desired_cursor_blink)
1876 {
1877 last_set_cursor_color = desired_cursor_color;
1878 last_set_cursor_shape = desired_cursor_shape;
1879 last_set_cursor_blink = desired_cursor_blink;
1880 term_cursor_color(desired_cursor_color);
1881 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1882 /* this will restore the initial cursor style, if possible */
1883 ui_cursor_shape_forced(TRUE);
1884 else
1885 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1886 }
1887}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001888
Bram Moolenaard317b382018-02-08 22:33:31 +01001889/*
1890 * Set the cursor color and shape, if not last set to these.
1891 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001892 static void
1893may_set_cursor_props(term_T *term)
1894{
1895#ifdef FEAT_GUI
1896 /* For the GUI the cursor properties are obtained with
1897 * term_get_cursor_shape(). */
1898 if (gui.in_use)
1899 return;
1900#endif
1901 if (in_terminal_loop == term)
1902 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001903 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001904 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001905 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001906 desired_cursor_color = (char_u *)"";
1907 desired_cursor_shape = term->tl_cursor_shape;
1908 desired_cursor_blink = term->tl_cursor_blink;
1909 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001910 }
1911}
1912
Bram Moolenaard317b382018-02-08 22:33:31 +01001913/*
1914 * Reset the desired cursor properties and restore them when needed.
1915 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001916 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001917prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001918{
1919#ifdef FEAT_GUI
1920 if (gui.in_use)
1921 return;
1922#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001923 desired_cursor_color = (char_u *)"";
1924 desired_cursor_shape = -1;
1925 desired_cursor_blink = -1;
1926 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001927}
1928
1929/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001930 * Returns TRUE if the current window contains a terminal and we are sending
1931 * keys to the job.
1932 * If "check_job_status" is TRUE update the job status.
1933 */
1934 static int
1935term_use_loop_check(int check_job_status)
1936{
1937 term_T *term = curbuf->b_term;
1938
1939 return term != NULL
1940 && !term->tl_normal_mode
1941 && term->tl_vterm != NULL
1942 && term_job_running_check(term, check_job_status);
1943}
1944
1945/*
1946 * Returns TRUE if the current window contains a terminal and we are sending
1947 * keys to the job.
1948 */
1949 int
1950term_use_loop(void)
1951{
1952 return term_use_loop_check(FALSE);
1953}
1954
1955/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001956 * Called when entering a window with the mouse. If this is a terminal window
1957 * we may want to change state.
1958 */
1959 void
1960term_win_entered()
1961{
1962 term_T *term = curbuf->b_term;
1963
1964 if (term != NULL)
1965 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001966 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001967 {
1968 reset_VIsual_and_resel();
1969 if (State & INSERT)
1970 stop_insert_mode = TRUE;
1971 }
1972 mouse_was_outside = FALSE;
1973 enter_mouse_col = mouse_col;
1974 enter_mouse_row = mouse_row;
1975 }
1976}
1977
1978/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001979 * Wait for input and send it to the job.
1980 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1981 * when there is no more typahead.
1982 * Return when the start of a CTRL-W command is typed or anything else that
1983 * should be handled as a Normal mode command.
1984 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1985 * the terminal was closed.
1986 */
1987 int
1988terminal_loop(int blocking)
1989{
1990 int c;
1991 int termkey = 0;
1992 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001993#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001994 int tty_fd = curbuf->b_term->tl_job->jv_channel
1995 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001996#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001997 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998
1999 /* Remember the terminal we are sending keys to. However, the terminal
2000 * might be closed while waiting for a character, e.g. typing "exit" in a
2001 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2002 * stored reference. */
2003 in_terminal_loop = curbuf->b_term;
2004
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002005 if (*curwin->w_p_twk != NUL)
2006 termkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002007 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2008 may_set_cursor_props(curbuf->b_term);
2009
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002010 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002012#ifdef FEAT_GUI
2013 if (!curbuf->b_term->tl_system)
2014#endif
2015 /* TODO: skip screen update when handling a sequence of keys. */
2016 /* Repeat redrawing in case a message is received while redrawing.
2017 */
2018 while (must_redraw != 0)
2019 if (update_screen(0) == FAIL)
2020 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002022 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023
2024 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002025 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002026 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002027 /* Job finished while waiting for a character. Push back the
2028 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002029 if (c != K_IGNORE)
2030 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002031 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002032 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002033 if (c == K_IGNORE)
2034 continue;
2035
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002036#ifdef UNIX
2037 /*
2038 * The shell or another program may change the tty settings. Getting
2039 * them for every typed character is a bit of overhead, but it's needed
2040 * for the first character typed, e.g. when Vim starts in a shell.
2041 */
2042 if (isatty(tty_fd))
2043 {
2044 ttyinfo_T info;
2045
2046 /* Get the current backspace character of the pty. */
2047 if (get_tty_info(tty_fd, &info) == OK)
2048 term_backspace_char = info.backspace;
2049 }
2050#endif
2051
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002052#ifdef WIN3264
2053 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2054 * Use CTRL-BREAK to kill the job. */
2055 if (ctrl_break_was_pressed)
2056 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2057#endif
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002058 /* Was either CTRL-W (termkey) or CTRL-\ pressed?
2059 * Not in a system terminal. */
2060 if ((c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
2061#ifdef FEAT_GUI
2062 && !curbuf->b_term->tl_system
2063#endif
2064 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002065 {
2066 int prev_c = c;
2067
2068#ifdef FEAT_CMDL_INFO
2069 if (add_to_showcmd(c))
2070 out_flush();
2071#endif
2072 c = term_vgetc();
2073#ifdef FEAT_CMDL_INFO
2074 clear_showcmd();
2075#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002076 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002077 /* job finished while waiting for a character */
2078 break;
2079
2080 if (prev_c == Ctrl_BSL)
2081 {
2082 if (c == Ctrl_N)
2083 {
2084 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2085 term_enter_normal_mode();
2086 ret = FAIL;
2087 goto theend;
2088 }
2089 /* Send both keys to the terminal. */
2090 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2091 }
2092 else if (c == Ctrl_C)
2093 {
2094 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
2095 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2096 }
2097 else if (termkey == 0 && c == '.')
2098 {
2099 /* "CTRL-W .": send CTRL-W to the job */
2100 c = Ctrl_W;
2101 }
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002102 else if (termkey == 0 && c == Ctrl_BSL)
2103 {
2104 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2105 c = Ctrl_BSL;
2106 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002107 else if (c == 'N')
2108 {
2109 /* CTRL-W N : go to Terminal-Normal mode. */
2110 term_enter_normal_mode();
2111 ret = FAIL;
2112 goto theend;
2113 }
2114 else if (c == '"')
2115 {
2116 term_paste_register(prev_c);
2117 continue;
2118 }
2119 else if (termkey == 0 || c != termkey)
2120 {
2121 stuffcharReadbuff(Ctrl_W);
2122 stuffcharReadbuff(c);
2123 ret = OK;
2124 goto theend;
2125 }
2126 }
2127# ifdef WIN3264
2128 if (!enc_utf8 && has_mbyte && c >= 0x80)
2129 {
2130 WCHAR wc;
2131 char_u mb[3];
2132
2133 mb[0] = (unsigned)c >> 8;
2134 mb[1] = c;
2135 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2136 c = wc;
2137 }
2138# endif
2139 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2140 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002141 if (c == K_MOUSEMOVE)
2142 /* We are sure to come back here, don't reset the cursor color
2143 * and shape to avoid flickering. */
2144 restore_cursor = FALSE;
2145
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002146 ret = OK;
2147 goto theend;
2148 }
2149 }
2150 ret = FAIL;
2151
2152theend:
2153 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002154 if (restore_cursor)
2155 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 return ret;
2157}
2158
2159/*
2160 * Called when a job has finished.
2161 * This updates the title and status, but does not close the vterm, because
2162 * there might still be pending output in the channel.
2163 */
2164 void
2165term_job_ended(job_T *job)
2166{
2167 term_T *term;
2168 int did_one = FALSE;
2169
2170 for (term = first_term; term != NULL; term = term->tl_next)
2171 if (term->tl_job == job)
2172 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002173 VIM_CLEAR(term->tl_title);
2174 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175 redraw_buf_and_status_later(term->tl_buffer, VALID);
2176 did_one = TRUE;
2177 }
2178 if (did_one)
2179 redraw_statuslines();
2180 if (curbuf->b_term != NULL)
2181 {
2182 if (curbuf->b_term->tl_job == job)
2183 maketitle();
2184 update_cursor(curbuf->b_term, TRUE);
2185 }
2186}
2187
2188 static void
2189may_toggle_cursor(term_T *term)
2190{
2191 if (in_terminal_loop == term)
2192 {
2193 if (term->tl_cursor_visible)
2194 cursor_on();
2195 else
2196 cursor_off();
2197 }
2198}
2199
2200/*
2201 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002202 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002203 */
2204 static int
2205color2index(VTermColor *color, int fg, int *boldp)
2206{
2207 int red = color->red;
2208 int blue = color->blue;
2209 int green = color->green;
2210
Bram Moolenaar46359e12017-11-29 22:33:38 +01002211 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002212 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002213 /* First 16 colors and default: use the ANSI index, because these
2214 * colors can be redefined. */
2215 if (t_colors >= 16)
2216 return color->ansi_index;
2217 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002218 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002219 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002220 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002221 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2222 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2223 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002224 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002225 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2226 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2227 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2228 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2229 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2230 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2231 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2232 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2233 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2234 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2235 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002236 }
2237 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002238
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002239 if (t_colors >= 256)
2240 {
2241 if (red == blue && red == green)
2242 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002243 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002244 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002245 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2246 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2247 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002248 int i;
2249
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002250 if (red < 5)
2251 return 17; /* 00/00/00 */
2252 if (red > 245) /* ff/ff/ff */
2253 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002254 for (i = 0; i < 23; ++i)
2255 if (red < cutoff[i])
2256 return i + 233;
2257 return 256;
2258 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002259 {
2260 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2261 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002263 /* 216-color cube */
2264 for (ri = 0; ri < 5; ++ri)
2265 if (red < cutoff[ri])
2266 break;
2267 for (gi = 0; gi < 5; ++gi)
2268 if (green < cutoff[gi])
2269 break;
2270 for (bi = 0; bi < 5; ++bi)
2271 if (blue < cutoff[bi])
2272 break;
2273 return 17 + ri * 36 + gi * 6 + bi;
2274 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 }
2276 return 0;
2277}
2278
2279/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002280 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002281 */
2282 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002283vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002284{
2285 int attr = 0;
2286
2287 if (cellattrs.bold)
2288 attr |= HL_BOLD;
2289 if (cellattrs.underline)
2290 attr |= HL_UNDERLINE;
2291 if (cellattrs.italic)
2292 attr |= HL_ITALIC;
2293 if (cellattrs.strike)
2294 attr |= HL_STRIKETHROUGH;
2295 if (cellattrs.reverse)
2296 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002297 return attr;
2298}
2299
2300/*
2301 * Store Vterm attributes in "cell" from highlight flags.
2302 */
2303 static void
2304hl2vtermAttr(int attr, cellattr_T *cell)
2305{
2306 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2307 if (attr & HL_BOLD)
2308 cell->attrs.bold = 1;
2309 if (attr & HL_UNDERLINE)
2310 cell->attrs.underline = 1;
2311 if (attr & HL_ITALIC)
2312 cell->attrs.italic = 1;
2313 if (attr & HL_STRIKETHROUGH)
2314 cell->attrs.strike = 1;
2315 if (attr & HL_INVERSE)
2316 cell->attrs.reverse = 1;
2317}
2318
2319/*
2320 * Convert the attributes of a vterm cell into an attribute index.
2321 */
2322 static int
2323cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2324{
2325 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002326
2327#ifdef FEAT_GUI
2328 if (gui.in_use)
2329 {
2330 guicolor_T fg, bg;
2331
2332 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2333 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2334 return get_gui_attr_idx(attr, fg, bg);
2335 }
2336 else
2337#endif
2338#ifdef FEAT_TERMGUICOLORS
2339 if (p_tgc)
2340 {
2341 guicolor_T fg, bg;
2342
2343 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2344 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2345
2346 return get_tgc_attr_idx(attr, fg, bg);
2347 }
2348 else
2349#endif
2350 {
2351 int bold = MAYBE;
2352 int fg = color2index(&cellfg, TRUE, &bold);
2353 int bg = color2index(&cellbg, FALSE, &bold);
2354
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002355 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002356 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002357 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002358 if (fg == 0 && term_default_cterm_fg >= 0)
2359 fg = term_default_cterm_fg + 1;
2360 if (bg == 0 && term_default_cterm_bg >= 0)
2361 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002362 }
2363
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002364 /* with 8 colors set the bold attribute to get a bright foreground */
2365 if (bold == TRUE)
2366 attr |= HL_BOLD;
2367 return get_cterm_attr_idx(attr, fg, bg);
2368 }
2369 return 0;
2370}
2371
2372 static int
2373handle_damage(VTermRect rect, void *user)
2374{
2375 term_T *term = (term_T *)user;
2376
2377 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2378 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2379 redraw_buf_later(term->tl_buffer, NOT_VALID);
2380 return 1;
2381}
2382
2383 static int
2384handle_moverect(VTermRect dest, VTermRect src, void *user)
2385{
2386 term_T *term = (term_T *)user;
2387
2388 /* Scrolling up is done much more efficiently by deleting lines instead of
2389 * redrawing the text. */
2390 if (dest.start_col == src.start_col
2391 && dest.end_col == src.end_col
2392 && dest.start_row < src.start_row)
2393 {
2394 win_T *wp;
2395 VTermColor fg, bg;
2396 VTermScreenCellAttrs attr;
2397 int clear_attr;
2398
2399 /* Set the color to clear lines with. */
2400 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2401 &fg, &bg);
2402 vim_memset(&attr, 0, sizeof(attr));
2403 clear_attr = cell2attr(attr, fg, bg);
2404
2405 FOR_ALL_WINDOWS(wp)
2406 {
2407 if (wp->w_buffer == term->tl_buffer)
2408 win_del_lines(wp, dest.start_row,
2409 src.start_row - dest.start_row, FALSE, FALSE,
2410 clear_attr);
2411 }
2412 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002413
2414 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2415 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2416
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002417 redraw_buf_later(term->tl_buffer, NOT_VALID);
2418 return 1;
2419}
2420
2421 static int
2422handle_movecursor(
2423 VTermPos pos,
2424 VTermPos oldpos UNUSED,
2425 int visible,
2426 void *user)
2427{
2428 term_T *term = (term_T *)user;
2429 win_T *wp;
2430
2431 term->tl_cursor_pos = pos;
2432 term->tl_cursor_visible = visible;
2433
2434 FOR_ALL_WINDOWS(wp)
2435 {
2436 if (wp->w_buffer == term->tl_buffer)
2437 position_cursor(wp, &pos);
2438 }
2439 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2440 {
2441 may_toggle_cursor(term);
2442 update_cursor(term, term->tl_cursor_visible);
2443 }
2444
2445 return 1;
2446}
2447
2448 static int
2449handle_settermprop(
2450 VTermProp prop,
2451 VTermValue *value,
2452 void *user)
2453{
2454 term_T *term = (term_T *)user;
2455
2456 switch (prop)
2457 {
2458 case VTERM_PROP_TITLE:
2459 vim_free(term->tl_title);
2460 /* a blank title isn't useful, make it empty, so that "running" is
2461 * displayed */
2462 if (*skipwhite((char_u *)value->string) == NUL)
2463 term->tl_title = NULL;
2464#ifdef WIN3264
2465 else if (!enc_utf8 && enc_codepage > 0)
2466 {
2467 WCHAR *ret = NULL;
2468 int length = 0;
2469
2470 MultiByteToWideChar_alloc(CP_UTF8, 0,
2471 (char*)value->string, (int)STRLEN(value->string),
2472 &ret, &length);
2473 if (ret != NULL)
2474 {
2475 WideCharToMultiByte_alloc(enc_codepage, 0,
2476 ret, length, (char**)&term->tl_title,
2477 &length, 0, 0);
2478 vim_free(ret);
2479 }
2480 }
2481#endif
2482 else
2483 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002484 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002485 if (term == curbuf->b_term)
2486 maketitle();
2487 break;
2488
2489 case VTERM_PROP_CURSORVISIBLE:
2490 term->tl_cursor_visible = value->boolean;
2491 may_toggle_cursor(term);
2492 out_flush();
2493 break;
2494
2495 case VTERM_PROP_CURSORBLINK:
2496 term->tl_cursor_blink = value->boolean;
2497 may_set_cursor_props(term);
2498 break;
2499
2500 case VTERM_PROP_CURSORSHAPE:
2501 term->tl_cursor_shape = value->number;
2502 may_set_cursor_props(term);
2503 break;
2504
2505 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002506 if (desired_cursor_color == term->tl_cursor_color)
2507 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002508 vim_free(term->tl_cursor_color);
2509 if (*value->string == NUL)
2510 term->tl_cursor_color = NULL;
2511 else
2512 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2513 may_set_cursor_props(term);
2514 break;
2515
2516 case VTERM_PROP_ALTSCREEN:
2517 /* TODO: do anything else? */
2518 term->tl_using_altscreen = value->boolean;
2519 break;
2520
2521 default:
2522 break;
2523 }
2524 /* Always return 1, otherwise vterm doesn't store the value internally. */
2525 return 1;
2526}
2527
2528/*
2529 * The job running in the terminal resized the terminal.
2530 */
2531 static int
2532handle_resize(int rows, int cols, void *user)
2533{
2534 term_T *term = (term_T *)user;
2535 win_T *wp;
2536
2537 term->tl_rows = rows;
2538 term->tl_cols = cols;
2539 if (term->tl_vterm_size_changed)
2540 /* Size was set by vterm_set_size(), don't set the window size. */
2541 term->tl_vterm_size_changed = FALSE;
2542 else
2543 {
2544 FOR_ALL_WINDOWS(wp)
2545 {
2546 if (wp->w_buffer == term->tl_buffer)
2547 {
2548 win_setheight_win(rows, wp);
2549 win_setwidth_win(cols, wp);
2550 }
2551 }
2552 redraw_buf_later(term->tl_buffer, NOT_VALID);
2553 }
2554 return 1;
2555}
2556
2557/*
2558 * Handle a line that is pushed off the top of the screen.
2559 */
2560 static int
2561handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2562{
2563 term_T *term = (term_T *)user;
2564
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002565 /* If the number of lines that are stored goes over 'termscrollback' then
2566 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002567 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002568 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002569 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002570 int i;
2571
2572 curbuf = term->tl_buffer;
2573 for (i = 0; i < todo; ++i)
2574 {
2575 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2576 ml_delete(1, FALSE);
2577 }
2578 curbuf = curwin->w_buffer;
2579
2580 term->tl_scrollback.ga_len -= todo;
2581 mch_memmove(term->tl_scrollback.ga_data,
2582 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2583 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2584 }
2585
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002586 if (ga_grow(&term->tl_scrollback, 1) == OK)
2587 {
2588 cellattr_T *p = NULL;
2589 int len = 0;
2590 int i;
2591 int c;
2592 int col;
2593 sb_line_T *line;
2594 garray_T ga;
2595 cellattr_T fill_attr = term->tl_default_color;
2596
2597 /* do not store empty cells at the end */
2598 for (i = 0; i < cols; ++i)
2599 if (cells[i].chars[0] != 0)
2600 len = i + 1;
2601 else
2602 cell2cellattr(&cells[i], &fill_attr);
2603
2604 ga_init2(&ga, 1, 100);
2605 if (len > 0)
2606 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2607 if (p != NULL)
2608 {
2609 for (col = 0; col < len; col += cells[col].width)
2610 {
2611 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2612 {
2613 ga.ga_len = 0;
2614 break;
2615 }
2616 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2617 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2618 (char_u *)ga.ga_data + ga.ga_len);
2619 cell2cellattr(&cells[col], &p[col]);
2620 }
2621 }
2622 if (ga_grow(&ga, 1) == FAIL)
2623 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2624 else
2625 {
2626 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2627 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2628 }
2629 ga_clear(&ga);
2630
2631 line = (sb_line_T *)term->tl_scrollback.ga_data
2632 + term->tl_scrollback.ga_len;
2633 line->sb_cols = len;
2634 line->sb_cells = p;
2635 line->sb_fill_attr = fill_attr;
2636 ++term->tl_scrollback.ga_len;
2637 ++term->tl_scrollback_scrolled;
2638 }
2639 return 0; /* ignored */
2640}
2641
2642static VTermScreenCallbacks screen_callbacks = {
2643 handle_damage, /* damage */
2644 handle_moverect, /* moverect */
2645 handle_movecursor, /* movecursor */
2646 handle_settermprop, /* settermprop */
2647 NULL, /* bell */
2648 handle_resize, /* resize */
2649 handle_pushline, /* sb_pushline */
2650 NULL /* sb_popline */
2651};
2652
2653/*
2654 * Called when a channel has been closed.
2655 * If this was a channel for a terminal window then finish it up.
2656 */
2657 void
2658term_channel_closed(channel_T *ch)
2659{
2660 term_T *term;
2661 int did_one = FALSE;
2662
2663 for (term = first_term; term != NULL; term = term->tl_next)
2664 if (term->tl_job == ch->ch_job)
2665 {
2666 term->tl_channel_closed = TRUE;
2667 did_one = TRUE;
2668
Bram Moolenaard23a8232018-02-10 18:45:26 +01002669 VIM_CLEAR(term->tl_title);
2670 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002671
2672 /* Unless in Terminal-Normal mode: clear the vterm. */
2673 if (!term->tl_normal_mode)
2674 {
2675 int fnum = term->tl_buffer->b_fnum;
2676
2677 cleanup_vterm(term);
2678
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002679 if (term->tl_finish == TL_FINISH_CLOSE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002680 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002681 aco_save_T aco;
2682
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 /* ++close or term_finish == "close" */
2684 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002685 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002686 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002687 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002688 break;
2689 }
Bram Moolenaar1dd98332018-03-16 22:54:53 +01002690 if (term->tl_finish == TL_FINISH_OPEN
2691 && term->tl_buffer->b_nwindows == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002692 {
2693 char buf[50];
2694
2695 /* TODO: use term_opencmd */
2696 ch_log(NULL, "terminal job finished, opening window");
2697 vim_snprintf(buf, sizeof(buf),
2698 term->tl_opencmd == NULL
2699 ? "botright sbuf %d"
2700 : (char *)term->tl_opencmd, fnum);
2701 do_cmdline_cmd((char_u *)buf);
2702 }
2703 else
2704 ch_log(NULL, "terminal job finished");
2705 }
2706
2707 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2708 }
2709 if (did_one)
2710 {
2711 redraw_statuslines();
2712
2713 /* Need to break out of vgetc(). */
2714 ins_char_typebuf(K_IGNORE);
2715 typebuf_was_filled = TRUE;
2716
2717 term = curbuf->b_term;
2718 if (term != NULL)
2719 {
2720 if (term->tl_job == ch->ch_job)
2721 maketitle();
2722 update_cursor(term, term->tl_cursor_visible);
2723 }
2724 }
2725}
2726
2727/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002728 * Fill one screen line from a line of the terminal.
2729 * Advances "pos" to past the last column.
2730 */
2731 static void
2732term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2733{
2734 int off = screen_get_current_line_off();
2735
2736 for (pos->col = 0; pos->col < max_col; )
2737 {
2738 VTermScreenCell cell;
2739 int c;
2740
2741 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2742 vim_memset(&cell, 0, sizeof(cell));
2743
2744 c = cell.chars[0];
2745 if (c == NUL)
2746 {
2747 ScreenLines[off] = ' ';
2748 if (enc_utf8)
2749 ScreenLinesUC[off] = NUL;
2750 }
2751 else
2752 {
2753 if (enc_utf8)
2754 {
2755 int i;
2756
2757 /* composing chars */
2758 for (i = 0; i < Screen_mco
2759 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2760 {
2761 ScreenLinesC[i][off] = cell.chars[i + 1];
2762 if (cell.chars[i + 1] == 0)
2763 break;
2764 }
2765 if (c >= 0x80 || (Screen_mco > 0
2766 && ScreenLinesC[0][off] != 0))
2767 {
2768 ScreenLines[off] = ' ';
2769 ScreenLinesUC[off] = c;
2770 }
2771 else
2772 {
2773 ScreenLines[off] = c;
2774 ScreenLinesUC[off] = NUL;
2775 }
2776 }
2777#ifdef WIN3264
2778 else if (has_mbyte && c >= 0x80)
2779 {
2780 char_u mb[MB_MAXBYTES+1];
2781 WCHAR wc = c;
2782
2783 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2784 (char*)mb, 2, 0, 0) > 1)
2785 {
2786 ScreenLines[off] = mb[0];
2787 ScreenLines[off + 1] = mb[1];
2788 cell.width = mb_ptr2cells(mb);
2789 }
2790 else
2791 ScreenLines[off] = c;
2792 }
2793#endif
2794 else
2795 ScreenLines[off] = c;
2796 }
2797 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2798
2799 ++pos->col;
2800 ++off;
2801 if (cell.width == 2)
2802 {
2803 if (enc_utf8)
2804 ScreenLinesUC[off] = NUL;
2805
2806 /* don't set the second byte to NUL for a DBCS encoding, it
2807 * has been set above */
2808 if (enc_utf8 || !has_mbyte)
2809 ScreenLines[off] = NUL;
2810
2811 ++pos->col;
2812 ++off;
2813 }
2814 }
2815}
2816
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002817#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01002818 static void
2819update_system_term(term_T *term)
2820{
2821 VTermPos pos;
2822 VTermScreen *screen;
2823
2824 if (term->tl_vterm == NULL)
2825 return;
2826 screen = vterm_obtain_screen(term->tl_vterm);
2827
2828 /* Scroll up to make more room for terminal lines if needed. */
2829 while (term->tl_toprow > 0
2830 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
2831 {
2832 int save_p_more = p_more;
2833
2834 p_more = FALSE;
2835 msg_row = Rows - 1;
2836 msg_puts((char_u *)"\n");
2837 p_more = save_p_more;
2838 --term->tl_toprow;
2839 }
2840
2841 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2842 && pos.row < Rows; ++pos.row)
2843 {
2844 if (pos.row < term->tl_rows)
2845 {
2846 int max_col = MIN(Columns, term->tl_cols);
2847
2848 term_line2screenline(screen, &pos, max_col);
2849 }
2850 else
2851 pos.col = 0;
2852
2853 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
2854 }
2855
2856 term->tl_dirty_row_start = MAX_ROW;
2857 term->tl_dirty_row_end = 0;
2858 update_cursor(term, TRUE);
2859}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01002860#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01002861
2862/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002863 * Called to update a window that contains an active terminal.
2864 * Returns FAIL when there is no terminal running in this window or in
2865 * Terminal-Normal mode.
2866 */
2867 int
2868term_update_window(win_T *wp)
2869{
2870 term_T *term = wp->w_buffer->b_term;
2871 VTerm *vterm;
2872 VTermScreen *screen;
2873 VTermState *state;
2874 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002875 int rows, cols;
2876 int newrows, newcols;
2877 int minsize;
2878 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002879
2880 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2881 return FAIL;
2882
2883 vterm = term->tl_vterm;
2884 screen = vterm_obtain_screen(vterm);
2885 state = vterm_obtain_state(vterm);
2886
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002887 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002888 {
2889 term->tl_dirty_row_start = 0;
2890 term->tl_dirty_row_end = MAX_ROW;
2891 }
2892
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002893 /*
2894 * If the window was resized a redraw will be triggered and we get here.
2895 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2896 */
Bram Moolenaar498c2562018-04-15 23:45:15 +02002897 minsize = parse_termsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002898
Bram Moolenaar498c2562018-04-15 23:45:15 +02002899 newrows = 99999;
2900 newcols = 99999;
2901 FOR_ALL_WINDOWS(twp)
2902 {
2903 /* When more than one window shows the same terminal, use the
2904 * smallest size. */
2905 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002906 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02002907 newrows = MIN(newrows, twp->w_height);
2908 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002909 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02002910 }
2911 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
2912 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
2913
2914 if (term->tl_rows != newrows || term->tl_cols != newcols)
2915 {
2916
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002917
2918 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02002919 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002920 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02002921 newrows);
2922 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002923 }
2924
2925 /* The cursor may have been moved when resizing. */
2926 vterm_state_get_cursorpos(state, &pos);
2927 position_cursor(wp, &pos);
2928
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002929 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2930 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002931 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002932 if (pos.row < term->tl_rows)
2933 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002934 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002935
Bram Moolenaar13568252018-03-16 20:46:58 +01002936 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002937 }
2938 else
2939 pos.col = 0;
2940
Bram Moolenaarf118d482018-03-13 13:14:00 +01002941 screen_line(wp->w_winrow + pos.row
2942#ifdef FEAT_MENU
2943 + winbar_height(wp)
2944#endif
2945 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002946 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002947 term->tl_dirty_row_start = MAX_ROW;
2948 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002949
2950 return OK;
2951}
2952
2953/*
2954 * Return TRUE if "wp" is a terminal window where the job has finished.
2955 */
2956 int
2957term_is_finished(buf_T *buf)
2958{
2959 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2960}
2961
2962/*
2963 * Return TRUE if "wp" is a terminal window where the job has finished or we
2964 * are in Terminal-Normal mode, thus we show the buffer contents.
2965 */
2966 int
2967term_show_buffer(buf_T *buf)
2968{
2969 term_T *term = buf->b_term;
2970
2971 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2972}
2973
2974/*
2975 * The current buffer is going to be changed. If there is terminal
2976 * highlighting remove it now.
2977 */
2978 void
2979term_change_in_curbuf(void)
2980{
2981 term_T *term = curbuf->b_term;
2982
2983 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2984 {
2985 free_scrollback(term);
2986 redraw_buf_later(term->tl_buffer, NOT_VALID);
2987
2988 /* The buffer is now like a normal buffer, it cannot be easily
2989 * abandoned when changed. */
2990 set_string_option_direct((char_u *)"buftype", -1,
2991 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2992 }
2993}
2994
2995/*
2996 * Get the screen attribute for a position in the buffer.
2997 * Use a negative "col" to get the filler background color.
2998 */
2999 int
3000term_get_attr(buf_T *buf, linenr_T lnum, int col)
3001{
3002 term_T *term = buf->b_term;
3003 sb_line_T *line;
3004 cellattr_T *cellattr;
3005
3006 if (lnum > term->tl_scrollback.ga_len)
3007 cellattr = &term->tl_default_color;
3008 else
3009 {
3010 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3011 if (col < 0 || col >= line->sb_cols)
3012 cellattr = &line->sb_fill_attr;
3013 else
3014 cellattr = line->sb_cells + col;
3015 }
3016 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3017}
3018
3019static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01003020 { 0, 0, 0, 1}, /* black */
3021 {224, 0, 0, 2}, /* dark red */
3022 { 0, 224, 0, 3}, /* dark green */
3023 {224, 224, 0, 4}, /* dark yellow / brown */
3024 { 0, 0, 224, 5}, /* dark blue */
3025 {224, 0, 224, 6}, /* dark magenta */
3026 { 0, 224, 224, 7}, /* dark cyan */
3027 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028
Bram Moolenaar46359e12017-11-29 22:33:38 +01003029 {128, 128, 128, 9}, /* dark grey */
3030 {255, 64, 64, 10}, /* light red */
3031 { 64, 255, 64, 11}, /* light green */
3032 {255, 255, 64, 12}, /* yellow */
3033 { 64, 64, 255, 13}, /* light blue */
3034 {255, 64, 255, 14}, /* light magenta */
3035 { 64, 255, 255, 15}, /* light cyan */
3036 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003037};
3038
3039static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003040 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003041};
3042
3043static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003044 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
3045 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003046};
3047
3048/*
3049 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003050 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003051 */
3052 static void
3053cterm_color2rgb(int nr, VTermColor *rgb)
3054{
3055 int idx;
3056
3057 if (nr < 16)
3058 {
3059 *rgb = ansi_table[nr];
3060 }
3061 else if (nr < 232)
3062 {
3063 /* 216 color cube */
3064 idx = nr - 16;
3065 rgb->blue = cube_value[idx % 6];
3066 rgb->green = cube_value[idx / 6 % 6];
3067 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003068 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003069 }
3070 else if (nr < 256)
3071 {
3072 /* 24 grey scale ramp */
3073 idx = nr - 232;
3074 rgb->blue = grey_ramp[idx];
3075 rgb->green = grey_ramp[idx];
3076 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003077 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003078 }
3079}
3080
3081/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003082 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003083 */
3084 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003085init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003086{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003087 VTermColor *fg, *bg;
3088 int fgval, bgval;
3089 int id;
3090
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003091 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3092 term->tl_default_color.width = 1;
3093 fg = &term->tl_default_color.fg;
3094 bg = &term->tl_default_color.bg;
3095
3096 /* Vterm uses a default black background. Set it to white when
3097 * 'background' is "light". */
3098 if (*p_bg == 'l')
3099 {
3100 fgval = 0;
3101 bgval = 255;
3102 }
3103 else
3104 {
3105 fgval = 255;
3106 bgval = 0;
3107 }
3108 fg->red = fg->green = fg->blue = fgval;
3109 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003110 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003111
3112 /* The "Terminal" highlight group overrules the defaults. */
3113 id = syn_name2id((char_u *)"Terminal");
3114
Bram Moolenaar46359e12017-11-29 22:33:38 +01003115 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3117 if (0
3118# ifdef FEAT_GUI
3119 || gui.in_use
3120# endif
3121# ifdef FEAT_TERMGUICOLORS
3122 || p_tgc
3123# endif
3124 )
3125 {
3126 guicolor_T fg_rgb = INVALCOLOR;
3127 guicolor_T bg_rgb = INVALCOLOR;
3128
3129 if (id != 0)
3130 syn_id2colors(id, &fg_rgb, &bg_rgb);
3131
3132# ifdef FEAT_GUI
3133 if (gui.in_use)
3134 {
3135 if (fg_rgb == INVALCOLOR)
3136 fg_rgb = gui.norm_pixel;
3137 if (bg_rgb == INVALCOLOR)
3138 bg_rgb = gui.back_pixel;
3139 }
3140# ifdef FEAT_TERMGUICOLORS
3141 else
3142# endif
3143# endif
3144# ifdef FEAT_TERMGUICOLORS
3145 {
3146 if (fg_rgb == INVALCOLOR)
3147 fg_rgb = cterm_normal_fg_gui_color;
3148 if (bg_rgb == INVALCOLOR)
3149 bg_rgb = cterm_normal_bg_gui_color;
3150 }
3151# endif
3152 if (fg_rgb != INVALCOLOR)
3153 {
3154 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3155
3156 fg->red = (unsigned)(rgb >> 16);
3157 fg->green = (unsigned)(rgb >> 8) & 255;
3158 fg->blue = (unsigned)rgb & 255;
3159 }
3160 if (bg_rgb != INVALCOLOR)
3161 {
3162 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3163
3164 bg->red = (unsigned)(rgb >> 16);
3165 bg->green = (unsigned)(rgb >> 8) & 255;
3166 bg->blue = (unsigned)rgb & 255;
3167 }
3168 }
3169 else
3170#endif
3171 if (id != 0 && t_colors >= 16)
3172 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003173 if (term_default_cterm_fg >= 0)
3174 cterm_color2rgb(term_default_cterm_fg, fg);
3175 if (term_default_cterm_bg >= 0)
3176 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003177 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003178 else
3179 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003180#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003181 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003182#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003183
3184 /* In an MS-Windows console we know the normal colors. */
3185 if (cterm_normal_fg_color > 0)
3186 {
3187 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003188# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003189 tmp = fg->red;
3190 fg->red = fg->blue;
3191 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003192# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003193 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003194# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003195 else
3196 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003197# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003198
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003199 if (cterm_normal_bg_color > 0)
3200 {
3201 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003202# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003203 tmp = bg->red;
3204 bg->red = bg->blue;
3205 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003206# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003207 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003208# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003209 else
3210 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003211# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003212 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003213}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003215#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3216/*
3217 * Set the 16 ANSI colors from array of RGB values
3218 */
3219 static void
3220set_vterm_palette(VTerm *vterm, long_u *rgb)
3221{
3222 int index = 0;
3223 VTermState *state = vterm_obtain_state(vterm);
3224 for (; index < 16; index++)
3225 {
3226 VTermColor color;
3227 color.red = (unsigned)(rgb[index] >> 16);
3228 color.green = (unsigned)(rgb[index] >> 8) & 255;
3229 color.blue = (unsigned)rgb[index] & 255;
3230 vterm_state_set_palette_color(state, index, &color);
3231 }
3232}
3233
3234/*
3235 * Set the ANSI color palette from a list of colors
3236 */
3237 static int
3238set_ansi_colors_list(VTerm *vterm, list_T *list)
3239{
3240 int n = 0;
3241 long_u rgb[16];
3242 listitem_T *li = list->lv_first;
3243
3244 for (; li != NULL && n < 16; li = li->li_next, n++)
3245 {
3246 char_u *color_name;
3247 guicolor_T guicolor;
3248
3249 color_name = get_tv_string_chk(&li->li_tv);
3250 if (color_name == NULL)
3251 return FAIL;
3252
3253 guicolor = GUI_GET_COLOR(color_name);
3254 if (guicolor == INVALCOLOR)
3255 return FAIL;
3256
3257 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3258 }
3259
3260 if (n != 16 || li != NULL)
3261 return FAIL;
3262
3263 set_vterm_palette(vterm, rgb);
3264
3265 return OK;
3266}
3267
3268/*
3269 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3270 */
3271 static void
3272init_vterm_ansi_colors(VTerm *vterm)
3273{
3274 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3275
3276 if (var != NULL
3277 && (var->di_tv.v_type != VAR_LIST
3278 || var->di_tv.vval.v_list == NULL
3279 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3280 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3281}
3282#endif
3283
Bram Moolenaar52acb112018-03-18 19:20:22 +01003284/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003285 * Handles a "drop" command from the job in the terminal.
3286 * "item" is the file name, "item->li_next" may have options.
3287 */
3288 static void
3289handle_drop_command(listitem_T *item)
3290{
3291 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003292 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003293 int bufnr;
3294 win_T *wp;
3295 tabpage_T *tp;
3296 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003297 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003298
3299 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3300 FOR_ALL_TAB_WINDOWS(tp, wp)
3301 {
3302 if (wp->w_buffer->b_fnum == bufnr)
3303 {
3304 /* buffer is in a window already, go there */
3305 goto_tabpage_win(tp, wp);
3306 return;
3307 }
3308 }
3309
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003310 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003311
3312 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3313 && opt_item->li_tv.vval.v_dict != NULL)
3314 {
3315 dict_T *dict = opt_item->li_tv.vval.v_dict;
3316 char_u *p;
3317
3318 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3319 if (p == NULL)
3320 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3321 if (p != NULL)
3322 {
3323 if (check_ff_value(p) == FAIL)
3324 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3325 else
3326 ea.force_ff = *p;
3327 }
3328 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3329 if (p == NULL)
3330 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3331 if (p != NULL)
3332 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003333 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003334 if (ea.cmd != NULL)
3335 {
3336 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3337 ea.force_enc = 11;
3338 tofree = ea.cmd;
3339 }
3340 }
3341
3342 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3343 if (p != NULL)
3344 get_bad_opt(p, &ea);
3345
3346 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3347 ea.force_bin = FORCE_BIN;
3348 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3349 ea.force_bin = FORCE_BIN;
3350 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3351 ea.force_bin = FORCE_NOBIN;
3352 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3353 ea.force_bin = FORCE_NOBIN;
3354 }
3355
3356 /* open in new window, like ":split fname" */
3357 if (ea.cmd == NULL)
3358 ea.cmd = (char_u *)"split";
3359 ea.arg = fname;
3360 ea.cmdidx = CMD_split;
3361 ex_splitview(&ea);
3362
3363 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003364}
3365
3366/*
3367 * Handles a function call from the job running in a terminal.
3368 * "item" is the function name, "item->li_next" has the arguments.
3369 */
3370 static void
3371handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3372{
3373 char_u *func;
3374 typval_T argvars[2];
3375 typval_T rettv;
3376 int doesrange;
3377
3378 if (item->li_next == NULL)
3379 {
3380 ch_log(channel, "Missing function arguments for call");
3381 return;
3382 }
3383 func = get_tv_string(&item->li_tv);
3384
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003385 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003386 {
3387 ch_log(channel, "Invalid function name: %s", func);
3388 return;
3389 }
3390
3391 argvars[0].v_type = VAR_NUMBER;
3392 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3393 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003394 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003395 2, argvars, /* argv_func */ NULL,
3396 /* firstline */ 1, /* lastline */ 1,
3397 &doesrange, /* evaluate */ TRUE,
3398 /* partial */ NULL, /* selfdict */ NULL) == OK)
3399 {
3400 clear_tv(&rettv);
3401 ch_log(channel, "Function %s called", func);
3402 }
3403 else
3404 ch_log(channel, "Calling function %s failed", func);
3405}
3406
3407/*
3408 * Called by libvterm when it cannot recognize an OSC sequence.
3409 * We recognize a terminal API command.
3410 */
3411 static int
3412parse_osc(const char *command, size_t cmdlen, void *user)
3413{
3414 term_T *term = (term_T *)user;
3415 js_read_T reader;
3416 typval_T tv;
3417 channel_T *channel = term->tl_job == NULL ? NULL
3418 : term->tl_job->jv_channel;
3419
3420 /* We recognize only OSC 5 1 ; {command} */
3421 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3422 return 0; /* not handled */
3423
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003424 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003425 if (reader.js_buf == NULL)
3426 return 1;
3427 reader.js_fill = NULL;
3428 reader.js_used = 0;
3429 if (json_decode(&reader, &tv, 0) == OK
3430 && tv.v_type == VAR_LIST
3431 && tv.vval.v_list != NULL)
3432 {
3433 listitem_T *item = tv.vval.v_list->lv_first;
3434
3435 if (item == NULL)
3436 ch_log(channel, "Missing command");
3437 else
3438 {
3439 char_u *cmd = get_tv_string(&item->li_tv);
3440
Bram Moolenaara997b452018-04-17 23:24:06 +02003441 /* Make sure an invoked command doesn't delete the buffer (and the
3442 * terminal) under our fingers. */
3443 ++term->tl_buffer->b_locked;
3444
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003445 item = item->li_next;
3446 if (item == NULL)
3447 ch_log(channel, "Missing argument for %s", cmd);
3448 else if (STRCMP(cmd, "drop") == 0)
3449 handle_drop_command(item);
3450 else if (STRCMP(cmd, "call") == 0)
3451 handle_call_command(term, channel, item);
3452 else
3453 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003454 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003455 }
3456 }
3457 else
3458 ch_log(channel, "Invalid JSON received");
3459
3460 vim_free(reader.js_buf);
3461 clear_tv(&tv);
3462 return 1;
3463}
3464
3465static VTermParserCallbacks parser_fallbacks = {
3466 NULL, /* text */
3467 NULL, /* control */
3468 NULL, /* escape */
3469 NULL, /* csi */
3470 parse_osc, /* osc */
3471 NULL, /* dcs */
3472 NULL /* resize */
3473};
3474
3475/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003476 * Use Vim's allocation functions for vterm so profiling works.
3477 */
3478 static void *
3479vterm_malloc(size_t size, void *data UNUSED)
3480{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003481 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003482}
3483
3484 static void
3485vterm_memfree(void *ptr, void *data UNUSED)
3486{
3487 vim_free(ptr);
3488}
3489
3490static VTermAllocatorFunctions vterm_allocator = {
3491 &vterm_malloc,
3492 &vterm_memfree
3493};
3494
3495/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003496 * Create a new vterm and initialize it.
3497 */
3498 static void
3499create_vterm(term_T *term, int rows, int cols)
3500{
3501 VTerm *vterm;
3502 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003503 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003504 VTermValue value;
3505
Bram Moolenaar756ef112018-04-10 12:04:27 +02003506 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003507 term->tl_vterm = vterm;
3508 screen = vterm_obtain_screen(vterm);
3509 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3510 /* TODO: depends on 'encoding'. */
3511 vterm_set_utf8(vterm, 1);
3512
3513 init_default_colors(term);
3514
3515 vterm_state_set_default_colors(
3516 vterm_obtain_state(vterm),
3517 &term->tl_default_color.fg,
3518 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003519
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003520 if (t_colors >= 16)
3521 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3522
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003523 /* Required to initialize most things. */
3524 vterm_screen_reset(screen, 1 /* hard */);
3525
3526 /* Allow using alternate screen. */
3527 vterm_screen_enable_altscreen(screen, 1);
3528
3529 /* For unix do not use a blinking cursor. In an xterm this causes the
3530 * cursor to blink if it's blinking in the xterm.
3531 * For Windows we respect the system wide setting. */
3532#ifdef WIN3264
3533 if (GetCaretBlinkTime() == INFINITE)
3534 value.boolean = 0;
3535 else
3536 value.boolean = 1;
3537#else
3538 value.boolean = 0;
3539#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003540 state = vterm_obtain_state(vterm);
3541 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3542 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003543}
3544
3545/*
3546 * Return the text to show for the buffer name and status.
3547 */
3548 char_u *
3549term_get_status_text(term_T *term)
3550{
3551 if (term->tl_status_text == NULL)
3552 {
3553 char_u *txt;
3554 size_t len;
3555
3556 if (term->tl_normal_mode)
3557 {
3558 if (term_job_running(term))
3559 txt = (char_u *)_("Terminal");
3560 else
3561 txt = (char_u *)_("Terminal-finished");
3562 }
3563 else if (term->tl_title != NULL)
3564 txt = term->tl_title;
3565 else if (term_none_open(term))
3566 txt = (char_u *)_("active");
3567 else if (term_job_running(term))
3568 txt = (char_u *)_("running");
3569 else
3570 txt = (char_u *)_("finished");
3571 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3572 term->tl_status_text = alloc((int)len);
3573 if (term->tl_status_text != NULL)
3574 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3575 term->tl_buffer->b_fname, txt);
3576 }
3577 return term->tl_status_text;
3578}
3579
3580/*
3581 * Mark references in jobs of terminals.
3582 */
3583 int
3584set_ref_in_term(int copyID)
3585{
3586 int abort = FALSE;
3587 term_T *term;
3588 typval_T tv;
3589
3590 for (term = first_term; term != NULL; term = term->tl_next)
3591 if (term->tl_job != NULL)
3592 {
3593 tv.v_type = VAR_JOB;
3594 tv.vval.v_job = term->tl_job;
3595 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3596 }
3597 return abort;
3598}
3599
3600/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003601 * Cache "Terminal" highlight group colors.
3602 */
3603 void
3604set_terminal_default_colors(int cterm_fg, int cterm_bg)
3605{
3606 term_default_cterm_fg = cterm_fg - 1;
3607 term_default_cterm_bg = cterm_bg - 1;
3608}
3609
3610/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003611 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003612 * Returns NULL when the buffer is not for a terminal window and logs a message
3613 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003614 */
3615 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003616term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003617{
3618 buf_T *buf;
3619
3620 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3621 ++emsg_off;
3622 buf = get_buf_tv(&argvars[0], FALSE);
3623 --emsg_off;
3624 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003625 {
3626 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003627 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003628 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003629 return buf;
3630}
3631
Bram Moolenaard96ff162018-02-18 22:13:29 +01003632 static int
3633same_color(VTermColor *a, VTermColor *b)
3634{
3635 return a->red == b->red
3636 && a->green == b->green
3637 && a->blue == b->blue
3638 && a->ansi_index == b->ansi_index;
3639}
3640
3641 static void
3642dump_term_color(FILE *fd, VTermColor *color)
3643{
3644 fprintf(fd, "%02x%02x%02x%d",
3645 (int)color->red, (int)color->green, (int)color->blue,
3646 (int)color->ansi_index);
3647}
3648
3649/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003650 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003651 *
3652 * Each screen cell in full is:
3653 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3654 * {characters} is a space for an empty cell
3655 * For a double-width character "+" is changed to "*" and the next cell is
3656 * skipped.
3657 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3658 * when "&" use the same as the previous cell.
3659 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3660 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3661 * {color-idx} is a number from 0 to 255
3662 *
3663 * Screen cell with same width, attributes and color as the previous one:
3664 * |{characters}
3665 *
3666 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3667 *
3668 * Repeating the previous screen cell:
3669 * @{count}
3670 */
3671 void
3672f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3673{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003674 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003675 term_T *term;
3676 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003677 int max_height = 0;
3678 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003679 stat_T st;
3680 FILE *fd;
3681 VTermPos pos;
3682 VTermScreen *screen;
3683 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003684 VTermState *state;
3685 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003686
3687 if (check_restricted() || check_secure())
3688 return;
3689 if (buf == NULL)
3690 return;
3691 term = buf->b_term;
3692
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003693 if (argvars[2].v_type != VAR_UNKNOWN)
3694 {
3695 dict_T *d;
3696
3697 if (argvars[2].v_type != VAR_DICT)
3698 {
3699 EMSG(_(e_dictreq));
3700 return;
3701 }
3702 d = argvars[2].vval.v_dict;
3703 if (d != NULL)
3704 {
3705 max_height = get_dict_number(d, (char_u *)"rows");
3706 max_width = get_dict_number(d, (char_u *)"columns");
3707 }
3708 }
3709
Bram Moolenaard96ff162018-02-18 22:13:29 +01003710 fname = get_tv_string_chk(&argvars[1]);
3711 if (fname == NULL)
3712 return;
3713 if (mch_stat((char *)fname, &st) >= 0)
3714 {
3715 EMSG2(_("E953: File exists: %s"), fname);
3716 return;
3717 }
3718
Bram Moolenaard96ff162018-02-18 22:13:29 +01003719 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3720 {
3721 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3722 return;
3723 }
3724
3725 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3726
3727 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003728 state = vterm_obtain_state(term->tl_vterm);
3729 vterm_state_get_cursorpos(state, &cursor_pos);
3730
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003731 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3732 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003733 {
3734 int repeat = 0;
3735
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003736 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3737 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003738 {
3739 VTermScreenCell cell;
3740 int same_attr;
3741 int same_chars = TRUE;
3742 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003743 int is_cursor_pos = (pos.col == cursor_pos.col
3744 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003745
3746 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3747 vim_memset(&cell, 0, sizeof(cell));
3748
3749 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3750 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003751 int c = cell.chars[i];
3752 int pc = prev_cell.chars[i];
3753
3754 /* For the first character NUL is the same as space. */
3755 if (i == 0)
3756 {
3757 c = (c == NUL) ? ' ' : c;
3758 pc = (pc == NUL) ? ' ' : pc;
3759 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003760 if (cell.chars[i] != prev_cell.chars[i])
3761 same_chars = FALSE;
3762 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3763 break;
3764 }
3765 same_attr = vtermAttr2hl(cell.attrs)
3766 == vtermAttr2hl(prev_cell.attrs)
3767 && same_color(&cell.fg, &prev_cell.fg)
3768 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003769 if (same_chars && cell.width == prev_cell.width && same_attr
3770 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003771 {
3772 ++repeat;
3773 }
3774 else
3775 {
3776 if (repeat > 0)
3777 {
3778 fprintf(fd, "@%d", repeat);
3779 repeat = 0;
3780 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003781 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003782
3783 if (cell.chars[0] == NUL)
3784 fputs(" ", fd);
3785 else
3786 {
3787 char_u charbuf[10];
3788 int len;
3789
3790 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3791 && cell.chars[i] != NUL; ++i)
3792 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003793 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003794 fwrite(charbuf, len, 1, fd);
3795 }
3796 }
3797
3798 /* When only the characters differ we don't write anything, the
3799 * following "|", "@" or NL will indicate using the same
3800 * attributes. */
3801 if (cell.width != prev_cell.width || !same_attr)
3802 {
3803 if (cell.width == 2)
3804 {
3805 fputs("*", fd);
3806 ++pos.col;
3807 }
3808 else
3809 fputs("+", fd);
3810
3811 if (same_attr)
3812 {
3813 fputs("&", fd);
3814 }
3815 else
3816 {
3817 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3818 if (same_color(&cell.fg, &prev_cell.fg))
3819 fputs("&", fd);
3820 else
3821 {
3822 fputs("#", fd);
3823 dump_term_color(fd, &cell.fg);
3824 }
3825 if (same_color(&cell.bg, &prev_cell.bg))
3826 fputs("&", fd);
3827 else
3828 {
3829 fputs("#", fd);
3830 dump_term_color(fd, &cell.bg);
3831 }
3832 }
3833 }
3834
3835 prev_cell = cell;
3836 }
3837 }
3838 if (repeat > 0)
3839 fprintf(fd, "@%d", repeat);
3840 fputs("\n", fd);
3841 }
3842
3843 fclose(fd);
3844}
3845
3846/*
3847 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3848 */
3849 static void
3850dump_is_corrupt(garray_T *gap)
3851{
3852 ga_concat(gap, (char_u *)"CORRUPT");
3853}
3854
3855 static void
3856append_cell(garray_T *gap, cellattr_T *cell)
3857{
3858 if (ga_grow(gap, 1) == OK)
3859 {
3860 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3861 ++gap->ga_len;
3862 }
3863}
3864
3865/*
3866 * Read the dump file from "fd" and append lines to the current buffer.
3867 * Return the cell width of the longest line.
3868 */
3869 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003870read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003871{
3872 int c;
3873 garray_T ga_text;
3874 garray_T ga_cell;
3875 char_u *prev_char = NULL;
3876 int attr = 0;
3877 cellattr_T cell;
3878 term_T *term = curbuf->b_term;
3879 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003880 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003881
3882 ga_init2(&ga_text, 1, 90);
3883 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3884 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003885 cursor_pos->row = -1;
3886 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003887
3888 c = fgetc(fd);
3889 for (;;)
3890 {
3891 if (c == EOF)
3892 break;
3893 if (c == '\n')
3894 {
3895 /* End of a line: append it to the buffer. */
3896 if (ga_text.ga_data == NULL)
3897 dump_is_corrupt(&ga_text);
3898 if (ga_grow(&term->tl_scrollback, 1) == OK)
3899 {
3900 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3901 + term->tl_scrollback.ga_len;
3902
3903 if (max_cells < ga_cell.ga_len)
3904 max_cells = ga_cell.ga_len;
3905 line->sb_cols = ga_cell.ga_len;
3906 line->sb_cells = ga_cell.ga_data;
3907 line->sb_fill_attr = term->tl_default_color;
3908 ++term->tl_scrollback.ga_len;
3909 ga_init(&ga_cell);
3910
3911 ga_append(&ga_text, NUL);
3912 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3913 ga_text.ga_len, FALSE);
3914 }
3915 else
3916 ga_clear(&ga_cell);
3917 ga_text.ga_len = 0;
3918
3919 c = fgetc(fd);
3920 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003921 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003922 {
3923 int prev_len = ga_text.ga_len;
3924
Bram Moolenaar9271d052018-02-25 21:39:46 +01003925 if (c == '>')
3926 {
3927 if (cursor_pos->row != -1)
3928 dump_is_corrupt(&ga_text); /* duplicate cursor */
3929 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3930 cursor_pos->col = ga_cell.ga_len;
3931 }
3932
Bram Moolenaard96ff162018-02-18 22:13:29 +01003933 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3934 c = fgetc(fd);
3935 if (c != EOF)
3936 ga_append(&ga_text, c);
3937 for (;;)
3938 {
3939 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003940 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003941 || c == EOF || c == '\n')
3942 break;
3943 ga_append(&ga_text, c);
3944 }
3945
3946 /* save the character for repeating it */
3947 vim_free(prev_char);
3948 if (ga_text.ga_data != NULL)
3949 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3950 ga_text.ga_len - prev_len);
3951
Bram Moolenaar9271d052018-02-25 21:39:46 +01003952 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003953 {
3954 /* use all attributes from previous cell */
3955 }
3956 else if (c == '+' || c == '*')
3957 {
3958 int is_bg;
3959
3960 cell.width = c == '+' ? 1 : 2;
3961
3962 c = fgetc(fd);
3963 if (c == '&')
3964 {
3965 /* use same attr as previous cell */
3966 c = fgetc(fd);
3967 }
3968 else if (isdigit(c))
3969 {
3970 /* get the decimal attribute */
3971 attr = 0;
3972 while (isdigit(c))
3973 {
3974 attr = attr * 10 + (c - '0');
3975 c = fgetc(fd);
3976 }
3977 hl2vtermAttr(attr, &cell);
3978 }
3979 else
3980 dump_is_corrupt(&ga_text);
3981
3982 /* is_bg == 0: fg, is_bg == 1: bg */
3983 for (is_bg = 0; is_bg <= 1; ++is_bg)
3984 {
3985 if (c == '&')
3986 {
3987 /* use same color as previous cell */
3988 c = fgetc(fd);
3989 }
3990 else if (c == '#')
3991 {
3992 int red, green, blue, index = 0;
3993
3994 c = fgetc(fd);
3995 red = hex2nr(c);
3996 c = fgetc(fd);
3997 red = (red << 4) + hex2nr(c);
3998 c = fgetc(fd);
3999 green = hex2nr(c);
4000 c = fgetc(fd);
4001 green = (green << 4) + hex2nr(c);
4002 c = fgetc(fd);
4003 blue = hex2nr(c);
4004 c = fgetc(fd);
4005 blue = (blue << 4) + hex2nr(c);
4006 c = fgetc(fd);
4007 if (!isdigit(c))
4008 dump_is_corrupt(&ga_text);
4009 while (isdigit(c))
4010 {
4011 index = index * 10 + (c - '0');
4012 c = fgetc(fd);
4013 }
4014
4015 if (is_bg)
4016 {
4017 cell.bg.red = red;
4018 cell.bg.green = green;
4019 cell.bg.blue = blue;
4020 cell.bg.ansi_index = index;
4021 }
4022 else
4023 {
4024 cell.fg.red = red;
4025 cell.fg.green = green;
4026 cell.fg.blue = blue;
4027 cell.fg.ansi_index = index;
4028 }
4029 }
4030 else
4031 dump_is_corrupt(&ga_text);
4032 }
4033 }
4034 else
4035 dump_is_corrupt(&ga_text);
4036
4037 append_cell(&ga_cell, &cell);
4038 }
4039 else if (c == '@')
4040 {
4041 if (prev_char == NULL)
4042 dump_is_corrupt(&ga_text);
4043 else
4044 {
4045 int count = 0;
4046
4047 /* repeat previous character, get the count */
4048 for (;;)
4049 {
4050 c = fgetc(fd);
4051 if (!isdigit(c))
4052 break;
4053 count = count * 10 + (c - '0');
4054 }
4055
4056 while (count-- > 0)
4057 {
4058 ga_concat(&ga_text, prev_char);
4059 append_cell(&ga_cell, &cell);
4060 }
4061 }
4062 }
4063 else
4064 {
4065 dump_is_corrupt(&ga_text);
4066 c = fgetc(fd);
4067 }
4068 }
4069
4070 if (ga_text.ga_len > 0)
4071 {
4072 /* trailing characters after last NL */
4073 dump_is_corrupt(&ga_text);
4074 ga_append(&ga_text, NUL);
4075 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4076 ga_text.ga_len, FALSE);
4077 }
4078
4079 ga_clear(&ga_text);
4080 vim_free(prev_char);
4081
4082 return max_cells;
4083}
4084
4085/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004086 * Return an allocated string with at least "text_width" "=" characters and
4087 * "fname" inserted in the middle.
4088 */
4089 static char_u *
4090get_separator(int text_width, char_u *fname)
4091{
4092 int width = MAX(text_width, curwin->w_width);
4093 char_u *textline;
4094 int fname_size;
4095 char_u *p = fname;
4096 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004097 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004098
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004099 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004100 if (textline == NULL)
4101 return NULL;
4102
4103 fname_size = vim_strsize(fname);
4104 if (fname_size < width - 8)
4105 {
4106 /* enough room, don't use the full window width */
4107 width = MAX(text_width, fname_size + 8);
4108 }
4109 else if (fname_size > width - 8)
4110 {
4111 /* full name doesn't fit, use only the tail */
4112 p = gettail(fname);
4113 fname_size = vim_strsize(p);
4114 }
4115 /* skip characters until the name fits */
4116 while (fname_size > width - 8)
4117 {
4118 p += (*mb_ptr2len)(p);
4119 fname_size = vim_strsize(p);
4120 }
4121
4122 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4123 textline[i] = '=';
4124 textline[i++] = ' ';
4125
4126 STRCPY(textline + i, p);
4127 off = STRLEN(textline);
4128 textline[off] = ' ';
4129 for (i = 1; i < (width - fname_size) / 2; ++i)
4130 textline[off + i] = '=';
4131 textline[off + i] = NUL;
4132
4133 return textline;
4134}
4135
4136/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004137 * Common for "term_dumpdiff()" and "term_dumpload()".
4138 */
4139 static void
4140term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4141{
4142 jobopt_T opt;
4143 buf_T *buf;
4144 char_u buf1[NUMBUFLEN];
4145 char_u buf2[NUMBUFLEN];
4146 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004147 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004148 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004149 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004150 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004151 char_u *textline = NULL;
4152
4153 /* First open the files. If this fails bail out. */
4154 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4155 if (do_diff)
4156 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4157 if (fname1 == NULL || (do_diff && fname2 == NULL))
4158 {
4159 EMSG(_(e_invarg));
4160 return;
4161 }
4162 fd1 = mch_fopen((char *)fname1, READBIN);
4163 if (fd1 == NULL)
4164 {
4165 EMSG2(_(e_notread), fname1);
4166 return;
4167 }
4168 if (do_diff)
4169 {
4170 fd2 = mch_fopen((char *)fname2, READBIN);
4171 if (fd2 == NULL)
4172 {
4173 fclose(fd1);
4174 EMSG2(_(e_notread), fname2);
4175 return;
4176 }
4177 }
4178
4179 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004180 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4181 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4182 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4183 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4184 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004185
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004186 if (opt.jo_term_name == NULL)
4187 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004188 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004189
Bram Moolenaarb571c632018-03-21 22:27:59 +01004190 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004191 if (fname_tofree != NULL)
4192 {
4193 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4194 opt.jo_term_name = fname_tofree;
4195 }
4196 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004197
Bram Moolenaar13568252018-03-16 20:46:58 +01004198 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004199 if (buf != NULL && buf->b_term != NULL)
4200 {
4201 int i;
4202 linenr_T bot_lnum;
4203 linenr_T lnum;
4204 term_T *term = buf->b_term;
4205 int width;
4206 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004207 VTermPos cursor_pos1;
4208 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004209
Bram Moolenaar52acb112018-03-18 19:20:22 +01004210 init_default_colors(term);
4211
Bram Moolenaard96ff162018-02-18 22:13:29 +01004212 rettv->vval.v_number = buf->b_fnum;
4213
4214 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004215 width = read_dump_file(fd1, &cursor_pos1);
4216
4217 /* position the cursor */
4218 if (cursor_pos1.row >= 0)
4219 {
4220 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4221 coladvance(cursor_pos1.col);
4222 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004223
4224 /* Delete the empty line that was in the empty buffer. */
4225 ml_delete(1, FALSE);
4226
4227 /* For term_dumpload() we are done here. */
4228 if (!do_diff)
4229 goto theend;
4230
4231 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4232
Bram Moolenaar4a696342018-04-05 18:45:26 +02004233 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004234 if (textline == NULL)
4235 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004236 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4237 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4238 vim_free(textline);
4239
4240 textline = get_separator(width, fname2);
4241 if (textline == NULL)
4242 goto theend;
4243 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4244 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004245 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004246
4247 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004248 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249 if (width2 > width)
4250 {
4251 vim_free(textline);
4252 textline = alloc(width2 + 1);
4253 if (textline == NULL)
4254 goto theend;
4255 width = width2;
4256 textline[width] = NUL;
4257 }
4258 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4259
4260 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4261 {
4262 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4263 {
4264 /* bottom part has fewer rows, fill with "-" */
4265 for (i = 0; i < width; ++i)
4266 textline[i] = '-';
4267 }
4268 else
4269 {
4270 char_u *line1;
4271 char_u *line2;
4272 char_u *p1;
4273 char_u *p2;
4274 int col;
4275 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4276 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4277 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4278 ->sb_cells;
4279
4280 /* Make a copy, getting the second line will invalidate it. */
4281 line1 = vim_strsave(ml_get(lnum));
4282 if (line1 == NULL)
4283 break;
4284 p1 = line1;
4285
4286 line2 = ml_get(lnum + bot_lnum);
4287 p2 = line2;
4288 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4289 {
4290 int len1 = utfc_ptr2len(p1);
4291 int len2 = utfc_ptr2len(p2);
4292
4293 textline[col] = ' ';
4294 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004295 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004296 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004297 else if (lnum == cursor_pos1.row + 1
4298 && col == cursor_pos1.col
4299 && (cursor_pos1.row != cursor_pos2.row
4300 || cursor_pos1.col != cursor_pos2.col))
4301 /* cursor in first but not in second */
4302 textline[col] = '>';
4303 else if (lnum == cursor_pos2.row + 1
4304 && col == cursor_pos2.col
4305 && (cursor_pos1.row != cursor_pos2.row
4306 || cursor_pos1.col != cursor_pos2.col))
4307 /* cursor in second but not in first */
4308 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004309 else if (cellattr1 != NULL && cellattr2 != NULL)
4310 {
4311 if ((cellattr1 + col)->width
4312 != (cellattr2 + col)->width)
4313 textline[col] = 'w';
4314 else if (!same_color(&(cellattr1 + col)->fg,
4315 &(cellattr2 + col)->fg))
4316 textline[col] = 'f';
4317 else if (!same_color(&(cellattr1 + col)->bg,
4318 &(cellattr2 + col)->bg))
4319 textline[col] = 'b';
4320 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4321 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4322 textline[col] = 'a';
4323 }
4324 p1 += len1;
4325 p2 += len2;
4326 /* TODO: handle different width */
4327 }
4328 vim_free(line1);
4329
4330 while (col < width)
4331 {
4332 if (*p1 == NUL && *p2 == NUL)
4333 textline[col] = '?';
4334 else if (*p1 == NUL)
4335 {
4336 textline[col] = '+';
4337 p2 += utfc_ptr2len(p2);
4338 }
4339 else
4340 {
4341 textline[col] = '-';
4342 p1 += utfc_ptr2len(p1);
4343 }
4344 ++col;
4345 }
4346 }
4347 if (add_empty_scrollback(term, &term->tl_default_color,
4348 term->tl_top_diff_rows) == OK)
4349 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4350 ++bot_lnum;
4351 }
4352
4353 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4354 {
4355 /* bottom part has more rows, fill with "+" */
4356 for (i = 0; i < width; ++i)
4357 textline[i] = '+';
4358 if (add_empty_scrollback(term, &term->tl_default_color,
4359 term->tl_top_diff_rows) == OK)
4360 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4361 ++lnum;
4362 ++bot_lnum;
4363 }
4364
4365 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004366
4367 /* looks better without wrapping */
4368 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004369 }
4370
4371theend:
4372 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004373 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004374 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004375 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004376 fclose(fd2);
4377}
4378
4379/*
4380 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4381 * bottom files.
4382 * Return FAIL when this is not possible.
4383 */
4384 int
4385term_swap_diff()
4386{
4387 term_T *term = curbuf->b_term;
4388 linenr_T line_count;
4389 linenr_T top_rows;
4390 linenr_T bot_rows;
4391 linenr_T bot_start;
4392 linenr_T lnum;
4393 char_u *p;
4394 sb_line_T *sb_line;
4395
4396 if (term == NULL
4397 || !term_is_finished(curbuf)
4398 || term->tl_top_diff_rows == 0
4399 || term->tl_scrollback.ga_len == 0)
4400 return FAIL;
4401
4402 line_count = curbuf->b_ml.ml_line_count;
4403 top_rows = term->tl_top_diff_rows;
4404 bot_rows = term->tl_bot_diff_rows;
4405 bot_start = line_count - bot_rows;
4406 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4407
4408 /* move lines from top to above the bottom part */
4409 for (lnum = 1; lnum <= top_rows; ++lnum)
4410 {
4411 p = vim_strsave(ml_get(1));
4412 if (p == NULL)
4413 return OK;
4414 ml_append(bot_start, p, 0, FALSE);
4415 ml_delete(1, FALSE);
4416 vim_free(p);
4417 }
4418
4419 /* move lines from bottom to the top */
4420 for (lnum = 1; lnum <= bot_rows; ++lnum)
4421 {
4422 p = vim_strsave(ml_get(bot_start + lnum));
4423 if (p == NULL)
4424 return OK;
4425 ml_delete(bot_start + lnum, FALSE);
4426 ml_append(lnum - 1, p, 0, FALSE);
4427 vim_free(p);
4428 }
4429
4430 if (top_rows == bot_rows)
4431 {
4432 /* rows counts are equal, can swap cell properties */
4433 for (lnum = 0; lnum < top_rows; ++lnum)
4434 {
4435 sb_line_T temp;
4436
4437 temp = *(sb_line + lnum);
4438 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4439 *(sb_line + bot_start + lnum) = temp;
4440 }
4441 }
4442 else
4443 {
4444 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4445 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4446
4447 /* need to copy cell properties into temp memory */
4448 if (temp != NULL)
4449 {
4450 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4451 mch_memmove(term->tl_scrollback.ga_data,
4452 temp + bot_start,
4453 sizeof(sb_line_T) * bot_rows);
4454 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4455 temp + top_rows,
4456 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4457 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4458 + line_count - top_rows,
4459 temp,
4460 sizeof(sb_line_T) * top_rows);
4461 vim_free(temp);
4462 }
4463 }
4464
4465 term->tl_top_diff_rows = bot_rows;
4466 term->tl_bot_diff_rows = top_rows;
4467
4468 update_screen(NOT_VALID);
4469 return OK;
4470}
4471
4472/*
4473 * "term_dumpdiff(filename, filename, options)" function
4474 */
4475 void
4476f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4477{
4478 term_load_dump(argvars, rettv, TRUE);
4479}
4480
4481/*
4482 * "term_dumpload(filename, options)" function
4483 */
4484 void
4485f_term_dumpload(typval_T *argvars, typval_T *rettv)
4486{
4487 term_load_dump(argvars, rettv, FALSE);
4488}
4489
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004490/*
4491 * "term_getaltscreen(buf)" function
4492 */
4493 void
4494f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4495{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004496 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004497
4498 if (buf == NULL)
4499 return;
4500 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4501}
4502
4503/*
4504 * "term_getattr(attr, name)" function
4505 */
4506 void
4507f_term_getattr(typval_T *argvars, typval_T *rettv)
4508{
4509 int attr;
4510 size_t i;
4511 char_u *name;
4512
4513 static struct {
4514 char *name;
4515 int attr;
4516 } attrs[] = {
4517 {"bold", HL_BOLD},
4518 {"italic", HL_ITALIC},
4519 {"underline", HL_UNDERLINE},
4520 {"strike", HL_STRIKETHROUGH},
4521 {"reverse", HL_INVERSE},
4522 };
4523
4524 attr = get_tv_number(&argvars[0]);
4525 name = get_tv_string_chk(&argvars[1]);
4526 if (name == NULL)
4527 return;
4528
4529 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4530 if (STRCMP(name, attrs[i].name) == 0)
4531 {
4532 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4533 break;
4534 }
4535}
4536
4537/*
4538 * "term_getcursor(buf)" function
4539 */
4540 void
4541f_term_getcursor(typval_T *argvars, typval_T *rettv)
4542{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004543 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004544 term_T *term;
4545 list_T *l;
4546 dict_T *d;
4547
4548 if (rettv_list_alloc(rettv) == FAIL)
4549 return;
4550 if (buf == NULL)
4551 return;
4552 term = buf->b_term;
4553
4554 l = rettv->vval.v_list;
4555 list_append_number(l, term->tl_cursor_pos.row + 1);
4556 list_append_number(l, term->tl_cursor_pos.col + 1);
4557
4558 d = dict_alloc();
4559 if (d != NULL)
4560 {
4561 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4562 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4563 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4564 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4565 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4566 ? (char_u *)"" : term->tl_cursor_color);
4567 list_append_dict(l, d);
4568 }
4569}
4570
4571/*
4572 * "term_getjob(buf)" function
4573 */
4574 void
4575f_term_getjob(typval_T *argvars, typval_T *rettv)
4576{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004577 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004578
4579 rettv->v_type = VAR_JOB;
4580 rettv->vval.v_job = NULL;
4581 if (buf == NULL)
4582 return;
4583
4584 rettv->vval.v_job = buf->b_term->tl_job;
4585 if (rettv->vval.v_job != NULL)
4586 ++rettv->vval.v_job->jv_refcount;
4587}
4588
4589 static int
4590get_row_number(typval_T *tv, term_T *term)
4591{
4592 if (tv->v_type == VAR_STRING
4593 && tv->vval.v_string != NULL
4594 && STRCMP(tv->vval.v_string, ".") == 0)
4595 return term->tl_cursor_pos.row;
4596 return (int)get_tv_number(tv) - 1;
4597}
4598
4599/*
4600 * "term_getline(buf, row)" function
4601 */
4602 void
4603f_term_getline(typval_T *argvars, typval_T *rettv)
4604{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004605 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004606 term_T *term;
4607 int row;
4608
4609 rettv->v_type = VAR_STRING;
4610 if (buf == NULL)
4611 return;
4612 term = buf->b_term;
4613 row = get_row_number(&argvars[1], term);
4614
4615 if (term->tl_vterm == NULL)
4616 {
4617 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4618
4619 /* vterm is finished, get the text from the buffer */
4620 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4621 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4622 }
4623 else
4624 {
4625 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4626 VTermRect rect;
4627 int len;
4628 char_u *p;
4629
4630 if (row < 0 || row >= term->tl_rows)
4631 return;
4632 len = term->tl_cols * MB_MAXBYTES + 1;
4633 p = alloc(len);
4634 if (p == NULL)
4635 return;
4636 rettv->vval.v_string = p;
4637
4638 rect.start_col = 0;
4639 rect.end_col = term->tl_cols;
4640 rect.start_row = row;
4641 rect.end_row = row + 1;
4642 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4643 }
4644}
4645
4646/*
4647 * "term_getscrolled(buf)" function
4648 */
4649 void
4650f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4651{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004652 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004653
4654 if (buf == NULL)
4655 return;
4656 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4657}
4658
4659/*
4660 * "term_getsize(buf)" function
4661 */
4662 void
4663f_term_getsize(typval_T *argvars, typval_T *rettv)
4664{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004665 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004666 list_T *l;
4667
4668 if (rettv_list_alloc(rettv) == FAIL)
4669 return;
4670 if (buf == NULL)
4671 return;
4672
4673 l = rettv->vval.v_list;
4674 list_append_number(l, buf->b_term->tl_rows);
4675 list_append_number(l, buf->b_term->tl_cols);
4676}
4677
4678/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004679 * "term_setsize(buf, rows, cols)" function
4680 */
4681 void
4682f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4683{
4684 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4685 term_T *term;
4686 varnumber_T rows, cols;
4687
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004688 if (buf == NULL)
4689 {
4690 EMSG(_("E955: Not a terminal buffer"));
4691 return;
4692 }
4693 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004694 return;
4695 term = buf->b_term;
4696 rows = get_tv_number(&argvars[1]);
4697 rows = rows <= 0 ? term->tl_rows : rows;
4698 cols = get_tv_number(&argvars[2]);
4699 cols = cols <= 0 ? term->tl_cols : cols;
4700 vterm_set_size(term->tl_vterm, rows, cols);
4701 /* handle_resize() will resize the windows */
4702
4703 /* Get and remember the size we ended up with. Update the pty. */
4704 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4705 term_report_winsize(term, term->tl_rows, term->tl_cols);
4706}
4707
4708/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004709 * "term_getstatus(buf)" function
4710 */
4711 void
4712f_term_getstatus(typval_T *argvars, typval_T *rettv)
4713{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004714 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004715 term_T *term;
4716 char_u val[100];
4717
4718 rettv->v_type = VAR_STRING;
4719 if (buf == NULL)
4720 return;
4721 term = buf->b_term;
4722
4723 if (term_job_running(term))
4724 STRCPY(val, "running");
4725 else
4726 STRCPY(val, "finished");
4727 if (term->tl_normal_mode)
4728 STRCAT(val, ",normal");
4729 rettv->vval.v_string = vim_strsave(val);
4730}
4731
4732/*
4733 * "term_gettitle(buf)" function
4734 */
4735 void
4736f_term_gettitle(typval_T *argvars, typval_T *rettv)
4737{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004738 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004739
4740 rettv->v_type = VAR_STRING;
4741 if (buf == NULL)
4742 return;
4743
4744 if (buf->b_term->tl_title != NULL)
4745 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4746}
4747
4748/*
4749 * "term_gettty(buf)" function
4750 */
4751 void
4752f_term_gettty(typval_T *argvars, typval_T *rettv)
4753{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004754 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004755 char_u *p;
4756 int num = 0;
4757
4758 rettv->v_type = VAR_STRING;
4759 if (buf == NULL)
4760 return;
4761 if (argvars[1].v_type != VAR_UNKNOWN)
4762 num = get_tv_number(&argvars[1]);
4763
4764 switch (num)
4765 {
4766 case 0:
4767 if (buf->b_term->tl_job != NULL)
4768 p = buf->b_term->tl_job->jv_tty_out;
4769 else
4770 p = buf->b_term->tl_tty_out;
4771 break;
4772 case 1:
4773 if (buf->b_term->tl_job != NULL)
4774 p = buf->b_term->tl_job->jv_tty_in;
4775 else
4776 p = buf->b_term->tl_tty_in;
4777 break;
4778 default:
4779 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4780 return;
4781 }
4782 if (p != NULL)
4783 rettv->vval.v_string = vim_strsave(p);
4784}
4785
4786/*
4787 * "term_list()" function
4788 */
4789 void
4790f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4791{
4792 term_T *tp;
4793 list_T *l;
4794
4795 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4796 return;
4797
4798 l = rettv->vval.v_list;
4799 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4800 if (tp != NULL && tp->tl_buffer != NULL)
4801 if (list_append_number(l,
4802 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4803 return;
4804}
4805
4806/*
4807 * "term_scrape(buf, row)" function
4808 */
4809 void
4810f_term_scrape(typval_T *argvars, typval_T *rettv)
4811{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004812 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004813 VTermScreen *screen = NULL;
4814 VTermPos pos;
4815 list_T *l;
4816 term_T *term;
4817 char_u *p;
4818 sb_line_T *line;
4819
4820 if (rettv_list_alloc(rettv) == FAIL)
4821 return;
4822 if (buf == NULL)
4823 return;
4824 term = buf->b_term;
4825
4826 l = rettv->vval.v_list;
4827 pos.row = get_row_number(&argvars[1], term);
4828
4829 if (term->tl_vterm != NULL)
4830 {
4831 screen = vterm_obtain_screen(term->tl_vterm);
4832 p = NULL;
4833 line = NULL;
4834 }
4835 else
4836 {
4837 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4838
4839 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4840 return;
4841 p = ml_get_buf(buf, lnum + 1, FALSE);
4842 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4843 }
4844
4845 for (pos.col = 0; pos.col < term->tl_cols; )
4846 {
4847 dict_T *dcell;
4848 int width;
4849 VTermScreenCellAttrs attrs;
4850 VTermColor fg, bg;
4851 char_u rgb[8];
4852 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4853 int off = 0;
4854 int i;
4855
4856 if (screen == NULL)
4857 {
4858 cellattr_T *cellattr;
4859 int len;
4860
4861 /* vterm has finished, get the cell from scrollback */
4862 if (pos.col >= line->sb_cols)
4863 break;
4864 cellattr = line->sb_cells + pos.col;
4865 width = cellattr->width;
4866 attrs = cellattr->attrs;
4867 fg = cellattr->fg;
4868 bg = cellattr->bg;
4869 len = MB_PTR2LEN(p);
4870 mch_memmove(mbs, p, len);
4871 mbs[len] = NUL;
4872 p += len;
4873 }
4874 else
4875 {
4876 VTermScreenCell cell;
4877 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4878 break;
4879 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4880 {
4881 if (cell.chars[i] == 0)
4882 break;
4883 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4884 }
4885 mbs[off] = NUL;
4886 width = cell.width;
4887 attrs = cell.attrs;
4888 fg = cell.fg;
4889 bg = cell.bg;
4890 }
4891 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004892 if (dcell == NULL)
4893 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004894 list_append_dict(l, dcell);
4895
4896 dict_add_nr_str(dcell, "chars", 0, mbs);
4897
4898 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4899 fg.red, fg.green, fg.blue);
4900 dict_add_nr_str(dcell, "fg", 0, rgb);
4901 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4902 bg.red, bg.green, bg.blue);
4903 dict_add_nr_str(dcell, "bg", 0, rgb);
4904
4905 dict_add_nr_str(dcell, "attr",
4906 cell2attr(attrs, fg, bg), NULL);
4907 dict_add_nr_str(dcell, "width", width, NULL);
4908
4909 ++pos.col;
4910 if (width == 2)
4911 ++pos.col;
4912 }
4913}
4914
4915/*
4916 * "term_sendkeys(buf, keys)" function
4917 */
4918 void
4919f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4920{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004921 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004922 char_u *msg;
4923 term_T *term;
4924
4925 rettv->v_type = VAR_UNKNOWN;
4926 if (buf == NULL)
4927 return;
4928
4929 msg = get_tv_string_chk(&argvars[1]);
4930 if (msg == NULL)
4931 return;
4932 term = buf->b_term;
4933 if (term->tl_vterm == NULL)
4934 return;
4935
4936 while (*msg != NUL)
4937 {
4938 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004939 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004940 }
4941}
4942
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004943#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
4944/*
4945 * "term_getansicolors(buf)" function
4946 */
4947 void
4948f_term_getansicolors(typval_T *argvars, typval_T *rettv)
4949{
4950 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
4951 term_T *term;
4952 VTermState *state;
4953 VTermColor color;
4954 char_u hexbuf[10];
4955 int index;
4956 list_T *list;
4957
4958 if (rettv_list_alloc(rettv) == FAIL)
4959 return;
4960
4961 if (buf == NULL)
4962 return;
4963 term = buf->b_term;
4964 if (term->tl_vterm == NULL)
4965 return;
4966
4967 list = rettv->vval.v_list;
4968 state = vterm_obtain_state(term->tl_vterm);
4969 for (index = 0; index < 16; index++)
4970 {
4971 vterm_state_get_palette_color(state, index, &color);
4972 sprintf((char *)hexbuf, "#%02x%02x%02x",
4973 color.red, color.green, color.blue);
4974 if (list_append_string(list, hexbuf, 7) == FAIL)
4975 return;
4976 }
4977}
4978
4979/*
4980 * "term_setansicolors(buf, list)" function
4981 */
4982 void
4983f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
4984{
4985 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
4986 term_T *term;
4987
4988 if (buf == NULL)
4989 return;
4990 term = buf->b_term;
4991 if (term->tl_vterm == NULL)
4992 return;
4993
4994 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
4995 {
4996 EMSG(_(e_listreq));
4997 return;
4998 }
4999
5000 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5001 EMSG(_(e_invarg));
5002}
5003#endif
5004
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005005/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005006 * "term_setrestore(buf, command)" function
5007 */
5008 void
5009f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5010{
5011#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005012 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005013 term_T *term;
5014 char_u *cmd;
5015
5016 if (buf == NULL)
5017 return;
5018 term = buf->b_term;
5019 vim_free(term->tl_command);
5020 cmd = get_tv_string_chk(&argvars[1]);
5021 if (cmd != NULL)
5022 term->tl_command = vim_strsave(cmd);
5023 else
5024 term->tl_command = NULL;
5025#endif
5026}
5027
5028/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005029 * "term_setkill(buf, how)" function
5030 */
5031 void
5032f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5033{
5034 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5035 term_T *term;
5036 char_u *how;
5037
5038 if (buf == NULL)
5039 return;
5040 term = buf->b_term;
5041 vim_free(term->tl_kill);
5042 how = get_tv_string_chk(&argvars[1]);
5043 if (how != NULL)
5044 term->tl_kill = vim_strsave(how);
5045 else
5046 term->tl_kill = NULL;
5047}
5048
5049/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005050 * "term_start(command, options)" function
5051 */
5052 void
5053f_term_start(typval_T *argvars, typval_T *rettv)
5054{
5055 jobopt_T opt;
5056 buf_T *buf;
5057
5058 init_job_options(&opt);
5059 if (argvars[1].v_type != VAR_UNKNOWN
5060 && get_job_options(&argvars[1], &opt,
5061 JO_TIMEOUT_ALL + JO_STOPONEXIT
5062 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5063 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5064 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5065 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005066 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005067 + JO2_NORESTORE + JO2_TERM_KILL
5068 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005069 return;
5070
Bram Moolenaar13568252018-03-16 20:46:58 +01005071 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005072
5073 if (buf != NULL && buf->b_term != NULL)
5074 rettv->vval.v_number = buf->b_fnum;
5075}
5076
5077/*
5078 * "term_wait" function
5079 */
5080 void
5081f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5082{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005083 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005084
5085 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005086 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005087 if (buf->b_term->tl_job == NULL)
5088 {
5089 ch_log(NULL, "term_wait(): no job to wait for");
5090 return;
5091 }
5092 if (buf->b_term->tl_job->jv_channel == NULL)
5093 /* channel is closed, nothing to do */
5094 return;
5095
5096 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005097 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005098 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5099 {
5100 /* The job is dead, keep reading channel I/O until the channel is
5101 * closed. buf->b_term may become NULL if the terminal was closed while
5102 * waiting. */
5103 ch_log(NULL, "term_wait(): waiting for channel to close");
5104 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5105 {
5106 mch_check_messages();
5107 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005108 if (!buf_valid(buf))
5109 /* If the terminal is closed when the channel is closed the
5110 * buffer disappears. */
5111 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005112 ui_delay(10L, FALSE);
5113 }
5114 mch_check_messages();
5115 parse_queued_messages();
5116 }
5117 else
5118 {
5119 long wait = 10L;
5120
5121 mch_check_messages();
5122 parse_queued_messages();
5123
5124 /* Wait for some time for any channel I/O. */
5125 if (argvars[1].v_type != VAR_UNKNOWN)
5126 wait = get_tv_number(&argvars[1]);
5127 ui_delay(wait, TRUE);
5128 mch_check_messages();
5129
5130 /* Flushing messages on channels is hopefully sufficient.
5131 * TODO: is there a better way? */
5132 parse_queued_messages();
5133 }
5134}
5135
5136/*
5137 * Called when a channel has sent all the lines to a terminal.
5138 * Send a CTRL-D to mark the end of the text.
5139 */
5140 void
5141term_send_eof(channel_T *ch)
5142{
5143 term_T *term;
5144
5145 for (term = first_term; term != NULL; term = term->tl_next)
5146 if (term->tl_job == ch->ch_job)
5147 {
5148 if (term->tl_eof_chars != NULL)
5149 {
5150 channel_send(ch, PART_IN, term->tl_eof_chars,
5151 (int)STRLEN(term->tl_eof_chars), NULL);
5152 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5153 }
5154# ifdef WIN3264
5155 else
5156 /* Default: CTRL-D */
5157 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5158# endif
5159 }
5160}
5161
5162# if defined(WIN3264) || defined(PROTO)
5163
5164/**************************************
5165 * 2. MS-Windows implementation.
5166 */
5167
5168# ifndef PROTO
5169
5170#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5171#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005172#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005173
5174void* (*winpty_config_new)(UINT64, void*);
5175void* (*winpty_open)(void*, void*);
5176void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5177BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5178void (*winpty_config_set_mouse_mode)(void*, int);
5179void (*winpty_config_set_initial_size)(void*, int, int);
5180LPCWSTR (*winpty_conin_name)(void*);
5181LPCWSTR (*winpty_conout_name)(void*);
5182LPCWSTR (*winpty_conerr_name)(void*);
5183void (*winpty_free)(void*);
5184void (*winpty_config_free)(void*);
5185void (*winpty_spawn_config_free)(void*);
5186void (*winpty_error_free)(void*);
5187LPCWSTR (*winpty_error_msg)(void*);
5188BOOL (*winpty_set_size)(void*, int, int, void*);
5189HANDLE (*winpty_agent_process)(void*);
5190
5191#define WINPTY_DLL "winpty.dll"
5192
5193static HINSTANCE hWinPtyDLL = NULL;
5194# endif
5195
5196 static int
5197dyn_winpty_init(int verbose)
5198{
5199 int i;
5200 static struct
5201 {
5202 char *name;
5203 FARPROC *ptr;
5204 } winpty_entry[] =
5205 {
5206 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5207 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5208 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5209 {"winpty_config_set_mouse_mode",
5210 (FARPROC*)&winpty_config_set_mouse_mode},
5211 {"winpty_config_set_initial_size",
5212 (FARPROC*)&winpty_config_set_initial_size},
5213 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5214 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5215 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5216 {"winpty_free", (FARPROC*)&winpty_free},
5217 {"winpty_open", (FARPROC*)&winpty_open},
5218 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5219 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5220 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5221 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5222 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5223 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5224 {NULL, NULL}
5225 };
5226
5227 /* No need to initialize twice. */
5228 if (hWinPtyDLL)
5229 return OK;
5230 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5231 * winpty.dll. */
5232 if (*p_winptydll != NUL)
5233 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5234 if (!hWinPtyDLL)
5235 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5236 if (!hWinPtyDLL)
5237 {
5238 if (verbose)
5239 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5240 : (char_u *)WINPTY_DLL);
5241 return FAIL;
5242 }
5243 for (i = 0; winpty_entry[i].name != NULL
5244 && winpty_entry[i].ptr != NULL; ++i)
5245 {
5246 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5247 winpty_entry[i].name)) == NULL)
5248 {
5249 if (verbose)
5250 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5251 return FAIL;
5252 }
5253 }
5254
5255 return OK;
5256}
5257
5258/*
5259 * Create a new terminal of "rows" by "cols" cells.
5260 * Store a reference in "term".
5261 * Return OK or FAIL.
5262 */
5263 static int
5264term_and_job_init(
5265 term_T *term,
5266 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005267 char **argv UNUSED,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005268 jobopt_T *opt)
5269{
5270 WCHAR *cmd_wchar = NULL;
5271 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005272 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005273 channel_T *channel = NULL;
5274 job_T *job = NULL;
5275 DWORD error;
5276 HANDLE jo = NULL;
5277 HANDLE child_process_handle;
5278 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005279 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005280 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005281 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005282 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005283
5284 if (dyn_winpty_init(TRUE) == FAIL)
5285 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005286 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5287 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005288
5289 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005290 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005291 cmd = argvar->vval.v_string;
5292 }
5293 else if (argvar->v_type == VAR_LIST)
5294 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005295 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005296 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005297 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005298 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005299 if (cmd == NULL || *cmd == NUL)
5300 {
5301 EMSG(_(e_invarg));
5302 goto failed;
5303 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005304
5305 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005306 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005307 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005308 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005309 if (opt->jo_cwd != NULL)
5310 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005311
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005312 win32_build_env(opt->jo_env, &ga_env, TRUE);
5313 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005314
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005315 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5316 if (term->tl_winpty_config == NULL)
5317 goto failed;
5318
5319 winpty_config_set_mouse_mode(term->tl_winpty_config,
5320 WINPTY_MOUSE_MODE_FORCE);
5321 winpty_config_set_initial_size(term->tl_winpty_config,
5322 term->tl_cols, term->tl_rows);
5323 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5324 if (term->tl_winpty == NULL)
5325 goto failed;
5326
5327 spawn_config = winpty_spawn_config_new(
5328 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5329 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5330 NULL,
5331 cmd_wchar,
5332 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005333 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005334 &winpty_err);
5335 if (spawn_config == NULL)
5336 goto failed;
5337
5338 channel = add_channel();
5339 if (channel == NULL)
5340 goto failed;
5341
5342 job = job_alloc();
5343 if (job == NULL)
5344 goto failed;
5345
5346 if (opt->jo_set & JO_IN_BUF)
5347 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5348
5349 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5350 &child_thread_handle, &error, &winpty_err))
5351 goto failed;
5352
5353 channel_set_pipes(channel,
5354 (sock_T)CreateFileW(
5355 winpty_conin_name(term->tl_winpty),
5356 GENERIC_WRITE, 0, NULL,
5357 OPEN_EXISTING, 0, NULL),
5358 (sock_T)CreateFileW(
5359 winpty_conout_name(term->tl_winpty),
5360 GENERIC_READ, 0, NULL,
5361 OPEN_EXISTING, 0, NULL),
5362 (sock_T)CreateFileW(
5363 winpty_conerr_name(term->tl_winpty),
5364 GENERIC_READ, 0, NULL,
5365 OPEN_EXISTING, 0, NULL));
5366
5367 /* Write lines with CR instead of NL. */
5368 channel->ch_write_text_mode = TRUE;
5369
5370 jo = CreateJobObject(NULL, NULL);
5371 if (jo == NULL)
5372 goto failed;
5373
5374 if (!AssignProcessToJobObject(jo, child_process_handle))
5375 {
5376 /* Failed, switch the way to terminate process with TerminateProcess. */
5377 CloseHandle(jo);
5378 jo = NULL;
5379 }
5380
5381 winpty_spawn_config_free(spawn_config);
5382 vim_free(cmd_wchar);
5383 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005384 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005385
5386 create_vterm(term, term->tl_rows, term->tl_cols);
5387
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005388#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5389 if (opt->jo_set2 & JO2_ANSI_COLORS)
5390 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5391 else
5392 init_vterm_ansi_colors(term->tl_vterm);
5393#endif
5394
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005395 channel_set_job(channel, job, opt);
5396 job_set_options(job, opt);
5397
5398 job->jv_channel = channel;
5399 job->jv_proc_info.hProcess = child_process_handle;
5400 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5401 job->jv_job_object = jo;
5402 job->jv_status = JOB_STARTED;
5403 job->jv_tty_in = utf16_to_enc(
5404 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5405 job->jv_tty_out = utf16_to_enc(
5406 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5407 ++job->jv_refcount;
5408 term->tl_job = job;
5409
5410 return OK;
5411
5412failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005413 ga_clear(&ga_cmd);
5414 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005415 vim_free(cmd_wchar);
5416 vim_free(cwd_wchar);
5417 if (spawn_config != NULL)
5418 winpty_spawn_config_free(spawn_config);
5419 if (channel != NULL)
5420 channel_clear(channel);
5421 if (job != NULL)
5422 {
5423 job->jv_channel = NULL;
5424 job_cleanup(job);
5425 }
5426 term->tl_job = NULL;
5427 if (jo != NULL)
5428 CloseHandle(jo);
5429 if (term->tl_winpty != NULL)
5430 winpty_free(term->tl_winpty);
5431 term->tl_winpty = NULL;
5432 if (term->tl_winpty_config != NULL)
5433 winpty_config_free(term->tl_winpty_config);
5434 term->tl_winpty_config = NULL;
5435 if (winpty_err != NULL)
5436 {
5437 char_u *msg = utf16_to_enc(
5438 (short_u *)winpty_error_msg(winpty_err), NULL);
5439
5440 EMSG(msg);
5441 winpty_error_free(winpty_err);
5442 }
5443 return FAIL;
5444}
5445
5446 static int
5447create_pty_only(term_T *term, jobopt_T *options)
5448{
5449 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5450 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5451 char in_name[80], out_name[80];
5452 channel_T *channel = NULL;
5453
5454 create_vterm(term, term->tl_rows, term->tl_cols);
5455
5456 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5457 GetCurrentProcessId(),
5458 curbuf->b_fnum);
5459 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5460 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5461 PIPE_UNLIMITED_INSTANCES,
5462 0, 0, NMPWAIT_NOWAIT, NULL);
5463 if (hPipeIn == INVALID_HANDLE_VALUE)
5464 goto failed;
5465
5466 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5467 GetCurrentProcessId(),
5468 curbuf->b_fnum);
5469 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5470 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5471 PIPE_UNLIMITED_INSTANCES,
5472 0, 0, 0, NULL);
5473 if (hPipeOut == INVALID_HANDLE_VALUE)
5474 goto failed;
5475
5476 ConnectNamedPipe(hPipeIn, NULL);
5477 ConnectNamedPipe(hPipeOut, NULL);
5478
5479 term->tl_job = job_alloc();
5480 if (term->tl_job == NULL)
5481 goto failed;
5482 ++term->tl_job->jv_refcount;
5483
5484 /* behave like the job is already finished */
5485 term->tl_job->jv_status = JOB_FINISHED;
5486
5487 channel = add_channel();
5488 if (channel == NULL)
5489 goto failed;
5490 term->tl_job->jv_channel = channel;
5491 channel->ch_keep_open = TRUE;
5492 channel->ch_named_pipe = TRUE;
5493
5494 channel_set_pipes(channel,
5495 (sock_T)hPipeIn,
5496 (sock_T)hPipeOut,
5497 (sock_T)hPipeOut);
5498 channel_set_job(channel, term->tl_job, options);
5499 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5500 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5501
5502 return OK;
5503
5504failed:
5505 if (hPipeIn != NULL)
5506 CloseHandle(hPipeIn);
5507 if (hPipeOut != NULL)
5508 CloseHandle(hPipeOut);
5509 return FAIL;
5510}
5511
5512/*
5513 * Free the terminal emulator part of "term".
5514 */
5515 static void
5516term_free_vterm(term_T *term)
5517{
5518 if (term->tl_winpty != NULL)
5519 winpty_free(term->tl_winpty);
5520 term->tl_winpty = NULL;
5521 if (term->tl_winpty_config != NULL)
5522 winpty_config_free(term->tl_winpty_config);
5523 term->tl_winpty_config = NULL;
5524 if (term->tl_vterm != NULL)
5525 vterm_free(term->tl_vterm);
5526 term->tl_vterm = NULL;
5527}
5528
5529/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005530 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005531 */
5532 static void
5533term_report_winsize(term_T *term, int rows, int cols)
5534{
5535 if (term->tl_winpty)
5536 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5537}
5538
5539 int
5540terminal_enabled(void)
5541{
5542 return dyn_winpty_init(FALSE) == OK;
5543}
5544
5545# else
5546
5547/**************************************
5548 * 3. Unix-like implementation.
5549 */
5550
5551/*
5552 * Create a new terminal of "rows" by "cols" cells.
5553 * Start job for "cmd".
5554 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005555 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005556 * Return OK or FAIL.
5557 */
5558 static int
5559term_and_job_init(
5560 term_T *term,
5561 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005562 char **argv,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005563 jobopt_T *opt)
5564{
5565 create_vterm(term, term->tl_rows, term->tl_cols);
5566
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005567#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5568 if (opt->jo_set2 & JO2_ANSI_COLORS)
5569 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5570 else
5571 init_vterm_ansi_colors(term->tl_vterm);
5572#endif
5573
Bram Moolenaar13568252018-03-16 20:46:58 +01005574 /* This may change a string in "argvar". */
5575 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005576 if (term->tl_job != NULL)
5577 ++term->tl_job->jv_refcount;
5578
5579 return term->tl_job != NULL
5580 && term->tl_job->jv_channel != NULL
5581 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5582}
5583
5584 static int
5585create_pty_only(term_T *term, jobopt_T *opt)
5586{
5587 create_vterm(term, term->tl_rows, term->tl_cols);
5588
5589 term->tl_job = job_alloc();
5590 if (term->tl_job == NULL)
5591 return FAIL;
5592 ++term->tl_job->jv_refcount;
5593
5594 /* behave like the job is already finished */
5595 term->tl_job->jv_status = JOB_FINISHED;
5596
5597 return mch_create_pty_channel(term->tl_job, opt);
5598}
5599
5600/*
5601 * Free the terminal emulator part of "term".
5602 */
5603 static void
5604term_free_vterm(term_T *term)
5605{
5606 if (term->tl_vterm != NULL)
5607 vterm_free(term->tl_vterm);
5608 term->tl_vterm = NULL;
5609}
5610
5611/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005612 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005613 */
5614 static void
5615term_report_winsize(term_T *term, int rows, int cols)
5616{
5617 /* Use an ioctl() to report the new window size to the job. */
5618 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5619 {
5620 int fd = -1;
5621 int part;
5622
5623 for (part = PART_OUT; part < PART_COUNT; ++part)
5624 {
5625 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5626 if (isatty(fd))
5627 break;
5628 }
5629 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5630 mch_signal_job(term->tl_job, (char_u *)"winch");
5631 }
5632}
5633
5634# endif
5635
5636#endif /* FEAT_TERMINAL */