blob: 4f2b8bb25caf4b41d1d8ed927cb1a3a5b04942fc [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.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020039 */
40
41#include "vim.h"
42
43#if defined(FEAT_TERMINAL) || defined(PROTO)
44
45#ifndef MIN
46# define MIN(x,y) ((x) < (y) ? (x) : (y))
47#endif
48#ifndef MAX
49# define MAX(x,y) ((x) > (y) ? (x) : (y))
50#endif
51
52#include "libvterm/include/vterm.h"
53
54/* This is VTermScreenCell without the characters, thus much smaller. */
55typedef struct {
56 VTermScreenCellAttrs attrs;
57 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010058 VTermColor fg;
59 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060} cellattr_T;
61
62typedef struct sb_line_S {
Bram Moolenaar29ae2232019-02-14 21:22:01 +010063 int sb_cols; // can differ per line
64 cellattr_T *sb_cells; // allocated
65 cellattr_T sb_fill_attr; // for short line
66 char_u *sb_text; // for tl_scrollback_postponed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067} sb_line_T;
68
Bram Moolenaar4f974752019-02-17 17:44:42 +010069#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +010070# ifndef HPCON
71# define HPCON VOID*
72# endif
73# ifndef EXTENDED_STARTUPINFO_PRESENT
74# define EXTENDED_STARTUPINFO_PRESENT 0x00080000
75# endif
76# ifndef PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE
77# define PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE 0x00020016
78# endif
79typedef struct _DYN_STARTUPINFOEXW
80{
81 STARTUPINFOW StartupInfo;
82 LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
83} DYN_STARTUPINFOEXW, *PDYN_STARTUPINFOEXW;
84#endif
85
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020086/* typedef term_T in structs.h */
87struct terminal_S {
88 term_T *tl_next;
89
90 VTerm *tl_vterm;
91 job_T *tl_job;
92 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010093#if defined(FEAT_GUI)
94 int tl_system; /* when non-zero used for :!cmd output */
95 int tl_toprow; /* row with first line of system terminal */
96#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
98 /* Set when setting the size of a vterm, reset after redrawing. */
99 int tl_vterm_size_changed;
100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200101 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
102 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200103 int tl_channel_recently_closed; // still need to handle tl_finish
104
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100105 int tl_finish;
106#define TL_FINISH_UNSET NUL
107#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
108#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
109#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200110 char_u *tl_opencmd;
111 char_u *tl_eof_chars;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200112 char_u *tl_api; // prefix for terminal API function
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100114 char_u *tl_arg0_cmd; // To format the status bar
115
Bram Moolenaar4f974752019-02-17 17:44:42 +0100116#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100120 HPCON tl_conpty;
121 DYN_STARTUPINFOEXW tl_siex; // Structure that always needs to be hold
122
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200123 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200124#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100125#if defined(FEAT_SESSION)
126 char_u *tl_command;
127#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100128 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200129
130 /* last known vterm size */
131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
134 char_u *tl_title; /* NULL or allocated */
135 char_u *tl_status_text; /* NULL or allocated */
136
137 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200138 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200139 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200140 int tl_dirty_snapshot; /* text updated after making snapshot */
141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200145 int tl_postponed_scroll; /* to be scrolled up */
146
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200147 garray_T tl_scrollback;
148 int tl_scrollback_scrolled;
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100149 garray_T tl_scrollback_postponed;
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 cellattr_T tl_default_color;
152
Bram Moolenaard96ff162018-02-18 22:13:29 +0100153 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
154 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
155
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
Bram Moolenaar4f974752019-02-17 17:44:42 +0100176#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100177static BOOL has_winpty = FALSE;
178static BOOL has_conpty = FALSE;
179#endif
180
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200181#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
182#define KEY_BUF_LEN 200
183
184/*
185 * Functions with separate implementation for MS-Windows and Unix-like systems.
186 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200187static int term_and_job_init(term_T *term, typval_T *argvar, char **argv, jobopt_T *opt, jobopt_T *orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188static int create_pty_only(term_T *term, jobopt_T *opt);
189static void term_report_winsize(term_T *term, int rows, int cols);
190static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100191#ifdef FEAT_GUI
192static void update_system_term(term_T *term);
193#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100195static void handle_postponed_scrollback(term_T *term);
196
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100197/* The character that we know (or assume) that the terminal expects for the
198 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200200
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100201/* "Terminal" highlight group colors. */
202static int term_default_cterm_fg = -1;
203static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204
Bram Moolenaard317b382018-02-08 22:33:31 +0100205/* Store the last set and the desired cursor properties, so that we only update
206 * them when needed. Doing it unnecessary may result in flicker. */
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200207static char_u *last_set_cursor_color = NULL;
208static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100209static int last_set_cursor_shape = -1;
210static int desired_cursor_shape = -1;
211static int last_set_cursor_blink = -1;
212static int desired_cursor_blink = -1;
213
214
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200215/**************************************
216 * 1. Generic code for all systems.
217 */
218
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200219 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200220cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
221{
222 if (lhs_color != NULL && rhs_color != NULL)
223 return STRCMP(lhs_color, rhs_color) == 0;
224 return lhs_color == NULL && rhs_color == NULL;
225}
226
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200227 static void
228cursor_color_copy(char_u **to_color, char_u *from_color)
229{
230 // Avoid a free & alloc if the value is already right.
231 if (cursor_color_equal(*to_color, from_color))
232 return;
233 vim_free(*to_color);
234 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
235}
236
237 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200238cursor_color_get(char_u *color)
239{
240 return (color == NULL) ? (char_u *)"" : color;
241}
242
243
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200244/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200245 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200246 * current window.
247 * Sets "rows" and/or "cols" to zero when it should follow the window size.
248 * Return TRUE if the size is the minimum size: "24*80".
249 */
250 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200251parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200252{
253 int minsize = FALSE;
254
255 *rows = 0;
256 *cols = 0;
257
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200258 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200259 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200260 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200261
262 /* Syntax of value was already checked when it's set. */
263 if (p == NULL)
264 {
265 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200266 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200268 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200269 *cols = atoi((char *)p + 1);
270 }
271 return minsize;
272}
273
274/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200275 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200276 */
277 static void
278set_term_and_win_size(term_T *term)
279{
Bram Moolenaar13568252018-03-16 20:46:58 +0100280#ifdef FEAT_GUI
281 if (term->tl_system)
282 {
283 /* Use the whole screen for the system command. However, it will start
284 * at the command line and scroll up as needed, using tl_toprow. */
285 term->tl_rows = Rows;
286 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200287 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100288 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100289#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200290 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200291 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200292 if (term->tl_rows != 0)
293 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
294 if (term->tl_cols != 0)
295 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 }
297 if (term->tl_rows == 0)
298 term->tl_rows = curwin->w_height;
299 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200301 if (term->tl_cols == 0)
302 term->tl_cols = curwin->w_width;
303 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305}
306
307/*
308 * Initialize job options for a terminal job.
309 * Caller may overrule some of them.
310 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100311 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200312init_job_options(jobopt_T *opt)
313{
314 clear_job_options(opt);
315
316 opt->jo_mode = MODE_RAW;
317 opt->jo_out_mode = MODE_RAW;
318 opt->jo_err_mode = MODE_RAW;
319 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
320}
321
322/*
323 * Set job options mandatory for a terminal job.
324 */
325 static void
326setup_job_options(jobopt_T *opt, int rows, int cols)
327{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100328#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200329 /* Win32: Redirecting the job output won't work, thus always connect stdout
330 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200331 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200332#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200333 {
334 /* Connect stdout to the terminal. */
335 opt->jo_io[PART_OUT] = JIO_BUFFER;
336 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
337 opt->jo_modifiable[PART_OUT] = 0;
338 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
339 }
340
Bram Moolenaar4f974752019-02-17 17:44:42 +0100341#ifndef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200342 /* Win32: Redirecting the job output won't work, thus always connect stderr
343 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200344 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200345#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346 {
347 /* Connect stderr to the terminal. */
348 opt->jo_io[PART_ERR] = JIO_BUFFER;
349 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
350 opt->jo_modifiable[PART_ERR] = 0;
351 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
352 }
353
354 opt->jo_pty = TRUE;
355 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
356 opt->jo_term_rows = rows;
357 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
358 opt->jo_term_cols = cols;
359}
360
361/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200362 * Flush messages on channels.
363 */
364 static void
365term_flush_messages()
366{
367 mch_check_messages();
368 parse_queued_messages();
369}
370
371/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100372 * Close a terminal buffer (and its window). Used when creating the terminal
373 * fails.
374 */
375 static void
376term_close_buffer(buf_T *buf, buf_T *old_curbuf)
377{
378 free_terminal(buf);
379 if (old_curbuf != NULL)
380 {
381 --curbuf->b_nwindows;
382 curbuf = old_curbuf;
383 curwin->w_buffer = curbuf;
384 ++curbuf->b_nwindows;
385 }
386
387 /* Wiping out the buffer will also close the window and call
388 * free_terminal(). */
389 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
390}
391
392/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200393 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100394 * Use either "argvar" or "argv", the other must be NULL.
395 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
396 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 * Returns NULL when failed.
398 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 buf_T *
400term_start(
401 typval_T *argvar,
402 char **argv,
403 jobopt_T *opt,
404 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200405{
406 exarg_T split_ea;
407 win_T *old_curwin = curwin;
408 term_T *term;
409 buf_T *old_curbuf = NULL;
410 int res;
411 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100412 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200413 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200414
415 if (check_restricted() || check_secure())
416 return NULL;
417
418 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
419 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
420 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
421 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
422 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100423 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200424 return NULL;
425 }
426
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200427 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200428 if (term == NULL)
429 return NULL;
430 term->tl_dirty_row_end = MAX_ROW;
431 term->tl_cursor_visible = TRUE;
432 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
433 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100434#ifdef FEAT_GUI
435 term->tl_system = (flags & TERM_START_SYSTEM);
436#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100438 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200439
440 vim_memset(&split_ea, 0, sizeof(split_ea));
441 if (opt->jo_curwin)
442 {
443 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100444 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200445 {
446 no_write_message();
447 vim_free(term);
448 return NULL;
449 }
450 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100451 ECMD_HIDE
452 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
453 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200454 {
455 vim_free(term);
456 return NULL;
457 }
458 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100459 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200460 {
461 buf_T *buf;
462
463 /* Create a new buffer without a window. Make it the current buffer for
464 * a moment to be able to do the initialisations. */
465 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
466 BLN_NEW | BLN_LISTED);
467 if (buf == NULL || ml_open(buf) == FAIL)
468 {
469 vim_free(term);
470 return NULL;
471 }
472 old_curbuf = curbuf;
473 --curbuf->b_nwindows;
474 curbuf = buf;
475 curwin->w_buffer = buf;
476 ++curbuf->b_nwindows;
477 }
478 else
479 {
480 /* Open a new window or tab. */
481 split_ea.cmdidx = CMD_new;
482 split_ea.cmd = (char_u *)"new";
483 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100484 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200485 {
486 split_ea.line2 = opt->jo_term_rows;
487 split_ea.addr_count = 1;
488 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100489 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200490 {
491 split_ea.line2 = opt->jo_term_cols;
492 split_ea.addr_count = 1;
493 }
494
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100495 if (vertical)
496 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200497 ex_splitview(&split_ea);
498 if (curwin == old_curwin)
499 {
500 /* split failed */
501 vim_free(term);
502 return NULL;
503 }
504 }
505 term->tl_buffer = curbuf;
506 curbuf->b_term = term;
507
508 if (!opt->jo_hidden)
509 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100510 /* Only one size was taken care of with :new, do the other one. With
511 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100512 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200513 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100514 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 win_setwidth(opt->jo_term_cols);
516 }
517
518 /* Link the new terminal in the list of active terminals. */
519 term->tl_next = first_term;
520 first_term = term;
521
522 if (opt->jo_term_name != NULL)
523 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100524 else if (argv != NULL)
525 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 else
527 {
528 int i;
529 size_t len;
530 char_u *cmd, *p;
531
532 if (argvar->v_type == VAR_STRING)
533 {
534 cmd = argvar->vval.v_string;
535 if (cmd == NULL)
536 cmd = (char_u *)"";
537 else if (STRCMP(cmd, "NONE") == 0)
538 cmd = (char_u *)"pty";
539 }
540 else if (argvar->v_type != VAR_LIST
541 || argvar->vval.v_list == NULL
542 || argvar->vval.v_list->lv_len < 1
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100543 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200544 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
545 cmd = (char_u*)"";
546
547 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200548 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200549
550 for (i = 0; p != NULL; ++i)
551 {
552 /* Prepend a ! to the command name to avoid the buffer name equals
553 * the executable, otherwise ":w!" would overwrite it. */
554 if (i == 0)
555 vim_snprintf((char *)p, len, "!%s", cmd);
556 else
557 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
558 if (buflist_findname(p) == NULL)
559 {
560 vim_free(curbuf->b_ffname);
561 curbuf->b_ffname = p;
562 break;
563 }
564 }
565 }
566 curbuf->b_fname = curbuf->b_ffname;
567
568 if (opt->jo_term_opencmd != NULL)
569 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
570
571 if (opt->jo_eof_chars != NULL)
572 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
573
574 set_string_option_direct((char_u *)"buftype", -1,
575 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200576 // Avoid that 'buftype' is reset when this buffer is entered.
577 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200578
579 /* Mark the buffer as not modifiable. It can only be made modifiable after
580 * the job finished. */
581 curbuf->b_p_ma = FALSE;
582
583 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100584#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200585 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
586#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200587 setup_job_options(opt, term->tl_rows, term->tl_cols);
588
Bram Moolenaar13568252018-03-16 20:46:58 +0100589 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100590 return curbuf;
591
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100592#if defined(FEAT_SESSION)
593 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100594 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100595 {
596 term->tl_command = vim_strsave((char_u *)"NONE");
597 }
598 else if (argvar->v_type == VAR_STRING)
599 {
600 char_u *cmd = argvar->vval.v_string;
601
602 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
603 term->tl_command = vim_strsave(cmd);
604 }
605 else if (argvar->v_type == VAR_LIST
606 && argvar->vval.v_list != NULL
607 && argvar->vval.v_list->lv_len > 0)
608 {
609 garray_T ga;
610 listitem_T *item;
611
612 ga_init2(&ga, 1, 100);
613 for (item = argvar->vval.v_list->lv_first;
614 item != NULL; item = item->li_next)
615 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100616 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100617 char_u *p;
618
619 if (s == NULL)
620 break;
621 p = vim_strsave_fnameescape(s, FALSE);
622 if (p == NULL)
623 break;
624 ga_concat(&ga, p);
625 vim_free(p);
626 ga_append(&ga, ' ');
627 }
628 if (item == NULL)
629 {
630 ga_append(&ga, NUL);
631 term->tl_command = ga.ga_data;
632 }
633 else
634 ga_clear(&ga);
635 }
636#endif
637
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100638 if (opt->jo_term_kill != NULL)
639 {
640 char_u *p = skiptowhite(opt->jo_term_kill);
641
642 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
643 }
644
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200645 if (opt->jo_term_api != NULL)
646 term->tl_api = vim_strsave(opt->jo_term_api);
647 else
648 term->tl_api = vim_strsave((char_u *)"Tapi_");
649
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200650 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100651 if (argv == NULL
652 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200653 && argvar->vval.v_string != NULL
654 && STRCMP(argvar->vval.v_string, "NONE") == 0)
655 res = create_pty_only(term, opt);
656 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200657 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200658
659 newbuf = curbuf;
660 if (res == OK)
661 {
662 /* Get and remember the size we ended up with. Update the pty. */
663 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
664 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100665#ifdef FEAT_GUI
666 if (term->tl_system)
667 {
668 /* display first line below typed command */
669 term->tl_toprow = msg_row + 1;
670 term->tl_dirty_row_end = 0;
671 }
672#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200673
674 /* Make sure we don't get stuck on sending keys to the job, it leads to
675 * a deadlock if the job is waiting for Vim to read. */
676 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
677
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200678 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200679 {
680 --curbuf->b_nwindows;
681 curbuf = old_curbuf;
682 curwin->w_buffer = curbuf;
683 ++curbuf->b_nwindows;
684 }
685 }
686 else
687 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100688 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200689 return NULL;
690 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100691
Bram Moolenaar13568252018-03-16 20:46:58 +0100692 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200693 return newbuf;
694}
695
696/*
697 * ":terminal": open a terminal window and execute a job in it.
698 */
699 void
700ex_terminal(exarg_T *eap)
701{
702 typval_T argvar[2];
703 jobopt_T opt;
704 char_u *cmd;
705 char_u *tofree = NULL;
706
707 init_job_options(&opt);
708
709 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100710 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200711 {
712 char_u *p, *ep;
713
714 cmd += 2;
715 p = skiptowhite(cmd);
716 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200717 if (ep != NULL)
718 {
719 if (ep < p)
720 p = ep;
721 else
722 ep = NULL;
723 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200724
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200725# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
726 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
727 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200728 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200729 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100730 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200731 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200735 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100738 opt.jo_term_norestore = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100740 {
741 opt.jo_set2 |= JO2_TERM_KILL;
742 opt.jo_term_kill = ep + 1;
743 p = skiptowhite(cmd);
744 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 else if (OPTARG_HAS("api"))
746 {
747 opt.jo_set2 |= JO2_TERM_API;
748 if (ep != NULL)
749 {
750 opt.jo_term_api = ep + 1;
751 p = skiptowhite(cmd);
752 }
753 else
754 opt.jo_term_api = NULL;
755 }
756 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200757 {
758 opt.jo_set2 |= JO2_TERM_ROWS;
759 opt.jo_term_rows = atoi((char *)ep + 1);
760 p = skiptowhite(cmd);
761 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200762 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200763 {
764 opt.jo_set2 |= JO2_TERM_COLS;
765 opt.jo_term_cols = atoi((char *)ep + 1);
766 p = skiptowhite(cmd);
767 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200768 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200769 {
770 char_u *buf = NULL;
771 char_u *keys;
772
773 p = skiptowhite(cmd);
774 *p = NUL;
775 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
776 opt.jo_set2 |= JO2_EOF_CHARS;
777 opt.jo_eof_chars = vim_strsave(keys);
778 vim_free(buf);
779 *p = ' ';
780 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100781#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100782 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
783 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100784 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100785 int tty_type = NUL;
786
787 p = skiptowhite(cmd);
788 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
789 tty_type = 'w';
790 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
791 tty_type = 'c';
792 else
793 {
794 semsg(e_invargval, "type");
795 goto theend;
796 }
797 opt.jo_set2 |= JO2_TTY_TYPE;
798 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100799 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100800#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200801 else
802 {
803 if (*p)
804 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100805 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100806 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200808# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200809 cmd = skipwhite(p);
810 }
811 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100812 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 /* Make a copy of 'shell', an autocommand may change the option. */
814 tofree = cmd = vim_strsave(p_sh);
815
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100816 /* default to close when the shell exits */
817 if (opt.jo_term_finish == NUL)
818 opt.jo_term_finish = 'c';
819 }
820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 if (eap->addr_count > 0)
822 {
823 /* Write lines from current buffer to the job. */
824 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
825 opt.jo_io[PART_IN] = JIO_BUFFER;
826 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
827 opt.jo_in_top = eap->line1;
828 opt.jo_in_bot = eap->line2;
829 }
830
831 argvar[0].v_type = VAR_STRING;
832 argvar[0].vval.v_string = cmd;
833 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100834 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200835 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100836
837theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 vim_free(opt.jo_eof_chars);
839}
840
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100841#if defined(FEAT_SESSION) || defined(PROTO)
842/*
843 * Write a :terminal command to the session file to restore the terminal in
844 * window "wp".
845 * Return FAIL if writing fails.
846 */
847 int
848term_write_session(FILE *fd, win_T *wp)
849{
850 term_T *term = wp->w_buffer->b_term;
851
852 /* Create the terminal and run the command. This is not without
853 * risk, but let's assume the user only creates a session when this
854 * will be OK. */
855 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
856 term->tl_cols, term->tl_rows) < 0)
857 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100858#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100859 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
860 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100861#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100862 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
863 return FAIL;
864
865 return put_eol(fd);
866}
867
868/*
869 * Return TRUE if "buf" has a terminal that should be restored.
870 */
871 int
872term_should_restore(buf_T *buf)
873{
874 term_T *term = buf->b_term;
875
876 return term != NULL && (term->tl_command == NULL
877 || STRCMP(term->tl_command, "NONE") != 0);
878}
879#endif
880
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200881/*
882 * Free the scrollback buffer for "term".
883 */
884 static void
885free_scrollback(term_T *term)
886{
887 int i;
888
889 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
890 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
891 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100892 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
893 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
894 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200895}
896
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100897
898// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200899static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901/*
902 * Free a terminal and everything it refers to.
903 * Kills the job if there is one.
904 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100905 * The actual terminal structure is freed later in free_unused_terminals(),
906 * because callbacks may wipe out a buffer while the terminal is still
907 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200908 */
909 void
910free_terminal(buf_T *buf)
911{
912 term_T *term = buf->b_term;
913 term_T *tp;
914
915 if (term == NULL)
916 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100917
918 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200919 if (first_term == term)
920 first_term = term->tl_next;
921 else
922 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
923 if (tp->tl_next == term)
924 {
925 tp->tl_next = term->tl_next;
926 break;
927 }
928
929 if (term->tl_job != NULL)
930 {
931 if (term->tl_job->jv_status != JOB_ENDED
932 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100933 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200934 job_stop(term->tl_job, NULL, "kill");
935 job_unref(term->tl_job);
936 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100937 term->tl_next = terminals_to_free;
938 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200939
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200940 buf->b_term = NULL;
941 if (in_terminal_loop == term)
942 in_terminal_loop = NULL;
943}
944
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100945 void
946free_unused_terminals()
947{
948 while (terminals_to_free != NULL)
949 {
950 term_T *term = terminals_to_free;
951
952 terminals_to_free = term->tl_next;
953
954 free_scrollback(term);
955
956 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200957 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100958 vim_free(term->tl_title);
959#ifdef FEAT_SESSION
960 vim_free(term->tl_command);
961#endif
962 vim_free(term->tl_kill);
963 vim_free(term->tl_status_text);
964 vim_free(term->tl_opencmd);
965 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100966 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100967#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100968 if (term->tl_out_fd != NULL)
969 fclose(term->tl_out_fd);
970#endif
971 vim_free(term->tl_cursor_color);
972 vim_free(term);
973 }
974}
975
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200976/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100977 * Get the part that is connected to the tty. Normally this is PART_IN, but
978 * when writing buffer lines to the job it can be another. This makes it
979 * possible to do "1,5term vim -".
980 */
981 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200982get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100983{
984#ifdef UNIX
985 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
986 int i;
987
988 for (i = 0; i < 3; ++i)
989 {
990 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
991
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100992 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100993 return parts[i];
994 }
995#endif
996 return PART_IN;
997}
998
999/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001000 * Write job output "msg[len]" to the vterm.
1001 */
1002 static void
1003term_write_job_output(term_T *term, char_u *msg, size_t len)
1004{
1005 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001006 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001007
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001008 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001009
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001010 /* flush vterm buffer when vterm responded to control sequence */
1011 if (prevlen != vterm_output_get_buffer_current(vterm))
1012 {
1013 char buf[KEY_BUF_LEN];
1014 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1015
1016 if (curlen > 0)
1017 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1018 (char_u *)buf, (int)curlen, NULL);
1019 }
1020
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001021 /* this invokes the damage callbacks */
1022 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1023}
1024
1025 static void
1026update_cursor(term_T *term, int redraw)
1027{
1028 if (term->tl_normal_mode)
1029 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001030#ifdef FEAT_GUI
1031 if (term->tl_system)
1032 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1033 term->tl_cursor_pos.col);
1034 else
1035#endif
1036 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001037 if (redraw)
1038 {
1039 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1040 cursor_on();
1041 out_flush();
1042#ifdef FEAT_GUI
1043 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001044 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001045 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001046 gui_mch_flush();
1047 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001048#endif
1049 }
1050}
1051
1052/*
1053 * Invoked when "msg" output from a job was received. Write it to the terminal
1054 * of "buffer".
1055 */
1056 void
1057write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1058{
1059 size_t len = STRLEN(msg);
1060 term_T *term = buffer->b_term;
1061
Bram Moolenaar4f974752019-02-17 17:44:42 +01001062#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001063 /* Win32: Cannot redirect output of the job, intercept it here and write to
1064 * the file. */
1065 if (term->tl_out_fd != NULL)
1066 {
1067 ch_log(channel, "Writing %d bytes to output file", (int)len);
1068 fwrite(msg, len, 1, term->tl_out_fd);
1069 return;
1070 }
1071#endif
1072
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001073 if (term->tl_vterm == NULL)
1074 {
1075 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1076 return;
1077 }
1078 ch_log(channel, "writing %d bytes to terminal", (int)len);
1079 term_write_job_output(term, msg, len);
1080
Bram Moolenaar13568252018-03-16 20:46:58 +01001081#ifdef FEAT_GUI
1082 if (term->tl_system)
1083 {
1084 /* show system output, scrolling up the screen as needed */
1085 update_system_term(term);
1086 update_cursor(term, TRUE);
1087 }
1088 else
1089#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001090 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1091 * contents, thus no screen update is needed. */
1092 if (!term->tl_normal_mode)
1093 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001094 // Don't use update_screen() when editing the command line, it gets
1095 // cleared.
1096 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001097 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001098 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001099 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001100 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001101 /* update_screen() can be slow, check the terminal wasn't closed
1102 * already */
1103 if (buffer == curbuf && curbuf->b_term != NULL)
1104 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001105 }
1106 else
1107 redraw_after_callback(TRUE);
1108 }
1109}
1110
1111/*
1112 * Send a mouse position and click to the vterm
1113 */
1114 static int
1115term_send_mouse(VTerm *vterm, int button, int pressed)
1116{
1117 VTermModifier mod = VTERM_MOD_NONE;
1118
1119 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001120 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001121 if (button != 0)
1122 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001123 return TRUE;
1124}
1125
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001126static int enter_mouse_col = -1;
1127static int enter_mouse_row = -1;
1128
1129/*
1130 * Handle a mouse click, drag or release.
1131 * Return TRUE when a mouse event is sent to the terminal.
1132 */
1133 static int
1134term_mouse_click(VTerm *vterm, int key)
1135{
1136#if defined(FEAT_CLIPBOARD)
1137 /* For modeless selection mouse drag and release events are ignored, unless
1138 * they are preceded with a mouse down event */
1139 static int ignore_drag_release = TRUE;
1140 VTermMouseState mouse_state;
1141
1142 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1143 if (mouse_state.flags == 0)
1144 {
1145 /* Terminal is not using the mouse, use modeless selection. */
1146 switch (key)
1147 {
1148 case K_LEFTDRAG:
1149 case K_LEFTRELEASE:
1150 case K_RIGHTDRAG:
1151 case K_RIGHTRELEASE:
1152 /* Ignore drag and release events when the button-down wasn't
1153 * seen before. */
1154 if (ignore_drag_release)
1155 {
1156 int save_mouse_col, save_mouse_row;
1157
1158 if (enter_mouse_col < 0)
1159 break;
1160
1161 /* mouse click in the window gave us focus, handle that
1162 * click now */
1163 save_mouse_col = mouse_col;
1164 save_mouse_row = mouse_row;
1165 mouse_col = enter_mouse_col;
1166 mouse_row = enter_mouse_row;
1167 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1168 mouse_col = save_mouse_col;
1169 mouse_row = save_mouse_row;
1170 }
1171 /* FALLTHROUGH */
1172 case K_LEFTMOUSE:
1173 case K_RIGHTMOUSE:
1174 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1175 ignore_drag_release = TRUE;
1176 else
1177 ignore_drag_release = FALSE;
1178 /* Should we call mouse_has() here? */
1179 if (clip_star.available)
1180 {
1181 int button, is_click, is_drag;
1182
1183 button = get_mouse_button(KEY2TERMCAP1(key),
1184 &is_click, &is_drag);
1185 if (mouse_model_popup() && button == MOUSE_LEFT
1186 && (mod_mask & MOD_MASK_SHIFT))
1187 {
1188 /* Translate shift-left to right button. */
1189 button = MOUSE_RIGHT;
1190 mod_mask &= ~MOD_MASK_SHIFT;
1191 }
1192 clip_modeless(button, is_click, is_drag);
1193 }
1194 break;
1195
1196 case K_MIDDLEMOUSE:
1197 if (clip_star.available)
1198 insert_reg('*', TRUE);
1199 break;
1200 }
1201 enter_mouse_col = -1;
1202 return FALSE;
1203 }
1204#endif
1205 enter_mouse_col = -1;
1206
1207 switch (key)
1208 {
1209 case K_LEFTMOUSE:
1210 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1211 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1212 case K_LEFTRELEASE:
1213 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1214 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1215 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1216 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1217 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1218 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1219 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1220 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1221 }
1222 return TRUE;
1223}
1224
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001225/*
1226 * Convert typed key "c" into bytes to send to the job.
1227 * Return the number of bytes in "buf".
1228 */
1229 static int
1230term_convert_key(term_T *term, int c, char *buf)
1231{
1232 VTerm *vterm = term->tl_vterm;
1233 VTermKey key = VTERM_KEY_NONE;
1234 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001235 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001236
1237 switch (c)
1238 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001239 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1240
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001241 /* don't use VTERM_KEY_BACKSPACE, it always
1242 * becomes 0x7f DEL */
1243 case K_BS: c = term_backspace_char; break;
1244
1245 case ESC: key = VTERM_KEY_ESCAPE; break;
1246 case K_DEL: key = VTERM_KEY_DEL; break;
1247 case K_DOWN: key = VTERM_KEY_DOWN; break;
1248 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1249 key = VTERM_KEY_DOWN; break;
1250 case K_END: key = VTERM_KEY_END; break;
1251 case K_S_END: mod = VTERM_MOD_SHIFT;
1252 key = VTERM_KEY_END; break;
1253 case K_C_END: mod = VTERM_MOD_CTRL;
1254 key = VTERM_KEY_END; break;
1255 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1256 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1257 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1258 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1259 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1260 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1261 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1262 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1263 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1264 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1265 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1266 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1267 case K_HOME: key = VTERM_KEY_HOME; break;
1268 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1269 key = VTERM_KEY_HOME; break;
1270 case K_C_HOME: mod = VTERM_MOD_CTRL;
1271 key = VTERM_KEY_HOME; break;
1272 case K_INS: key = VTERM_KEY_INS; break;
1273 case K_K0: key = VTERM_KEY_KP_0; break;
1274 case K_K1: key = VTERM_KEY_KP_1; break;
1275 case K_K2: key = VTERM_KEY_KP_2; break;
1276 case K_K3: key = VTERM_KEY_KP_3; break;
1277 case K_K4: key = VTERM_KEY_KP_4; break;
1278 case K_K5: key = VTERM_KEY_KP_5; break;
1279 case K_K6: key = VTERM_KEY_KP_6; break;
1280 case K_K7: key = VTERM_KEY_KP_7; break;
1281 case K_K8: key = VTERM_KEY_KP_8; break;
1282 case K_K9: key = VTERM_KEY_KP_9; break;
1283 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1284 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1285 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1286 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1287 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1288 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1289 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1290 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1291 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1292 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1293 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1294 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1295 case K_LEFT: key = VTERM_KEY_LEFT; break;
1296 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1297 key = VTERM_KEY_LEFT; break;
1298 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1299 key = VTERM_KEY_LEFT; break;
1300 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1301 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1302 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1303 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1304 key = VTERM_KEY_RIGHT; break;
1305 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1306 key = VTERM_KEY_RIGHT; break;
1307 case K_UP: key = VTERM_KEY_UP; break;
1308 case K_S_UP: mod = VTERM_MOD_SHIFT;
1309 key = VTERM_KEY_UP; break;
1310 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001311 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1312 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001313
Bram Moolenaara42ad572017-11-16 13:08:04 +01001314 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1315 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001316 case K_MOUSELEFT: /* TODO */ return 0;
1317 case K_MOUSERIGHT: /* TODO */ return 0;
1318
1319 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001320 case K_LEFTMOUSE_NM:
1321 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001322 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001323 case K_LEFTRELEASE_NM:
1324 case K_MOUSEMOVE:
1325 case K_MIDDLEMOUSE:
1326 case K_MIDDLEDRAG:
1327 case K_MIDDLERELEASE:
1328 case K_RIGHTMOUSE:
1329 case K_RIGHTDRAG:
1330 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1331 return 0;
1332 other = TRUE;
1333 break;
1334
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001335 case K_X1MOUSE: /* TODO */ return 0;
1336 case K_X1DRAG: /* TODO */ return 0;
1337 case K_X1RELEASE: /* TODO */ return 0;
1338 case K_X2MOUSE: /* TODO */ return 0;
1339 case K_X2DRAG: /* TODO */ return 0;
1340 case K_X2RELEASE: /* TODO */ return 0;
1341
1342 case K_IGNORE: return 0;
1343 case K_NOP: return 0;
1344 case K_UNDO: return 0;
1345 case K_HELP: return 0;
1346 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1347 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1348 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1349 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1350 case K_SELECT: return 0;
1351#ifdef FEAT_GUI
1352 case K_VER_SCROLLBAR: return 0;
1353 case K_HOR_SCROLLBAR: return 0;
1354#endif
1355#ifdef FEAT_GUI_TABLINE
1356 case K_TABLINE: return 0;
1357 case K_TABMENU: return 0;
1358#endif
1359#ifdef FEAT_NETBEANS_INTG
1360 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1361#endif
1362#ifdef FEAT_DND
1363 case K_DROP: return 0;
1364#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001366 case K_PS: vterm_keyboard_start_paste(vterm);
1367 other = TRUE;
1368 break;
1369 case K_PE: vterm_keyboard_end_paste(vterm);
1370 other = TRUE;
1371 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001372 }
1373
1374 /*
1375 * Convert special keys to vterm keys:
1376 * - Write keys to vterm: vterm_keyboard_key()
1377 * - Write output to channel.
1378 * TODO: use mod_mask
1379 */
1380 if (key != VTERM_KEY_NONE)
1381 /* Special key, let vterm convert it. */
1382 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001383 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001384 /* Normal character, let vterm convert it. */
1385 vterm_keyboard_unichar(vterm, c, mod);
1386
1387 /* Read back the converted escape sequence. */
1388 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1389}
1390
1391/*
1392 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001393 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001394 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001395 */
1396 static int
1397term_job_running_check(term_T *term, int check_job_status)
1398{
1399 /* Also consider the job finished when the channel is closed, to avoid a
1400 * race condition when updating the title. */
1401 if (term != NULL
1402 && term->tl_job != NULL
1403 && channel_is_open(term->tl_job->jv_channel))
1404 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001405 job_T *job = term->tl_job;
1406
1407 // Careful: Checking the job status may invoked callbacks, which close
1408 // the buffer and terminate "term". However, "job" will not be freed
1409 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001410 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001411 job_status(job);
1412 return (job->jv_status == JOB_STARTED
1413 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001414 }
1415 return FALSE;
1416}
1417
1418/*
1419 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001420 */
1421 int
1422term_job_running(term_T *term)
1423{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001424 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001425}
1426
1427/*
1428 * Return TRUE if "term" has an active channel and used ":term NONE".
1429 */
1430 int
1431term_none_open(term_T *term)
1432{
1433 /* Also consider the job finished when the channel is closed, to avoid a
1434 * race condition when updating the title. */
1435 return term != NULL
1436 && term->tl_job != NULL
1437 && channel_is_open(term->tl_job->jv_channel)
1438 && term->tl_job->jv_channel->ch_keep_open;
1439}
1440
1441/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001442 * Used when exiting: kill the job in "buf" if so desired.
1443 * Return OK when the job finished.
1444 * Return FAIL when the job is still running.
1445 */
1446 int
1447term_try_stop_job(buf_T *buf)
1448{
1449 int count;
1450 char *how = (char *)buf->b_term->tl_kill;
1451
1452#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1453 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1454 {
1455 char_u buff[DIALOG_MSG_SIZE];
1456 int ret;
1457
1458 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1459 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1460 if (ret == VIM_YES)
1461 how = "kill";
1462 else if (ret == VIM_CANCEL)
1463 return FAIL;
1464 }
1465#endif
1466 if (how == NULL || *how == NUL)
1467 return FAIL;
1468
1469 job_stop(buf->b_term->tl_job, NULL, how);
1470
Bram Moolenaar9172d232019-01-29 23:06:54 +01001471 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001472 for (count = 0; count < 100; ++count)
1473 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001474 job_T *job;
1475
1476 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001477 if (!buf_valid(buf)
1478 || buf->b_term == NULL
1479 || buf->b_term->tl_job == NULL)
1480 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001481 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001482
Bram Moolenaar9172d232019-01-29 23:06:54 +01001483 // Call job_status() to update jv_status. It may cause the job to be
1484 // cleaned up but it won't be freed.
1485 job_status(job);
1486 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001487 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001488
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001489 ui_delay(10L, FALSE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001490 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001491 }
1492 return FAIL;
1493}
1494
1495/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001496 * Add the last line of the scrollback buffer to the buffer in the window.
1497 */
1498 static void
1499add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1500{
1501 buf_T *buf = term->tl_buffer;
1502 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1503 linenr_T lnum = buf->b_ml.ml_line_count;
1504
Bram Moolenaar4f974752019-02-17 17:44:42 +01001505#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001506 if (!enc_utf8 && enc_codepage > 0)
1507 {
1508 WCHAR *ret = NULL;
1509 int length = 0;
1510
1511 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1512 &ret, &length);
1513 if (ret != NULL)
1514 {
1515 WideCharToMultiByte_alloc(enc_codepage, 0,
1516 ret, length, (char **)&text, &len, 0, 0);
1517 vim_free(ret);
1518 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1519 vim_free(text);
1520 }
1521 }
1522 else
1523#endif
1524 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1525 if (empty)
1526 {
1527 /* Delete the empty line that was in the empty buffer. */
1528 curbuf = buf;
1529 ml_delete(1, FALSE);
1530 curbuf = curwin->w_buffer;
1531 }
1532}
1533
1534 static void
1535cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1536{
1537 attr->width = cell->width;
1538 attr->attrs = cell->attrs;
1539 attr->fg = cell->fg;
1540 attr->bg = cell->bg;
1541}
1542
1543 static int
1544equal_celattr(cellattr_T *a, cellattr_T *b)
1545{
1546 /* Comparing the colors should be sufficient. */
1547 return a->fg.red == b->fg.red
1548 && a->fg.green == b->fg.green
1549 && a->fg.blue == b->fg.blue
1550 && a->bg.red == b->bg.red
1551 && a->bg.green == b->bg.green
1552 && a->bg.blue == b->bg.blue;
1553}
1554
Bram Moolenaard96ff162018-02-18 22:13:29 +01001555/*
1556 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1557 * line at this position. Otherwise at the end.
1558 */
1559 static int
1560add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1561{
1562 if (ga_grow(&term->tl_scrollback, 1) == OK)
1563 {
1564 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1565 + term->tl_scrollback.ga_len;
1566
1567 if (lnum > 0)
1568 {
1569 int i;
1570
1571 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1572 {
1573 *line = *(line - 1);
1574 --line;
1575 }
1576 }
1577 line->sb_cols = 0;
1578 line->sb_cells = NULL;
1579 line->sb_fill_attr = *fill_attr;
1580 ++term->tl_scrollback.ga_len;
1581 return OK;
1582 }
1583 return FALSE;
1584}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001585
1586/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001587 * Remove the terminal contents from the scrollback and the buffer.
1588 * Used before adding a new scrollback line or updating the buffer for lines
1589 * displayed in the terminal.
1590 */
1591 static void
1592cleanup_scrollback(term_T *term)
1593{
1594 sb_line_T *line;
1595 garray_T *gap;
1596
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001597 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001598 gap = &term->tl_scrollback;
1599 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1600 && gap->ga_len > 0)
1601 {
1602 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1603 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1604 vim_free(line->sb_cells);
1605 --gap->ga_len;
1606 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001607 curbuf = curwin->w_buffer;
1608 if (curbuf == term->tl_buffer)
1609 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001610}
1611
1612/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001613 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001614 */
1615 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001616update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001617{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001618 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619 int len;
1620 int lines_skipped = 0;
1621 VTermPos pos;
1622 VTermScreenCell cell;
1623 cellattr_T fill_attr, new_fill_attr;
1624 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001625
1626 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1627 "Adding terminal window snapshot to buffer");
1628
1629 /* First remove the lines that were appended before, they might be
1630 * outdated. */
1631 cleanup_scrollback(term);
1632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001633 screen = vterm_obtain_screen(term->tl_vterm);
1634 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001635 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1636 {
1637 len = 0;
1638 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1639 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1640 && cell.chars[0] != NUL)
1641 {
1642 len = pos.col + 1;
1643 new_fill_attr = term->tl_default_color;
1644 }
1645 else
1646 /* Assume the last attr is the filler attr. */
1647 cell2cellattr(&cell, &new_fill_attr);
1648
1649 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1650 ++lines_skipped;
1651 else
1652 {
1653 while (lines_skipped > 0)
1654 {
1655 /* Line was skipped, add an empty line. */
1656 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001657 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001658 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001659 }
1660
1661 if (len == 0)
1662 p = NULL;
1663 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001664 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001665 if ((p != NULL || len == 0)
1666 && ga_grow(&term->tl_scrollback, 1) == OK)
1667 {
1668 garray_T ga;
1669 int width;
1670 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1671 + term->tl_scrollback.ga_len;
1672
1673 ga_init2(&ga, 1, 100);
1674 for (pos.col = 0; pos.col < len; pos.col += width)
1675 {
1676 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1677 {
1678 width = 1;
1679 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1680 if (ga_grow(&ga, 1) == OK)
1681 ga.ga_len += utf_char2bytes(' ',
1682 (char_u *)ga.ga_data + ga.ga_len);
1683 }
1684 else
1685 {
1686 width = cell.width;
1687
1688 cell2cellattr(&cell, &p[pos.col]);
1689
Bram Moolenaara79fd562018-12-20 20:47:32 +01001690 // Each character can be up to 6 bytes.
1691 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 {
1693 int i;
1694 int c;
1695
1696 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1697 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1698 (char_u *)ga.ga_data + ga.ga_len);
1699 }
1700 }
1701 }
1702 line->sb_cols = len;
1703 line->sb_cells = p;
1704 line->sb_fill_attr = new_fill_attr;
1705 fill_attr = new_fill_attr;
1706 ++term->tl_scrollback.ga_len;
1707
1708 if (ga_grow(&ga, 1) == FAIL)
1709 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1710 else
1711 {
1712 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1713 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1714 }
1715 ga_clear(&ga);
1716 }
1717 else
1718 vim_free(p);
1719 }
1720 }
1721
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001722 // Add trailing empty lines.
1723 for (pos.row = term->tl_scrollback.ga_len;
1724 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1725 ++pos.row)
1726 {
1727 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1728 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1729 }
1730
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001731 term->tl_dirty_snapshot = FALSE;
1732#ifdef FEAT_TIMERS
1733 term->tl_timer_set = FALSE;
1734#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001735}
1736
1737/*
1738 * If needed, add the current lines of the terminal to scrollback and to the
1739 * buffer. Called after the job has ended and when switching to
1740 * Terminal-Normal mode.
1741 * When "redraw" is TRUE redraw the windows that show the terminal.
1742 */
1743 static void
1744may_move_terminal_to_buffer(term_T *term, int redraw)
1745{
1746 win_T *wp;
1747
1748 if (term->tl_vterm == NULL)
1749 return;
1750
1751 /* Update the snapshot only if something changes or the buffer does not
1752 * have all the lines. */
1753 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1754 <= term->tl_scrollback_scrolled)
1755 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001756
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757 /* Obtain the current background color. */
1758 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1759 &term->tl_default_color.fg, &term->tl_default_color.bg);
1760
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001761 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001762 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001763 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001764 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001765 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001766 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1767 wp->w_cursor.col = 0;
1768 wp->w_valid = 0;
1769 if (wp->w_cursor.lnum >= wp->w_height)
1770 {
1771 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001773 if (wp->w_topline < min_topline)
1774 wp->w_topline = min_topline;
1775 }
1776 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001777 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001778 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001779}
1780
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001781#if defined(FEAT_TIMERS) || defined(PROTO)
1782/*
1783 * Check if any terminal timer expired. If so, copy text from the terminal to
1784 * the buffer.
1785 * Return the time until the next timer will expire.
1786 */
1787 int
1788term_check_timers(int next_due_arg, proftime_T *now)
1789{
1790 term_T *term;
1791 int next_due = next_due_arg;
1792
1793 for (term = first_term; term != NULL; term = term->tl_next)
1794 {
1795 if (term->tl_timer_set && !term->tl_normal_mode)
1796 {
1797 long this_due = proftime_time_left(&term->tl_timer_due, now);
1798
1799 if (this_due <= 1)
1800 {
1801 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001802 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001803 }
1804 else if (next_due == -1 || next_due > this_due)
1805 next_due = this_due;
1806 }
1807 }
1808
1809 return next_due;
1810}
1811#endif
1812
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001813/*
1814 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1815 * otherwise end it.
1816 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817 static void
1818set_terminal_mode(term_T *term, int normal_mode)
1819{
1820 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001821 if (!normal_mode)
1822 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001823 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 if (term->tl_buffer == curbuf)
1825 maketitle();
1826}
1827
1828/*
1829 * Called after the job if finished and Terminal mode is not active:
1830 * Move the vterm contents into the scrollback buffer and free the vterm.
1831 */
1832 static void
1833cleanup_vterm(term_T *term)
1834{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001835 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001836 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001837 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001838 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001839}
1840
1841/*
1842 * Switch from Terminal-Job mode to Terminal-Normal mode.
1843 * Suspends updating the terminal window.
1844 */
1845 static void
1846term_enter_normal_mode(void)
1847{
1848 term_T *term = curbuf->b_term;
1849
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001850 set_terminal_mode(term, TRUE);
1851
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001852 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001853 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001854
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001855 /* Move the window cursor to the position of the cursor in the
1856 * terminal. */
1857 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1858 + term->tl_cursor_pos.row + 1;
1859 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001860 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1861 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001862
1863 /* Display the same lines as in the terminal. */
1864 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1865}
1866
1867/*
1868 * Returns TRUE if the current window contains a terminal and we are in
1869 * Terminal-Normal mode.
1870 */
1871 int
1872term_in_normal_mode(void)
1873{
1874 term_T *term = curbuf->b_term;
1875
1876 return term != NULL && term->tl_normal_mode;
1877}
1878
1879/*
1880 * Switch from Terminal-Normal mode to Terminal-Job mode.
1881 * Restores updating the terminal window.
1882 */
1883 void
1884term_enter_job_mode()
1885{
1886 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887
1888 set_terminal_mode(term, FALSE);
1889
1890 if (term->tl_channel_closed)
1891 cleanup_vterm(term);
1892 redraw_buf_and_status_later(curbuf, NOT_VALID);
1893}
1894
1895/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001896 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001897 * Note: while waiting a terminal may be closed and freed if the channel is
1898 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001899 */
1900 static int
1901term_vgetc()
1902{
1903 int c;
1904 int save_State = State;
1905
1906 State = TERMINAL;
1907 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001908#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001909 ctrl_break_was_pressed = FALSE;
1910#endif
1911 c = vgetc();
1912 got_int = FALSE;
1913 State = save_State;
1914 return c;
1915}
1916
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001917static int mouse_was_outside = FALSE;
1918
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001919/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001920 * Send keys to terminal.
1921 * Return FAIL when the key needs to be handled in Normal mode.
1922 * Return OK when the key was dropped or sent to the terminal.
1923 */
1924 int
1925send_keys_to_term(term_T *term, int c, int typed)
1926{
1927 char msg[KEY_BUF_LEN];
1928 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001929 int dragging_outside = FALSE;
1930
1931 /* Catch keys that need to be handled as in Normal mode. */
1932 switch (c)
1933 {
1934 case NUL:
1935 case K_ZERO:
1936 if (typed)
1937 stuffcharReadbuff(c);
1938 return FAIL;
1939
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001940 case K_TABLINE:
1941 stuffcharReadbuff(c);
1942 return FAIL;
1943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001944 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001945 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946 return FAIL;
1947
1948 case K_LEFTDRAG:
1949 case K_MIDDLEDRAG:
1950 case K_RIGHTDRAG:
1951 case K_X1DRAG:
1952 case K_X2DRAG:
1953 dragging_outside = mouse_was_outside;
1954 /* FALLTHROUGH */
1955 case K_LEFTMOUSE:
1956 case K_LEFTMOUSE_NM:
1957 case K_LEFTRELEASE:
1958 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001959 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001960 case K_MIDDLEMOUSE:
1961 case K_MIDDLERELEASE:
1962 case K_RIGHTMOUSE:
1963 case K_RIGHTRELEASE:
1964 case K_X1MOUSE:
1965 case K_X1RELEASE:
1966 case K_X2MOUSE:
1967 case K_X2RELEASE:
1968
1969 case K_MOUSEUP:
1970 case K_MOUSEDOWN:
1971 case K_MOUSELEFT:
1972 case K_MOUSERIGHT:
1973 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001974 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001975 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001976 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001977 || dragging_outside)
1978 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001979 /* click or scroll outside the current window or on status line
1980 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001981 if (typed)
1982 {
1983 stuffcharReadbuff(c);
1984 mouse_was_outside = TRUE;
1985 }
1986 return FAIL;
1987 }
1988 }
1989 if (typed)
1990 mouse_was_outside = FALSE;
1991
1992 /* Convert the typed key to a sequence of bytes for the job. */
1993 len = term_convert_key(term, c, msg);
1994 if (len > 0)
1995 /* TODO: if FAIL is returned, stop? */
1996 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1997 (char_u *)msg, (int)len, NULL);
1998
1999 return OK;
2000}
2001
2002 static void
2003position_cursor(win_T *wp, VTermPos *pos)
2004{
2005 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2006 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2007 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2008}
2009
2010/*
2011 * Handle CTRL-W "": send register contents to the job.
2012 */
2013 static void
2014term_paste_register(int prev_c UNUSED)
2015{
2016 int c;
2017 list_T *l;
2018 listitem_T *item;
2019 long reglen = 0;
2020 int type;
2021
2022#ifdef FEAT_CMDL_INFO
2023 if (add_to_showcmd(prev_c))
2024 if (add_to_showcmd('"'))
2025 out_flush();
2026#endif
2027 c = term_vgetc();
2028#ifdef FEAT_CMDL_INFO
2029 clear_showcmd();
2030#endif
2031 if (!term_use_loop())
2032 /* job finished while waiting for a character */
2033 return;
2034
2035 /* CTRL-W "= prompt for expression to evaluate. */
2036 if (c == '=' && get_expr_register() != '=')
2037 return;
2038 if (!term_use_loop())
2039 /* job finished while waiting for a character */
2040 return;
2041
2042 l = (list_T *)get_reg_contents(c, GREG_LIST);
2043 if (l != NULL)
2044 {
2045 type = get_reg_type(c, &reglen);
2046 for (item = l->lv_first; item != NULL; item = item->li_next)
2047 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002048 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002049#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002050 char_u *tmp = s;
2051
2052 if (!enc_utf8 && enc_codepage > 0)
2053 {
2054 WCHAR *ret = NULL;
2055 int length = 0;
2056
2057 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2058 (int)STRLEN(s), &ret, &length);
2059 if (ret != NULL)
2060 {
2061 WideCharToMultiByte_alloc(CP_UTF8, 0,
2062 ret, length, (char **)&s, &length, 0, 0);
2063 vim_free(ret);
2064 }
2065 }
2066#endif
2067 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2068 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002069#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070 if (tmp != s)
2071 vim_free(s);
2072#endif
2073
2074 if (item->li_next != NULL || type == MLINE)
2075 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2076 (char_u *)"\r", 1, NULL);
2077 }
2078 list_free(l);
2079 }
2080}
2081
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002082/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002083 * Return TRUE when waiting for a character in the terminal, the cursor of the
2084 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085 */
2086 int
2087terminal_is_active()
2088{
2089 return in_terminal_loop != NULL;
2090}
2091
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002092#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002093 cursorentry_T *
2094term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2095{
2096 term_T *term = in_terminal_loop;
2097 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002098 int id;
2099 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100
2101 vim_memset(&entry, 0, sizeof(entry));
2102 entry.shape = entry.mshape =
2103 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2104 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2105 SHAPE_BLOCK;
2106 entry.percentage = 20;
2107 if (term->tl_cursor_blink)
2108 {
2109 entry.blinkwait = 700;
2110 entry.blinkon = 400;
2111 entry.blinkoff = 250;
2112 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002113
2114 /* The "Terminal" highlight group overrules the defaults. */
2115 id = syn_name2id((char_u *)"Terminal");
2116 if (id != 0)
2117 {
2118 syn_id2colors(id, &term_fg, &term_bg);
2119 *fg = term_bg;
2120 }
2121 else
2122 *fg = gui.back_pixel;
2123
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002124 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002125 {
2126 if (id != 0)
2127 *bg = term_fg;
2128 else
2129 *bg = gui.norm_pixel;
2130 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131 else
2132 *bg = color_name2handle(term->tl_cursor_color);
2133 entry.name = "n";
2134 entry.used_for = SHAPE_CURSOR;
2135
2136 return &entry;
2137}
2138#endif
2139
Bram Moolenaard317b382018-02-08 22:33:31 +01002140 static void
2141may_output_cursor_props(void)
2142{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002143 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002144 || last_set_cursor_shape != desired_cursor_shape
2145 || last_set_cursor_blink != desired_cursor_blink)
2146 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002147 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002148 last_set_cursor_shape = desired_cursor_shape;
2149 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002150 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002151 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2152 /* this will restore the initial cursor style, if possible */
2153 ui_cursor_shape_forced(TRUE);
2154 else
2155 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2156 }
2157}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158
Bram Moolenaard317b382018-02-08 22:33:31 +01002159/*
2160 * Set the cursor color and shape, if not last set to these.
2161 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002162 static void
2163may_set_cursor_props(term_T *term)
2164{
2165#ifdef FEAT_GUI
2166 /* For the GUI the cursor properties are obtained with
2167 * term_get_cursor_shape(). */
2168 if (gui.in_use)
2169 return;
2170#endif
2171 if (in_terminal_loop == term)
2172 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002173 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002174 desired_cursor_shape = term->tl_cursor_shape;
2175 desired_cursor_blink = term->tl_cursor_blink;
2176 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002177 }
2178}
2179
Bram Moolenaard317b382018-02-08 22:33:31 +01002180/*
2181 * Reset the desired cursor properties and restore them when needed.
2182 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002183 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002184prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002185{
2186#ifdef FEAT_GUI
2187 if (gui.in_use)
2188 return;
2189#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002190 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002191 desired_cursor_shape = -1;
2192 desired_cursor_blink = -1;
2193 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002194}
2195
2196/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002197 * Returns TRUE if the current window contains a terminal and we are sending
2198 * keys to the job.
2199 * If "check_job_status" is TRUE update the job status.
2200 */
2201 static int
2202term_use_loop_check(int check_job_status)
2203{
2204 term_T *term = curbuf->b_term;
2205
2206 return term != NULL
2207 && !term->tl_normal_mode
2208 && term->tl_vterm != NULL
2209 && term_job_running_check(term, check_job_status);
2210}
2211
2212/*
2213 * Returns TRUE if the current window contains a terminal and we are sending
2214 * keys to the job.
2215 */
2216 int
2217term_use_loop(void)
2218{
2219 return term_use_loop_check(FALSE);
2220}
2221
2222/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002223 * Called when entering a window with the mouse. If this is a terminal window
2224 * we may want to change state.
2225 */
2226 void
2227term_win_entered()
2228{
2229 term_T *term = curbuf->b_term;
2230
2231 if (term != NULL)
2232 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002233 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002234 {
2235 reset_VIsual_and_resel();
2236 if (State & INSERT)
2237 stop_insert_mode = TRUE;
2238 }
2239 mouse_was_outside = FALSE;
2240 enter_mouse_col = mouse_col;
2241 enter_mouse_row = mouse_row;
2242 }
2243}
2244
2245/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 * Wait for input and send it to the job.
2247 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2248 * when there is no more typahead.
2249 * Return when the start of a CTRL-W command is typed or anything else that
2250 * should be handled as a Normal mode command.
2251 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2252 * the terminal was closed.
2253 */
2254 int
2255terminal_loop(int blocking)
2256{
2257 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002258 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002259 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002260#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002261 int tty_fd = curbuf->b_term->tl_job->jv_channel
2262 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002263#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002264 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002265
2266 /* Remember the terminal we are sending keys to. However, the terminal
2267 * might be closed while waiting for a character, e.g. typing "exit" in a
2268 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2269 * stored reference. */
2270 in_terminal_loop = curbuf->b_term;
2271
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002272 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002273 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002274 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002275 if (termwinkey == Ctrl_W)
2276 termwinkey = 0;
2277 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2279 may_set_cursor_props(curbuf->b_term);
2280
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002281 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002282 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002283#ifdef FEAT_GUI
2284 if (!curbuf->b_term->tl_system)
2285#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002286 // TODO: skip screen update when handling a sequence of keys.
2287 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002288 while (must_redraw != 0)
2289 if (update_screen(0) == FAIL)
2290 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002291 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002292 /* job finished while redrawing */
2293 break;
2294
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002295 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002296 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297
2298 c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002299 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002300 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002301 /* Job finished while waiting for a character. Push back the
2302 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002303 if (c != K_IGNORE)
2304 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002306 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002307 if (c == K_IGNORE)
2308 continue;
2309
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002310#ifdef UNIX
2311 /*
2312 * The shell or another program may change the tty settings. Getting
2313 * them for every typed character is a bit of overhead, but it's needed
2314 * for the first character typed, e.g. when Vim starts in a shell.
2315 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002316 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002317 {
2318 ttyinfo_T info;
2319
2320 /* Get the current backspace character of the pty. */
2321 if (get_tty_info(tty_fd, &info) == OK)
2322 term_backspace_char = info.backspace;
2323 }
2324#endif
2325
Bram Moolenaar4f974752019-02-17 17:44:42 +01002326#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002327 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2328 * Use CTRL-BREAK to kill the job. */
2329 if (ctrl_break_was_pressed)
2330 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2331#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002332 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002333 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002334 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002335#ifdef FEAT_GUI
2336 && !curbuf->b_term->tl_system
2337#endif
2338 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002339 {
2340 int prev_c = c;
2341
2342#ifdef FEAT_CMDL_INFO
2343 if (add_to_showcmd(c))
2344 out_flush();
2345#endif
2346 c = term_vgetc();
2347#ifdef FEAT_CMDL_INFO
2348 clear_showcmd();
2349#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002350 if (!term_use_loop_check(TRUE)
2351 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002352 /* job finished while waiting for a character */
2353 break;
2354
2355 if (prev_c == Ctrl_BSL)
2356 {
2357 if (c == Ctrl_N)
2358 {
2359 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2360 term_enter_normal_mode();
2361 ret = FAIL;
2362 goto theend;
2363 }
2364 /* Send both keys to the terminal. */
2365 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2366 }
2367 else if (c == Ctrl_C)
2368 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002369 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002370 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2371 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002372 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002373 {
2374 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002375 /* "'termwinkey' .": send 'termwinkey' to the job */
2376 c = termwinkey == 0 ? Ctrl_W : termwinkey;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002378 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002379 {
2380 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2381 c = Ctrl_BSL;
2382 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002383 else if (c == 'N')
2384 {
2385 /* CTRL-W N : go to Terminal-Normal mode. */
2386 term_enter_normal_mode();
2387 ret = FAIL;
2388 goto theend;
2389 }
2390 else if (c == '"')
2391 {
2392 term_paste_register(prev_c);
2393 continue;
2394 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002395 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002397 char_u buf[MB_MAXBYTES + 2];
2398
2399 // Put the command into the typeahead buffer, when using the
2400 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2401 buf[0] = Ctrl_W;
2402 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2403 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002404 ret = OK;
2405 goto theend;
2406 }
2407 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002408# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409 if (!enc_utf8 && has_mbyte && c >= 0x80)
2410 {
2411 WCHAR wc;
2412 char_u mb[3];
2413
2414 mb[0] = (unsigned)c >> 8;
2415 mb[1] = c;
2416 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2417 c = wc;
2418 }
2419# endif
2420 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2421 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002422 if (c == K_MOUSEMOVE)
2423 /* We are sure to come back here, don't reset the cursor color
2424 * and shape to avoid flickering. */
2425 restore_cursor = FALSE;
2426
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002427 ret = OK;
2428 goto theend;
2429 }
2430 }
2431 ret = FAIL;
2432
2433theend:
2434 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002435 if (restore_cursor)
2436 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002437
2438 /* Move a snapshot of the screen contents to the buffer, so that completion
2439 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002440 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2441 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002442
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002443 return ret;
2444}
2445
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002446 static void
2447may_toggle_cursor(term_T *term)
2448{
2449 if (in_terminal_loop == term)
2450 {
2451 if (term->tl_cursor_visible)
2452 cursor_on();
2453 else
2454 cursor_off();
2455 }
2456}
2457
2458/*
2459 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002460 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002461 */
2462 static int
2463color2index(VTermColor *color, int fg, int *boldp)
2464{
2465 int red = color->red;
2466 int blue = color->blue;
2467 int green = color->green;
2468
Bram Moolenaar46359e12017-11-29 22:33:38 +01002469 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002471 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002472 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002473 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002474 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002475 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002476 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2477 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2478 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002479 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002480 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2481 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2482 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2483 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2484 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2485 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2486 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2487 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2488 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2489 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2490 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002491 }
2492 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002493
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494 if (t_colors >= 256)
2495 {
2496 if (red == blue && red == green)
2497 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002498 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002499 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002500 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2501 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2502 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 int i;
2504
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002505 if (red < 5)
2506 return 17; /* 00/00/00 */
2507 if (red > 245) /* ff/ff/ff */
2508 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002509 for (i = 0; i < 23; ++i)
2510 if (red < cutoff[i])
2511 return i + 233;
2512 return 256;
2513 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002514 {
2515 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2516 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002517
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002518 /* 216-color cube */
2519 for (ri = 0; ri < 5; ++ri)
2520 if (red < cutoff[ri])
2521 break;
2522 for (gi = 0; gi < 5; ++gi)
2523 if (green < cutoff[gi])
2524 break;
2525 for (bi = 0; bi < 5; ++bi)
2526 if (blue < cutoff[bi])
2527 break;
2528 return 17 + ri * 36 + gi * 6 + bi;
2529 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002530 }
2531 return 0;
2532}
2533
2534/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002535 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002536 */
2537 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002538vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539{
2540 int attr = 0;
2541
2542 if (cellattrs.bold)
2543 attr |= HL_BOLD;
2544 if (cellattrs.underline)
2545 attr |= HL_UNDERLINE;
2546 if (cellattrs.italic)
2547 attr |= HL_ITALIC;
2548 if (cellattrs.strike)
2549 attr |= HL_STRIKETHROUGH;
2550 if (cellattrs.reverse)
2551 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002552 return attr;
2553}
2554
2555/*
2556 * Store Vterm attributes in "cell" from highlight flags.
2557 */
2558 static void
2559hl2vtermAttr(int attr, cellattr_T *cell)
2560{
2561 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2562 if (attr & HL_BOLD)
2563 cell->attrs.bold = 1;
2564 if (attr & HL_UNDERLINE)
2565 cell->attrs.underline = 1;
2566 if (attr & HL_ITALIC)
2567 cell->attrs.italic = 1;
2568 if (attr & HL_STRIKETHROUGH)
2569 cell->attrs.strike = 1;
2570 if (attr & HL_INVERSE)
2571 cell->attrs.reverse = 1;
2572}
2573
2574/*
2575 * Convert the attributes of a vterm cell into an attribute index.
2576 */
2577 static int
2578cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2579{
2580 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002581
2582#ifdef FEAT_GUI
2583 if (gui.in_use)
2584 {
2585 guicolor_T fg, bg;
2586
2587 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2588 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2589 return get_gui_attr_idx(attr, fg, bg);
2590 }
2591 else
2592#endif
2593#ifdef FEAT_TERMGUICOLORS
2594 if (p_tgc)
2595 {
2596 guicolor_T fg, bg;
2597
2598 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2599 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2600
2601 return get_tgc_attr_idx(attr, fg, bg);
2602 }
2603 else
2604#endif
2605 {
2606 int bold = MAYBE;
2607 int fg = color2index(&cellfg, TRUE, &bold);
2608 int bg = color2index(&cellbg, FALSE, &bold);
2609
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002610 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002611 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002612 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002613 if (fg == 0 && term_default_cterm_fg >= 0)
2614 fg = term_default_cterm_fg + 1;
2615 if (bg == 0 && term_default_cterm_bg >= 0)
2616 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002617 }
2618
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002619 /* with 8 colors set the bold attribute to get a bright foreground */
2620 if (bold == TRUE)
2621 attr |= HL_BOLD;
2622 return get_cterm_attr_idx(attr, fg, bg);
2623 }
2624 return 0;
2625}
2626
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002627 static void
2628set_dirty_snapshot(term_T *term)
2629{
2630 term->tl_dirty_snapshot = TRUE;
2631#ifdef FEAT_TIMERS
2632 if (!term->tl_normal_mode)
2633 {
2634 /* Update the snapshot after 100 msec of not getting updates. */
2635 profile_setlimit(100L, &term->tl_timer_due);
2636 term->tl_timer_set = TRUE;
2637 }
2638#endif
2639}
2640
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002641 static int
2642handle_damage(VTermRect rect, void *user)
2643{
2644 term_T *term = (term_T *)user;
2645
2646 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2647 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002648 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002649 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650 return 1;
2651}
2652
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002653 static void
2654term_scroll_up(term_T *term, int start_row, int count)
2655{
2656 win_T *wp;
2657 VTermColor fg, bg;
2658 VTermScreenCellAttrs attr;
2659 int clear_attr;
2660
2661 /* Set the color to clear lines with. */
2662 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2663 &fg, &bg);
2664 vim_memset(&attr, 0, sizeof(attr));
2665 clear_attr = cell2attr(attr, fg, bg);
2666
2667 FOR_ALL_WINDOWS(wp)
2668 {
2669 if (wp->w_buffer == term->tl_buffer)
2670 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2671 }
2672}
2673
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002674 static int
2675handle_moverect(VTermRect dest, VTermRect src, void *user)
2676{
2677 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002678 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002679
2680 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002681 * redrawing the text. But avoid doing this multiple times, postpone until
2682 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002683 if (dest.start_col == src.start_col
2684 && dest.end_col == src.end_col
2685 && dest.start_row < src.start_row)
2686 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002687 if (dest.start_row == 0)
2688 term->tl_postponed_scroll += count;
2689 else
2690 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002691 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002692
2693 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2694 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002695 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002696
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002697 /* Note sure if the scrolling will work correctly, let's do a complete
2698 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002699 redraw_buf_later(term->tl_buffer, NOT_VALID);
2700 return 1;
2701}
2702
2703 static int
2704handle_movecursor(
2705 VTermPos pos,
2706 VTermPos oldpos UNUSED,
2707 int visible,
2708 void *user)
2709{
2710 term_T *term = (term_T *)user;
2711 win_T *wp;
2712
2713 term->tl_cursor_pos = pos;
2714 term->tl_cursor_visible = visible;
2715
2716 FOR_ALL_WINDOWS(wp)
2717 {
2718 if (wp->w_buffer == term->tl_buffer)
2719 position_cursor(wp, &pos);
2720 }
2721 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2722 {
2723 may_toggle_cursor(term);
2724 update_cursor(term, term->tl_cursor_visible);
2725 }
2726
2727 return 1;
2728}
2729
2730 static int
2731handle_settermprop(
2732 VTermProp prop,
2733 VTermValue *value,
2734 void *user)
2735{
2736 term_T *term = (term_T *)user;
2737
2738 switch (prop)
2739 {
2740 case VTERM_PROP_TITLE:
2741 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002742 // a blank title isn't useful, make it empty, so that "running" is
2743 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002744 if (*skipwhite((char_u *)value->string) == NUL)
2745 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002746 // Same as blank
2747 else if (term->tl_arg0_cmd != NULL
2748 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2749 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2750 term->tl_title = NULL;
2751 // Empty corrupted data of winpty
2752 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2753 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002754#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002755 else if (!enc_utf8 && enc_codepage > 0)
2756 {
2757 WCHAR *ret = NULL;
2758 int length = 0;
2759
2760 MultiByteToWideChar_alloc(CP_UTF8, 0,
2761 (char*)value->string, (int)STRLEN(value->string),
2762 &ret, &length);
2763 if (ret != NULL)
2764 {
2765 WideCharToMultiByte_alloc(enc_codepage, 0,
2766 ret, length, (char**)&term->tl_title,
2767 &length, 0, 0);
2768 vim_free(ret);
2769 }
2770 }
2771#endif
2772 else
2773 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002774 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002775 if (term == curbuf->b_term)
2776 maketitle();
2777 break;
2778
2779 case VTERM_PROP_CURSORVISIBLE:
2780 term->tl_cursor_visible = value->boolean;
2781 may_toggle_cursor(term);
2782 out_flush();
2783 break;
2784
2785 case VTERM_PROP_CURSORBLINK:
2786 term->tl_cursor_blink = value->boolean;
2787 may_set_cursor_props(term);
2788 break;
2789
2790 case VTERM_PROP_CURSORSHAPE:
2791 term->tl_cursor_shape = value->number;
2792 may_set_cursor_props(term);
2793 break;
2794
2795 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002796 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002797 may_set_cursor_props(term);
2798 break;
2799
2800 case VTERM_PROP_ALTSCREEN:
2801 /* TODO: do anything else? */
2802 term->tl_using_altscreen = value->boolean;
2803 break;
2804
2805 default:
2806 break;
2807 }
2808 /* Always return 1, otherwise vterm doesn't store the value internally. */
2809 return 1;
2810}
2811
2812/*
2813 * The job running in the terminal resized the terminal.
2814 */
2815 static int
2816handle_resize(int rows, int cols, void *user)
2817{
2818 term_T *term = (term_T *)user;
2819 win_T *wp;
2820
2821 term->tl_rows = rows;
2822 term->tl_cols = cols;
2823 if (term->tl_vterm_size_changed)
2824 /* Size was set by vterm_set_size(), don't set the window size. */
2825 term->tl_vterm_size_changed = FALSE;
2826 else
2827 {
2828 FOR_ALL_WINDOWS(wp)
2829 {
2830 if (wp->w_buffer == term->tl_buffer)
2831 {
2832 win_setheight_win(rows, wp);
2833 win_setwidth_win(cols, wp);
2834 }
2835 }
2836 redraw_buf_later(term->tl_buffer, NOT_VALID);
2837 }
2838 return 1;
2839}
2840
2841/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002842 * If the number of lines that are stored goes over 'termscrollback' then
2843 * delete the first 10%.
2844 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2845 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002847 static void
2848limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002849{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002850 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002851 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002852 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002853 int i;
2854
2855 curbuf = term->tl_buffer;
2856 for (i = 0; i < todo; ++i)
2857 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002858 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2859 if (update_buffer)
2860 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002861 }
2862 curbuf = curwin->w_buffer;
2863
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002864 gap->ga_len -= todo;
2865 mch_memmove(gap->ga_data,
2866 (sb_line_T *)gap->ga_data + todo,
2867 sizeof(sb_line_T) * gap->ga_len);
2868 if (update_buffer)
2869 term->tl_scrollback_scrolled -= todo;
2870 }
2871}
2872
2873/*
2874 * Handle a line that is pushed off the top of the screen.
2875 */
2876 static int
2877handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2878{
2879 term_T *term = (term_T *)user;
2880 garray_T *gap;
2881 int update_buffer;
2882
2883 if (term->tl_normal_mode)
2884 {
2885 // In Terminal-Normal mode the user interacts with the buffer, thus we
2886 // must not change it. Postpone adding the scrollback lines.
2887 gap = &term->tl_scrollback_postponed;
2888 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002889 }
2890 else
2891 {
2892 // First remove the lines that were appended before, the pushed line
2893 // goes above it.
2894 cleanup_scrollback(term);
2895 gap = &term->tl_scrollback;
2896 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002897 }
2898
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002899 limit_scrollback(term, gap, update_buffer);
2900
2901 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902 {
2903 cellattr_T *p = NULL;
2904 int len = 0;
2905 int i;
2906 int c;
2907 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002908 int text_len;
2909 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910 sb_line_T *line;
2911 garray_T ga;
2912 cellattr_T fill_attr = term->tl_default_color;
2913
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002914 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002915 for (i = 0; i < cols; ++i)
2916 if (cells[i].chars[0] != 0)
2917 len = i + 1;
2918 else
2919 cell2cellattr(&cells[i], &fill_attr);
2920
2921 ga_init2(&ga, 1, 100);
2922 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002923 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002924 if (p != NULL)
2925 {
2926 for (col = 0; col < len; col += cells[col].width)
2927 {
2928 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2929 {
2930 ga.ga_len = 0;
2931 break;
2932 }
2933 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2934 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2935 (char_u *)ga.ga_data + ga.ga_len);
2936 cell2cellattr(&cells[col], &p[col]);
2937 }
2938 }
2939 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002940 {
2941 if (update_buffer)
2942 text = (char_u *)"";
2943 else
2944 text = vim_strsave((char_u *)"");
2945 text_len = 0;
2946 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002947 else
2948 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002949 text = ga.ga_data;
2950 text_len = ga.ga_len;
2951 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002952 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002953 if (update_buffer)
2954 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002955
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002956 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002957 line->sb_cols = len;
2958 line->sb_cells = p;
2959 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002960 if (update_buffer)
2961 {
2962 line->sb_text = NULL;
2963 ++term->tl_scrollback_scrolled;
2964 ga_clear(&ga); // free the text
2965 }
2966 else
2967 {
2968 line->sb_text = text;
2969 ga_init(&ga); // text is kept in tl_scrollback_postponed
2970 }
2971 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002972 }
2973 return 0; /* ignored */
2974}
2975
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002976/*
2977 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
2978 * received and stored in tl_scrollback_postponed.
2979 */
2980 static void
2981handle_postponed_scrollback(term_T *term)
2982{
2983 int i;
2984
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01002985 if (term->tl_scrollback_postponed.ga_len == 0)
2986 return;
2987 ch_log(NULL, "Moving postponed scrollback to scrollback");
2988
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002989 // First remove the lines that were appended before, the pushed lines go
2990 // above it.
2991 cleanup_scrollback(term);
2992
2993 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
2994 {
2995 char_u *text;
2996 sb_line_T *pp_line;
2997 sb_line_T *line;
2998
2999 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3000 break;
3001 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3002
3003 text = pp_line->sb_text;
3004 if (text == NULL)
3005 text = (char_u *)"";
3006 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3007 vim_free(pp_line->sb_text);
3008
3009 line = (sb_line_T *)term->tl_scrollback.ga_data
3010 + term->tl_scrollback.ga_len;
3011 line->sb_cols = pp_line->sb_cols;
3012 line->sb_cells = pp_line->sb_cells;
3013 line->sb_fill_attr = pp_line->sb_fill_attr;
3014 line->sb_text = NULL;
3015 ++term->tl_scrollback_scrolled;
3016 ++term->tl_scrollback.ga_len;
3017 }
3018
3019 ga_clear(&term->tl_scrollback_postponed);
3020 limit_scrollback(term, &term->tl_scrollback, TRUE);
3021}
3022
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003023static VTermScreenCallbacks screen_callbacks = {
3024 handle_damage, /* damage */
3025 handle_moverect, /* moverect */
3026 handle_movecursor, /* movecursor */
3027 handle_settermprop, /* settermprop */
3028 NULL, /* bell */
3029 handle_resize, /* resize */
3030 handle_pushline, /* sb_pushline */
3031 NULL /* sb_popline */
3032};
3033
3034/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003035 * Do the work after the channel of a terminal was closed.
3036 * Must be called only when updating_screen is FALSE.
3037 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3038 */
3039 static int
3040term_after_channel_closed(term_T *term)
3041{
3042 /* Unless in Terminal-Normal mode: clear the vterm. */
3043 if (!term->tl_normal_mode)
3044 {
3045 int fnum = term->tl_buffer->b_fnum;
3046
3047 cleanup_vterm(term);
3048
3049 if (term->tl_finish == TL_FINISH_CLOSE)
3050 {
3051 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003052 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003053
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003054 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003055 ch_log(NULL, "terminal job finished, closing window");
3056 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003057 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003058 if (curwin == aucmd_win)
3059 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003060 if (do_set_w_closing)
3061 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003062 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003063 if (do_set_w_closing)
3064 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003065 aucmd_restbuf(&aco);
3066 return TRUE;
3067 }
3068 if (term->tl_finish == TL_FINISH_OPEN
3069 && term->tl_buffer->b_nwindows == 0)
3070 {
3071 char buf[50];
3072
3073 /* TODO: use term_opencmd */
3074 ch_log(NULL, "terminal job finished, opening window");
3075 vim_snprintf(buf, sizeof(buf),
3076 term->tl_opencmd == NULL
3077 ? "botright sbuf %d"
3078 : (char *)term->tl_opencmd, fnum);
3079 do_cmdline_cmd((char_u *)buf);
3080 }
3081 else
3082 ch_log(NULL, "terminal job finished");
3083 }
3084
3085 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3086 return FALSE;
3087}
3088
3089/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003090 * Called when a channel has been closed.
3091 * If this was a channel for a terminal window then finish it up.
3092 */
3093 void
3094term_channel_closed(channel_T *ch)
3095{
3096 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003097 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003098 int did_one = FALSE;
3099
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003100 for (term = first_term; term != NULL; term = next_term)
3101 {
3102 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003103 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003104 {
3105 term->tl_channel_closed = TRUE;
3106 did_one = TRUE;
3107
Bram Moolenaard23a8232018-02-10 18:45:26 +01003108 VIM_CLEAR(term->tl_title);
3109 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003110#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003111 if (term->tl_out_fd != NULL)
3112 {
3113 fclose(term->tl_out_fd);
3114 term->tl_out_fd = NULL;
3115 }
3116#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003117
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003118 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003120 /* Cannot open or close windows now. Can happen when
3121 * 'lazyredraw' is set. */
3122 term->tl_channel_recently_closed = TRUE;
3123 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003124 }
3125
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003126 if (term_after_channel_closed(term))
3127 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003128 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003129 }
3130
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131 if (did_one)
3132 {
3133 redraw_statuslines();
3134
3135 /* Need to break out of vgetc(). */
3136 ins_char_typebuf(K_IGNORE);
3137 typebuf_was_filled = TRUE;
3138
3139 term = curbuf->b_term;
3140 if (term != NULL)
3141 {
3142 if (term->tl_job == ch->ch_job)
3143 maketitle();
3144 update_cursor(term, term->tl_cursor_visible);
3145 }
3146 }
3147}
3148
3149/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003150 * To be called after resetting updating_screen: handle any terminal where the
3151 * channel was closed.
3152 */
3153 void
3154term_check_channel_closed_recently()
3155{
3156 term_T *term;
3157 term_T *next_term;
3158
3159 for (term = first_term; term != NULL; term = next_term)
3160 {
3161 next_term = term->tl_next;
3162 if (term->tl_channel_recently_closed)
3163 {
3164 term->tl_channel_recently_closed = FALSE;
3165 if (term_after_channel_closed(term))
3166 // start over, the list may have changed
3167 next_term = first_term;
3168 }
3169 }
3170}
3171
3172/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003173 * Fill one screen line from a line of the terminal.
3174 * Advances "pos" to past the last column.
3175 */
3176 static void
3177term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3178{
3179 int off = screen_get_current_line_off();
3180
3181 for (pos->col = 0; pos->col < max_col; )
3182 {
3183 VTermScreenCell cell;
3184 int c;
3185
3186 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3187 vim_memset(&cell, 0, sizeof(cell));
3188
3189 c = cell.chars[0];
3190 if (c == NUL)
3191 {
3192 ScreenLines[off] = ' ';
3193 if (enc_utf8)
3194 ScreenLinesUC[off] = NUL;
3195 }
3196 else
3197 {
3198 if (enc_utf8)
3199 {
3200 int i;
3201
3202 /* composing chars */
3203 for (i = 0; i < Screen_mco
3204 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3205 {
3206 ScreenLinesC[i][off] = cell.chars[i + 1];
3207 if (cell.chars[i + 1] == 0)
3208 break;
3209 }
3210 if (c >= 0x80 || (Screen_mco > 0
3211 && ScreenLinesC[0][off] != 0))
3212 {
3213 ScreenLines[off] = ' ';
3214 ScreenLinesUC[off] = c;
3215 }
3216 else
3217 {
3218 ScreenLines[off] = c;
3219 ScreenLinesUC[off] = NUL;
3220 }
3221 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003222#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003223 else if (has_mbyte && c >= 0x80)
3224 {
3225 char_u mb[MB_MAXBYTES+1];
3226 WCHAR wc = c;
3227
3228 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3229 (char*)mb, 2, 0, 0) > 1)
3230 {
3231 ScreenLines[off] = mb[0];
3232 ScreenLines[off + 1] = mb[1];
3233 cell.width = mb_ptr2cells(mb);
3234 }
3235 else
3236 ScreenLines[off] = c;
3237 }
3238#endif
3239 else
3240 ScreenLines[off] = c;
3241 }
3242 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3243
3244 ++pos->col;
3245 ++off;
3246 if (cell.width == 2)
3247 {
3248 if (enc_utf8)
3249 ScreenLinesUC[off] = NUL;
3250
3251 /* don't set the second byte to NUL for a DBCS encoding, it
3252 * has been set above */
3253 if (enc_utf8 || !has_mbyte)
3254 ScreenLines[off] = NUL;
3255
3256 ++pos->col;
3257 ++off;
3258 }
3259 }
3260}
3261
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003262#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003263 static void
3264update_system_term(term_T *term)
3265{
3266 VTermPos pos;
3267 VTermScreen *screen;
3268
3269 if (term->tl_vterm == NULL)
3270 return;
3271 screen = vterm_obtain_screen(term->tl_vterm);
3272
3273 /* Scroll up to make more room for terminal lines if needed. */
3274 while (term->tl_toprow > 0
3275 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3276 {
3277 int save_p_more = p_more;
3278
3279 p_more = FALSE;
3280 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003281 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003282 p_more = save_p_more;
3283 --term->tl_toprow;
3284 }
3285
3286 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3287 && pos.row < Rows; ++pos.row)
3288 {
3289 if (pos.row < term->tl_rows)
3290 {
3291 int max_col = MIN(Columns, term->tl_cols);
3292
3293 term_line2screenline(screen, &pos, max_col);
3294 }
3295 else
3296 pos.col = 0;
3297
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003298 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003299 }
3300
3301 term->tl_dirty_row_start = MAX_ROW;
3302 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003303}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003304#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003305
3306/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003307 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3308 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003309 * Terminal-Normal mode.
3310 */
3311 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003312term_do_update_window(win_T *wp)
3313{
3314 term_T *term = wp->w_buffer->b_term;
3315
3316 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3317}
3318
3319/*
3320 * Called to update a window that contains an active terminal.
3321 */
3322 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003323term_update_window(win_T *wp)
3324{
3325 term_T *term = wp->w_buffer->b_term;
3326 VTerm *vterm;
3327 VTermScreen *screen;
3328 VTermState *state;
3329 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003330 int rows, cols;
3331 int newrows, newcols;
3332 int minsize;
3333 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003334
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003335 vterm = term->tl_vterm;
3336 screen = vterm_obtain_screen(vterm);
3337 state = vterm_obtain_state(vterm);
3338
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003339 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3340 * SOME_VALID only redraw what was marked dirty. */
3341 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003342 {
3343 term->tl_dirty_row_start = 0;
3344 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003345
3346 if (term->tl_postponed_scroll > 0
3347 && term->tl_postponed_scroll < term->tl_rows / 3)
3348 /* Scrolling is usually faster than redrawing, when there are only
3349 * a few lines to scroll. */
3350 term_scroll_up(term, 0, term->tl_postponed_scroll);
3351 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003352 }
3353
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003354 /*
3355 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003356 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003357 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003358 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003359
Bram Moolenaar498c2562018-04-15 23:45:15 +02003360 newrows = 99999;
3361 newcols = 99999;
3362 FOR_ALL_WINDOWS(twp)
3363 {
3364 /* When more than one window shows the same terminal, use the
3365 * smallest size. */
3366 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003367 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003368 newrows = MIN(newrows, twp->w_height);
3369 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003370 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003371 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003372 if (newrows == 99999 || newcols == 99999)
3373 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003374 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3375 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3376
3377 if (term->tl_rows != newrows || term->tl_cols != newcols)
3378 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003380 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003382 newrows);
3383 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003384
3385 // Updating the terminal size will cause the snapshot to be cleared.
3386 // When not in terminal_loop() we need to restore it.
3387 if (term != in_terminal_loop)
3388 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003389 }
3390
3391 /* The cursor may have been moved when resizing. */
3392 vterm_state_get_cursorpos(state, &pos);
3393 position_cursor(wp, &pos);
3394
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003395 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3396 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003397 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003398 if (pos.row < term->tl_rows)
3399 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003400 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401
Bram Moolenaar13568252018-03-16 20:46:58 +01003402 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003403 }
3404 else
3405 pos.col = 0;
3406
Bram Moolenaarf118d482018-03-13 13:14:00 +01003407 screen_line(wp->w_winrow + pos.row
3408#ifdef FEAT_MENU
3409 + winbar_height(wp)
3410#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003411 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003412 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003413 term->tl_dirty_row_start = MAX_ROW;
3414 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003415}
3416
3417/*
3418 * Return TRUE if "wp" is a terminal window where the job has finished.
3419 */
3420 int
3421term_is_finished(buf_T *buf)
3422{
3423 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3424}
3425
3426/*
3427 * Return TRUE if "wp" is a terminal window where the job has finished or we
3428 * are in Terminal-Normal mode, thus we show the buffer contents.
3429 */
3430 int
3431term_show_buffer(buf_T *buf)
3432{
3433 term_T *term = buf->b_term;
3434
3435 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3436}
3437
3438/*
3439 * The current buffer is going to be changed. If there is terminal
3440 * highlighting remove it now.
3441 */
3442 void
3443term_change_in_curbuf(void)
3444{
3445 term_T *term = curbuf->b_term;
3446
3447 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3448 {
3449 free_scrollback(term);
3450 redraw_buf_later(term->tl_buffer, NOT_VALID);
3451
3452 /* The buffer is now like a normal buffer, it cannot be easily
3453 * abandoned when changed. */
3454 set_string_option_direct((char_u *)"buftype", -1,
3455 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3456 }
3457}
3458
3459/*
3460 * Get the screen attribute for a position in the buffer.
3461 * Use a negative "col" to get the filler background color.
3462 */
3463 int
3464term_get_attr(buf_T *buf, linenr_T lnum, int col)
3465{
3466 term_T *term = buf->b_term;
3467 sb_line_T *line;
3468 cellattr_T *cellattr;
3469
3470 if (lnum > term->tl_scrollback.ga_len)
3471 cellattr = &term->tl_default_color;
3472 else
3473 {
3474 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3475 if (col < 0 || col >= line->sb_cols)
3476 cellattr = &line->sb_fill_attr;
3477 else
3478 cellattr = line->sb_cells + col;
3479 }
3480 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3481}
3482
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003483/*
3484 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003485 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003486 */
3487 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003488cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003489{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003490 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003491}
3492
3493/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003494 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003495 */
3496 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003497init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003498{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003499 VTermColor *fg, *bg;
3500 int fgval, bgval;
3501 int id;
3502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003503 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3504 term->tl_default_color.width = 1;
3505 fg = &term->tl_default_color.fg;
3506 bg = &term->tl_default_color.bg;
3507
3508 /* Vterm uses a default black background. Set it to white when
3509 * 'background' is "light". */
3510 if (*p_bg == 'l')
3511 {
3512 fgval = 0;
3513 bgval = 255;
3514 }
3515 else
3516 {
3517 fgval = 255;
3518 bgval = 0;
3519 }
3520 fg->red = fg->green = fg->blue = fgval;
3521 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003522 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003523
3524 /* The "Terminal" highlight group overrules the defaults. */
3525 id = syn_name2id((char_u *)"Terminal");
3526
Bram Moolenaar46359e12017-11-29 22:33:38 +01003527 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003528#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3529 if (0
3530# ifdef FEAT_GUI
3531 || gui.in_use
3532# endif
3533# ifdef FEAT_TERMGUICOLORS
3534 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003535# ifdef FEAT_VTP
3536 /* Finally get INVALCOLOR on this execution path */
3537 || (!p_tgc && t_colors >= 256)
3538# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003539# endif
3540 )
3541 {
3542 guicolor_T fg_rgb = INVALCOLOR;
3543 guicolor_T bg_rgb = INVALCOLOR;
3544
3545 if (id != 0)
3546 syn_id2colors(id, &fg_rgb, &bg_rgb);
3547
3548# ifdef FEAT_GUI
3549 if (gui.in_use)
3550 {
3551 if (fg_rgb == INVALCOLOR)
3552 fg_rgb = gui.norm_pixel;
3553 if (bg_rgb == INVALCOLOR)
3554 bg_rgb = gui.back_pixel;
3555 }
3556# ifdef FEAT_TERMGUICOLORS
3557 else
3558# endif
3559# endif
3560# ifdef FEAT_TERMGUICOLORS
3561 {
3562 if (fg_rgb == INVALCOLOR)
3563 fg_rgb = cterm_normal_fg_gui_color;
3564 if (bg_rgb == INVALCOLOR)
3565 bg_rgb = cterm_normal_bg_gui_color;
3566 }
3567# endif
3568 if (fg_rgb != INVALCOLOR)
3569 {
3570 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3571
3572 fg->red = (unsigned)(rgb >> 16);
3573 fg->green = (unsigned)(rgb >> 8) & 255;
3574 fg->blue = (unsigned)rgb & 255;
3575 }
3576 if (bg_rgb != INVALCOLOR)
3577 {
3578 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3579
3580 bg->red = (unsigned)(rgb >> 16);
3581 bg->green = (unsigned)(rgb >> 8) & 255;
3582 bg->blue = (unsigned)rgb & 255;
3583 }
3584 }
3585 else
3586#endif
3587 if (id != 0 && t_colors >= 16)
3588 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003589 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003590 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003591 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003592 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003593 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003594 else
3595 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003596#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003597 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003598#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003599
3600 /* In an MS-Windows console we know the normal colors. */
3601 if (cterm_normal_fg_color > 0)
3602 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003603 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003604# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3605# ifdef VIMDLL
3606 if (!gui.in_use)
3607# endif
3608 {
3609 tmp = fg->red;
3610 fg->red = fg->blue;
3611 fg->blue = tmp;
3612 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003613# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003614 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003615# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003616 else
3617 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003618# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003619
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003620 if (cterm_normal_bg_color > 0)
3621 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003622 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003623# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3624# ifdef VIMDLL
3625 if (!gui.in_use)
3626# endif
3627 {
3628 tmp = fg->red;
3629 fg->red = fg->blue;
3630 fg->blue = tmp;
3631 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003632# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003633 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003634# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003635 else
3636 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003637# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003638 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003639}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003640
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003641#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3642/*
3643 * Set the 16 ANSI colors from array of RGB values
3644 */
3645 static void
3646set_vterm_palette(VTerm *vterm, long_u *rgb)
3647{
3648 int index = 0;
3649 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003650
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003651 for (; index < 16; index++)
3652 {
3653 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003654
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003655 color.red = (unsigned)(rgb[index] >> 16);
3656 color.green = (unsigned)(rgb[index] >> 8) & 255;
3657 color.blue = (unsigned)rgb[index] & 255;
3658 vterm_state_set_palette_color(state, index, &color);
3659 }
3660}
3661
3662/*
3663 * Set the ANSI color palette from a list of colors
3664 */
3665 static int
3666set_ansi_colors_list(VTerm *vterm, list_T *list)
3667{
3668 int n = 0;
3669 long_u rgb[16];
3670 listitem_T *li = list->lv_first;
3671
3672 for (; li != NULL && n < 16; li = li->li_next, n++)
3673 {
3674 char_u *color_name;
3675 guicolor_T guicolor;
3676
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003677 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003678 if (color_name == NULL)
3679 return FAIL;
3680
3681 guicolor = GUI_GET_COLOR(color_name);
3682 if (guicolor == INVALCOLOR)
3683 return FAIL;
3684
3685 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3686 }
3687
3688 if (n != 16 || li != NULL)
3689 return FAIL;
3690
3691 set_vterm_palette(vterm, rgb);
3692
3693 return OK;
3694}
3695
3696/*
3697 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3698 */
3699 static void
3700init_vterm_ansi_colors(VTerm *vterm)
3701{
3702 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3703
3704 if (var != NULL
3705 && (var->di_tv.v_type != VAR_LIST
3706 || var->di_tv.vval.v_list == NULL
3707 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003708 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003709}
3710#endif
3711
Bram Moolenaar52acb112018-03-18 19:20:22 +01003712/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003713 * Handles a "drop" command from the job in the terminal.
3714 * "item" is the file name, "item->li_next" may have options.
3715 */
3716 static void
3717handle_drop_command(listitem_T *item)
3718{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003719 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003720 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003721 int bufnr;
3722 win_T *wp;
3723 tabpage_T *tp;
3724 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003725 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003726
3727 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3728 FOR_ALL_TAB_WINDOWS(tp, wp)
3729 {
3730 if (wp->w_buffer->b_fnum == bufnr)
3731 {
3732 /* buffer is in a window already, go there */
3733 goto_tabpage_win(tp, wp);
3734 return;
3735 }
3736 }
3737
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003738 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003739
3740 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3741 && opt_item->li_tv.vval.v_dict != NULL)
3742 {
3743 dict_T *dict = opt_item->li_tv.vval.v_dict;
3744 char_u *p;
3745
Bram Moolenaar8f667172018-12-14 15:38:31 +01003746 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003747 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003748 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003749 if (p != NULL)
3750 {
3751 if (check_ff_value(p) == FAIL)
3752 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3753 else
3754 ea.force_ff = *p;
3755 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003756 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003757 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003758 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003759 if (p != NULL)
3760 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003761 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003762 if (ea.cmd != NULL)
3763 {
3764 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3765 ea.force_enc = 11;
3766 tofree = ea.cmd;
3767 }
3768 }
3769
Bram Moolenaar8f667172018-12-14 15:38:31 +01003770 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003771 if (p != NULL)
3772 get_bad_opt(p, &ea);
3773
3774 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3775 ea.force_bin = FORCE_BIN;
3776 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3777 ea.force_bin = FORCE_BIN;
3778 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3779 ea.force_bin = FORCE_NOBIN;
3780 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3781 ea.force_bin = FORCE_NOBIN;
3782 }
3783
3784 /* open in new window, like ":split fname" */
3785 if (ea.cmd == NULL)
3786 ea.cmd = (char_u *)"split";
3787 ea.arg = fname;
3788 ea.cmdidx = CMD_split;
3789 ex_splitview(&ea);
3790
3791 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003792}
3793
3794/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003795 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3796 */
3797 static int
3798is_permitted_term_api(char_u *func, char_u *pat)
3799{
3800 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3801}
3802
3803/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003804 * Handles a function call from the job running in a terminal.
3805 * "item" is the function name, "item->li_next" has the arguments.
3806 */
3807 static void
3808handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3809{
3810 char_u *func;
3811 typval_T argvars[2];
3812 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003813 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003814
3815 if (item->li_next == NULL)
3816 {
3817 ch_log(channel, "Missing function arguments for call");
3818 return;
3819 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003820 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003821
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003822 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003823 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003824 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003825 return;
3826 }
3827
3828 argvars[0].v_type = VAR_NUMBER;
3829 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3830 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003831 vim_memset(&funcexe, 0, sizeof(funcexe));
3832 funcexe.firstline = 1L;
3833 funcexe.lastline = 1L;
3834 funcexe.evaluate = TRUE;
3835 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003836 {
3837 clear_tv(&rettv);
3838 ch_log(channel, "Function %s called", func);
3839 }
3840 else
3841 ch_log(channel, "Calling function %s failed", func);
3842}
3843
3844/*
3845 * Called by libvterm when it cannot recognize an OSC sequence.
3846 * We recognize a terminal API command.
3847 */
3848 static int
3849parse_osc(const char *command, size_t cmdlen, void *user)
3850{
3851 term_T *term = (term_T *)user;
3852 js_read_T reader;
3853 typval_T tv;
3854 channel_T *channel = term->tl_job == NULL ? NULL
3855 : term->tl_job->jv_channel;
3856
3857 /* We recognize only OSC 5 1 ; {command} */
3858 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3859 return 0; /* not handled */
3860
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003861 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003862 if (reader.js_buf == NULL)
3863 return 1;
3864 reader.js_fill = NULL;
3865 reader.js_used = 0;
3866 if (json_decode(&reader, &tv, 0) == OK
3867 && tv.v_type == VAR_LIST
3868 && tv.vval.v_list != NULL)
3869 {
3870 listitem_T *item = tv.vval.v_list->lv_first;
3871
3872 if (item == NULL)
3873 ch_log(channel, "Missing command");
3874 else
3875 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003876 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003877
Bram Moolenaara997b452018-04-17 23:24:06 +02003878 /* Make sure an invoked command doesn't delete the buffer (and the
3879 * terminal) under our fingers. */
3880 ++term->tl_buffer->b_locked;
3881
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003882 item = item->li_next;
3883 if (item == NULL)
3884 ch_log(channel, "Missing argument for %s", cmd);
3885 else if (STRCMP(cmd, "drop") == 0)
3886 handle_drop_command(item);
3887 else if (STRCMP(cmd, "call") == 0)
3888 handle_call_command(term, channel, item);
3889 else
3890 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003891 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003892 }
3893 }
3894 else
3895 ch_log(channel, "Invalid JSON received");
3896
3897 vim_free(reader.js_buf);
3898 clear_tv(&tv);
3899 return 1;
3900}
3901
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003902/*
3903 * Called by libvterm when it cannot recognize a CSI sequence.
3904 * We recognize the window position report.
3905 */
3906 static int
3907parse_csi(
3908 const char *leader UNUSED,
3909 const long args[],
3910 int argcount,
3911 const char *intermed UNUSED,
3912 char command,
3913 void *user)
3914{
3915 term_T *term = (term_T *)user;
3916 char buf[100];
3917 int len;
3918 int x = 0;
3919 int y = 0;
3920 win_T *wp;
3921
3922 // We recognize only CSI 13 t
3923 if (command != 't' || argcount != 1 || args[0] != 13)
3924 return 0; // not handled
3925
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003926 // When getting the window position is not possible or it fails it results
3927 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003928#if defined(FEAT_GUI) \
3929 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3930 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003931 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003932#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003933
3934 FOR_ALL_WINDOWS(wp)
3935 if (wp->w_buffer == term->tl_buffer)
3936 break;
3937 if (wp != NULL)
3938 {
3939#ifdef FEAT_GUI
3940 if (gui.in_use)
3941 {
3942 x += wp->w_wincol * gui.char_width;
3943 y += W_WINROW(wp) * gui.char_height;
3944 }
3945 else
3946#endif
3947 {
3948 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003949 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003950 x += wp->w_wincol * 7;
3951 y += W_WINROW(wp) * 10;
3952 }
3953 }
3954
3955 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
3956 channel_send(term->tl_job->jv_channel, get_tty_part(term),
3957 (char_u *)buf, len, NULL);
3958 return 1;
3959}
3960
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003961static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003962 NULL, // text
3963 NULL, // control
3964 NULL, // escape
3965 parse_csi, // csi
3966 parse_osc, // osc
3967 NULL, // dcs
3968 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003969};
3970
3971/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003972 * Use Vim's allocation functions for vterm so profiling works.
3973 */
3974 static void *
3975vterm_malloc(size_t size, void *data UNUSED)
3976{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02003977 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003978}
3979
3980 static void
3981vterm_memfree(void *ptr, void *data UNUSED)
3982{
3983 vim_free(ptr);
3984}
3985
3986static VTermAllocatorFunctions vterm_allocator = {
3987 &vterm_malloc,
3988 &vterm_memfree
3989};
3990
3991/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003992 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003993 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01003994 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003995 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01003996create_vterm(term_T *term, int rows, int cols)
3997{
3998 VTerm *vterm;
3999 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004000 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004001 VTermValue value;
4002
Bram Moolenaar756ef112018-04-10 12:04:27 +02004003 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004004 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004005 if (vterm == NULL)
4006 return FAIL;
4007
4008 // Allocate screen and state here, so we can bail out if that fails.
4009 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004010 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004011 if (state == NULL || screen == NULL)
4012 {
4013 vterm_free(vterm);
4014 return FAIL;
4015 }
4016
Bram Moolenaar52acb112018-03-18 19:20:22 +01004017 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4018 /* TODO: depends on 'encoding'. */
4019 vterm_set_utf8(vterm, 1);
4020
4021 init_default_colors(term);
4022
4023 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004024 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004025 &term->tl_default_color.fg,
4026 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004027
Bram Moolenaar9e587872019-05-13 20:27:23 +02004028 if (t_colors < 16)
4029 // Less than 16 colors: assume that bold means using a bright color for
4030 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004031 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4032
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004033 /* Required to initialize most things. */
4034 vterm_screen_reset(screen, 1 /* hard */);
4035
4036 /* Allow using alternate screen. */
4037 vterm_screen_enable_altscreen(screen, 1);
4038
4039 /* For unix do not use a blinking cursor. In an xterm this causes the
4040 * cursor to blink if it's blinking in the xterm.
4041 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004042#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004043 if (GetCaretBlinkTime() == INFINITE)
4044 value.boolean = 0;
4045 else
4046 value.boolean = 1;
4047#else
4048 value.boolean = 0;
4049#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004050 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4051 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004052
4053 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004054}
4055
4056/*
4057 * Return the text to show for the buffer name and status.
4058 */
4059 char_u *
4060term_get_status_text(term_T *term)
4061{
4062 if (term->tl_status_text == NULL)
4063 {
4064 char_u *txt;
4065 size_t len;
4066
4067 if (term->tl_normal_mode)
4068 {
4069 if (term_job_running(term))
4070 txt = (char_u *)_("Terminal");
4071 else
4072 txt = (char_u *)_("Terminal-finished");
4073 }
4074 else if (term->tl_title != NULL)
4075 txt = term->tl_title;
4076 else if (term_none_open(term))
4077 txt = (char_u *)_("active");
4078 else if (term_job_running(term))
4079 txt = (char_u *)_("running");
4080 else
4081 txt = (char_u *)_("finished");
4082 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004083 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004084 if (term->tl_status_text != NULL)
4085 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4086 term->tl_buffer->b_fname, txt);
4087 }
4088 return term->tl_status_text;
4089}
4090
4091/*
4092 * Mark references in jobs of terminals.
4093 */
4094 int
4095set_ref_in_term(int copyID)
4096{
4097 int abort = FALSE;
4098 term_T *term;
4099 typval_T tv;
4100
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004101 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004102 if (term->tl_job != NULL)
4103 {
4104 tv.v_type = VAR_JOB;
4105 tv.vval.v_job = term->tl_job;
4106 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4107 }
4108 return abort;
4109}
4110
4111/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004112 * Cache "Terminal" highlight group colors.
4113 */
4114 void
4115set_terminal_default_colors(int cterm_fg, int cterm_bg)
4116{
4117 term_default_cterm_fg = cterm_fg - 1;
4118 term_default_cterm_bg = cterm_bg - 1;
4119}
4120
4121/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004122 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004123 * Returns NULL when the buffer is not for a terminal window and logs a message
4124 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004125 */
4126 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004127term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004128{
4129 buf_T *buf;
4130
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004131 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004132 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004133 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004134 --emsg_off;
4135 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004136 {
4137 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004138 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004139 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004140 return buf;
4141}
4142
Bram Moolenaard96ff162018-02-18 22:13:29 +01004143 static int
4144same_color(VTermColor *a, VTermColor *b)
4145{
4146 return a->red == b->red
4147 && a->green == b->green
4148 && a->blue == b->blue
4149 && a->ansi_index == b->ansi_index;
4150}
4151
4152 static void
4153dump_term_color(FILE *fd, VTermColor *color)
4154{
4155 fprintf(fd, "%02x%02x%02x%d",
4156 (int)color->red, (int)color->green, (int)color->blue,
4157 (int)color->ansi_index);
4158}
4159
4160/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004161 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004162 *
4163 * Each screen cell in full is:
4164 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4165 * {characters} is a space for an empty cell
4166 * For a double-width character "+" is changed to "*" and the next cell is
4167 * skipped.
4168 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4169 * when "&" use the same as the previous cell.
4170 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4171 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4172 * {color-idx} is a number from 0 to 255
4173 *
4174 * Screen cell with same width, attributes and color as the previous one:
4175 * |{characters}
4176 *
4177 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4178 *
4179 * Repeating the previous screen cell:
4180 * @{count}
4181 */
4182 void
4183f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4184{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004185 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004186 term_T *term;
4187 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004188 int max_height = 0;
4189 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004190 stat_T st;
4191 FILE *fd;
4192 VTermPos pos;
4193 VTermScreen *screen;
4194 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004195 VTermState *state;
4196 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004197
4198 if (check_restricted() || check_secure())
4199 return;
4200 if (buf == NULL)
4201 return;
4202 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004203 if (term->tl_vterm == NULL)
4204 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004205 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004206 return;
4207 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004208
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004209 if (argvars[2].v_type != VAR_UNKNOWN)
4210 {
4211 dict_T *d;
4212
4213 if (argvars[2].v_type != VAR_DICT)
4214 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004215 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004216 return;
4217 }
4218 d = argvars[2].vval.v_dict;
4219 if (d != NULL)
4220 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004221 max_height = dict_get_number(d, (char_u *)"rows");
4222 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004223 }
4224 }
4225
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004226 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004227 if (fname == NULL)
4228 return;
4229 if (mch_stat((char *)fname, &st) >= 0)
4230 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004231 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004232 return;
4233 }
4234
Bram Moolenaard96ff162018-02-18 22:13:29 +01004235 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4236 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004237 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004238 return;
4239 }
4240
4241 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4242
4243 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004244 state = vterm_obtain_state(term->tl_vterm);
4245 vterm_state_get_cursorpos(state, &cursor_pos);
4246
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004247 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4248 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249 {
4250 int repeat = 0;
4251
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004252 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4253 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004254 {
4255 VTermScreenCell cell;
4256 int same_attr;
4257 int same_chars = TRUE;
4258 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004259 int is_cursor_pos = (pos.col == cursor_pos.col
4260 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004261
4262 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4263 vim_memset(&cell, 0, sizeof(cell));
4264
4265 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4266 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004267 int c = cell.chars[i];
4268 int pc = prev_cell.chars[i];
4269
4270 /* For the first character NUL is the same as space. */
4271 if (i == 0)
4272 {
4273 c = (c == NUL) ? ' ' : c;
4274 pc = (pc == NUL) ? ' ' : pc;
4275 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004276 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004277 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004278 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004279 break;
4280 }
4281 same_attr = vtermAttr2hl(cell.attrs)
4282 == vtermAttr2hl(prev_cell.attrs)
4283 && same_color(&cell.fg, &prev_cell.fg)
4284 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004285 if (same_chars && cell.width == prev_cell.width && same_attr
4286 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004287 {
4288 ++repeat;
4289 }
4290 else
4291 {
4292 if (repeat > 0)
4293 {
4294 fprintf(fd, "@%d", repeat);
4295 repeat = 0;
4296 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004297 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004298
4299 if (cell.chars[0] == NUL)
4300 fputs(" ", fd);
4301 else
4302 {
4303 char_u charbuf[10];
4304 int len;
4305
4306 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4307 && cell.chars[i] != NUL; ++i)
4308 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004309 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004310 fwrite(charbuf, len, 1, fd);
4311 }
4312 }
4313
4314 /* When only the characters differ we don't write anything, the
4315 * following "|", "@" or NL will indicate using the same
4316 * attributes. */
4317 if (cell.width != prev_cell.width || !same_attr)
4318 {
4319 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004321 else
4322 fputs("+", fd);
4323
4324 if (same_attr)
4325 {
4326 fputs("&", fd);
4327 }
4328 else
4329 {
4330 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4331 if (same_color(&cell.fg, &prev_cell.fg))
4332 fputs("&", fd);
4333 else
4334 {
4335 fputs("#", fd);
4336 dump_term_color(fd, &cell.fg);
4337 }
4338 if (same_color(&cell.bg, &prev_cell.bg))
4339 fputs("&", fd);
4340 else
4341 {
4342 fputs("#", fd);
4343 dump_term_color(fd, &cell.bg);
4344 }
4345 }
4346 }
4347
4348 prev_cell = cell;
4349 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004350
4351 if (cell.width == 2)
4352 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004353 }
4354 if (repeat > 0)
4355 fprintf(fd, "@%d", repeat);
4356 fputs("\n", fd);
4357 }
4358
4359 fclose(fd);
4360}
4361
4362/*
4363 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4364 */
4365 static void
4366dump_is_corrupt(garray_T *gap)
4367{
4368 ga_concat(gap, (char_u *)"CORRUPT");
4369}
4370
4371 static void
4372append_cell(garray_T *gap, cellattr_T *cell)
4373{
4374 if (ga_grow(gap, 1) == OK)
4375 {
4376 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4377 ++gap->ga_len;
4378 }
4379}
4380
4381/*
4382 * Read the dump file from "fd" and append lines to the current buffer.
4383 * Return the cell width of the longest line.
4384 */
4385 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004386read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004387{
4388 int c;
4389 garray_T ga_text;
4390 garray_T ga_cell;
4391 char_u *prev_char = NULL;
4392 int attr = 0;
4393 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004394 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004395 term_T *term = curbuf->b_term;
4396 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004397 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004398
4399 ga_init2(&ga_text, 1, 90);
4400 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4401 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004402 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004403 cursor_pos->row = -1;
4404 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004405
4406 c = fgetc(fd);
4407 for (;;)
4408 {
4409 if (c == EOF)
4410 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004411 if (c == '\r')
4412 {
4413 // DOS line endings? Ignore.
4414 c = fgetc(fd);
4415 }
4416 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004417 {
4418 /* End of a line: append it to the buffer. */
4419 if (ga_text.ga_data == NULL)
4420 dump_is_corrupt(&ga_text);
4421 if (ga_grow(&term->tl_scrollback, 1) == OK)
4422 {
4423 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4424 + term->tl_scrollback.ga_len;
4425
4426 if (max_cells < ga_cell.ga_len)
4427 max_cells = ga_cell.ga_len;
4428 line->sb_cols = ga_cell.ga_len;
4429 line->sb_cells = ga_cell.ga_data;
4430 line->sb_fill_attr = term->tl_default_color;
4431 ++term->tl_scrollback.ga_len;
4432 ga_init(&ga_cell);
4433
4434 ga_append(&ga_text, NUL);
4435 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4436 ga_text.ga_len, FALSE);
4437 }
4438 else
4439 ga_clear(&ga_cell);
4440 ga_text.ga_len = 0;
4441
4442 c = fgetc(fd);
4443 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004444 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004445 {
4446 int prev_len = ga_text.ga_len;
4447
Bram Moolenaar9271d052018-02-25 21:39:46 +01004448 if (c == '>')
4449 {
4450 if (cursor_pos->row != -1)
4451 dump_is_corrupt(&ga_text); /* duplicate cursor */
4452 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4453 cursor_pos->col = ga_cell.ga_len;
4454 }
4455
Bram Moolenaard96ff162018-02-18 22:13:29 +01004456 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4457 c = fgetc(fd);
4458 if (c != EOF)
4459 ga_append(&ga_text, c);
4460 for (;;)
4461 {
4462 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004463 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004464 || c == EOF || c == '\n')
4465 break;
4466 ga_append(&ga_text, c);
4467 }
4468
4469 /* save the character for repeating it */
4470 vim_free(prev_char);
4471 if (ga_text.ga_data != NULL)
4472 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4473 ga_text.ga_len - prev_len);
4474
Bram Moolenaar9271d052018-02-25 21:39:46 +01004475 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004476 {
4477 /* use all attributes from previous cell */
4478 }
4479 else if (c == '+' || c == '*')
4480 {
4481 int is_bg;
4482
4483 cell.width = c == '+' ? 1 : 2;
4484
4485 c = fgetc(fd);
4486 if (c == '&')
4487 {
4488 /* use same attr as previous cell */
4489 c = fgetc(fd);
4490 }
4491 else if (isdigit(c))
4492 {
4493 /* get the decimal attribute */
4494 attr = 0;
4495 while (isdigit(c))
4496 {
4497 attr = attr * 10 + (c - '0');
4498 c = fgetc(fd);
4499 }
4500 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004501
4502 /* is_bg == 0: fg, is_bg == 1: bg */
4503 for (is_bg = 0; is_bg <= 1; ++is_bg)
4504 {
4505 if (c == '&')
4506 {
4507 /* use same color as previous cell */
4508 c = fgetc(fd);
4509 }
4510 else if (c == '#')
4511 {
4512 int red, green, blue, index = 0;
4513
4514 c = fgetc(fd);
4515 red = hex2nr(c);
4516 c = fgetc(fd);
4517 red = (red << 4) + hex2nr(c);
4518 c = fgetc(fd);
4519 green = hex2nr(c);
4520 c = fgetc(fd);
4521 green = (green << 4) + hex2nr(c);
4522 c = fgetc(fd);
4523 blue = hex2nr(c);
4524 c = fgetc(fd);
4525 blue = (blue << 4) + hex2nr(c);
4526 c = fgetc(fd);
4527 if (!isdigit(c))
4528 dump_is_corrupt(&ga_text);
4529 while (isdigit(c))
4530 {
4531 index = index * 10 + (c - '0');
4532 c = fgetc(fd);
4533 }
4534
4535 if (is_bg)
4536 {
4537 cell.bg.red = red;
4538 cell.bg.green = green;
4539 cell.bg.blue = blue;
4540 cell.bg.ansi_index = index;
4541 }
4542 else
4543 {
4544 cell.fg.red = red;
4545 cell.fg.green = green;
4546 cell.fg.blue = blue;
4547 cell.fg.ansi_index = index;
4548 }
4549 }
4550 else
4551 dump_is_corrupt(&ga_text);
4552 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004553 }
4554 else
4555 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004556 }
4557 else
4558 dump_is_corrupt(&ga_text);
4559
4560 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004561 if (cell.width == 2)
4562 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004563 }
4564 else if (c == '@')
4565 {
4566 if (prev_char == NULL)
4567 dump_is_corrupt(&ga_text);
4568 else
4569 {
4570 int count = 0;
4571
4572 /* repeat previous character, get the count */
4573 for (;;)
4574 {
4575 c = fgetc(fd);
4576 if (!isdigit(c))
4577 break;
4578 count = count * 10 + (c - '0');
4579 }
4580
4581 while (count-- > 0)
4582 {
4583 ga_concat(&ga_text, prev_char);
4584 append_cell(&ga_cell, &cell);
4585 }
4586 }
4587 }
4588 else
4589 {
4590 dump_is_corrupt(&ga_text);
4591 c = fgetc(fd);
4592 }
4593 }
4594
4595 if (ga_text.ga_len > 0)
4596 {
4597 /* trailing characters after last NL */
4598 dump_is_corrupt(&ga_text);
4599 ga_append(&ga_text, NUL);
4600 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4601 ga_text.ga_len, FALSE);
4602 }
4603
4604 ga_clear(&ga_text);
4605 vim_free(prev_char);
4606
4607 return max_cells;
4608}
4609
4610/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004611 * Return an allocated string with at least "text_width" "=" characters and
4612 * "fname" inserted in the middle.
4613 */
4614 static char_u *
4615get_separator(int text_width, char_u *fname)
4616{
4617 int width = MAX(text_width, curwin->w_width);
4618 char_u *textline;
4619 int fname_size;
4620 char_u *p = fname;
4621 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004622 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004623
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004624 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004625 if (textline == NULL)
4626 return NULL;
4627
4628 fname_size = vim_strsize(fname);
4629 if (fname_size < width - 8)
4630 {
4631 /* enough room, don't use the full window width */
4632 width = MAX(text_width, fname_size + 8);
4633 }
4634 else if (fname_size > width - 8)
4635 {
4636 /* full name doesn't fit, use only the tail */
4637 p = gettail(fname);
4638 fname_size = vim_strsize(p);
4639 }
4640 /* skip characters until the name fits */
4641 while (fname_size > width - 8)
4642 {
4643 p += (*mb_ptr2len)(p);
4644 fname_size = vim_strsize(p);
4645 }
4646
4647 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4648 textline[i] = '=';
4649 textline[i++] = ' ';
4650
4651 STRCPY(textline + i, p);
4652 off = STRLEN(textline);
4653 textline[off] = ' ';
4654 for (i = 1; i < (width - fname_size) / 2; ++i)
4655 textline[off + i] = '=';
4656 textline[off + i] = NUL;
4657
4658 return textline;
4659}
4660
4661/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004662 * Common for "term_dumpdiff()" and "term_dumpload()".
4663 */
4664 static void
4665term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4666{
4667 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004668 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004669 char_u buf1[NUMBUFLEN];
4670 char_u buf2[NUMBUFLEN];
4671 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004672 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004673 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004674 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004675 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004676 char_u *textline = NULL;
4677
4678 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004679 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004680 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004681 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004682 if (fname1 == NULL || (do_diff && fname2 == NULL))
4683 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004684 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004685 return;
4686 }
4687 fd1 = mch_fopen((char *)fname1, READBIN);
4688 if (fd1 == NULL)
4689 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004690 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004691 return;
4692 }
4693 if (do_diff)
4694 {
4695 fd2 = mch_fopen((char *)fname2, READBIN);
4696 if (fd2 == NULL)
4697 {
4698 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004699 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004700 return;
4701 }
4702 }
4703
4704 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004705 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4706 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4707 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4708 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4709 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004710
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004711 if (opt.jo_term_name == NULL)
4712 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004713 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004714
Bram Moolenaar51e14382019-05-25 20:21:28 +02004715 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004716 if (fname_tofree != NULL)
4717 {
4718 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4719 opt.jo_term_name = fname_tofree;
4720 }
4721 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004722
Bram Moolenaar87abab92019-06-03 21:14:59 +02004723 if (opt.jo_bufnr_buf != NULL)
4724 {
4725 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4726
4727 // With "bufnr" argument: enter the window with this buffer and make it
4728 // empty.
4729 if (wp == NULL)
4730 semsg(_(e_invarg2), "bufnr");
4731 else
4732 {
4733 buf = curbuf;
4734 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4735 ml_delete((linenr_T)1, FALSE);
4736 ga_clear(&curbuf->b_term->tl_scrollback);
4737 redraw_later(NOT_VALID);
4738 }
4739 }
4740 else
4741 // Create a new terminal window.
4742 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4743
Bram Moolenaard96ff162018-02-18 22:13:29 +01004744 if (buf != NULL && buf->b_term != NULL)
4745 {
4746 int i;
4747 linenr_T bot_lnum;
4748 linenr_T lnum;
4749 term_T *term = buf->b_term;
4750 int width;
4751 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004752 VTermPos cursor_pos1;
4753 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004754
Bram Moolenaar52acb112018-03-18 19:20:22 +01004755 init_default_colors(term);
4756
Bram Moolenaard96ff162018-02-18 22:13:29 +01004757 rettv->vval.v_number = buf->b_fnum;
4758
4759 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004760 width = read_dump_file(fd1, &cursor_pos1);
4761
4762 /* position the cursor */
4763 if (cursor_pos1.row >= 0)
4764 {
4765 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4766 coladvance(cursor_pos1.col);
4767 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004768
4769 /* Delete the empty line that was in the empty buffer. */
4770 ml_delete(1, FALSE);
4771
4772 /* For term_dumpload() we are done here. */
4773 if (!do_diff)
4774 goto theend;
4775
4776 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4777
Bram Moolenaar4a696342018-04-05 18:45:26 +02004778 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004779 if (textline == NULL)
4780 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004781 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4782 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4783 vim_free(textline);
4784
4785 textline = get_separator(width, fname2);
4786 if (textline == NULL)
4787 goto theend;
4788 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4789 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004790 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004791
4792 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004793 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004794 if (width2 > width)
4795 {
4796 vim_free(textline);
4797 textline = alloc(width2 + 1);
4798 if (textline == NULL)
4799 goto theend;
4800 width = width2;
4801 textline[width] = NUL;
4802 }
4803 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4804
4805 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4806 {
4807 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4808 {
4809 /* bottom part has fewer rows, fill with "-" */
4810 for (i = 0; i < width; ++i)
4811 textline[i] = '-';
4812 }
4813 else
4814 {
4815 char_u *line1;
4816 char_u *line2;
4817 char_u *p1;
4818 char_u *p2;
4819 int col;
4820 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4821 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4822 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4823 ->sb_cells;
4824
4825 /* Make a copy, getting the second line will invalidate it. */
4826 line1 = vim_strsave(ml_get(lnum));
4827 if (line1 == NULL)
4828 break;
4829 p1 = line1;
4830
4831 line2 = ml_get(lnum + bot_lnum);
4832 p2 = line2;
4833 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4834 {
4835 int len1 = utfc_ptr2len(p1);
4836 int len2 = utfc_ptr2len(p2);
4837
4838 textline[col] = ' ';
4839 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004840 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004841 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004842 else if (lnum == cursor_pos1.row + 1
4843 && col == cursor_pos1.col
4844 && (cursor_pos1.row != cursor_pos2.row
4845 || cursor_pos1.col != cursor_pos2.col))
4846 /* cursor in first but not in second */
4847 textline[col] = '>';
4848 else if (lnum == cursor_pos2.row + 1
4849 && col == cursor_pos2.col
4850 && (cursor_pos1.row != cursor_pos2.row
4851 || cursor_pos1.col != cursor_pos2.col))
4852 /* cursor in second but not in first */
4853 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004854 else if (cellattr1 != NULL && cellattr2 != NULL)
4855 {
4856 if ((cellattr1 + col)->width
4857 != (cellattr2 + col)->width)
4858 textline[col] = 'w';
4859 else if (!same_color(&(cellattr1 + col)->fg,
4860 &(cellattr2 + col)->fg))
4861 textline[col] = 'f';
4862 else if (!same_color(&(cellattr1 + col)->bg,
4863 &(cellattr2 + col)->bg))
4864 textline[col] = 'b';
4865 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4866 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4867 textline[col] = 'a';
4868 }
4869 p1 += len1;
4870 p2 += len2;
4871 /* TODO: handle different width */
4872 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004873
4874 while (col < width)
4875 {
4876 if (*p1 == NUL && *p2 == NUL)
4877 textline[col] = '?';
4878 else if (*p1 == NUL)
4879 {
4880 textline[col] = '+';
4881 p2 += utfc_ptr2len(p2);
4882 }
4883 else
4884 {
4885 textline[col] = '-';
4886 p1 += utfc_ptr2len(p1);
4887 }
4888 ++col;
4889 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004890
4891 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004892 }
4893 if (add_empty_scrollback(term, &term->tl_default_color,
4894 term->tl_top_diff_rows) == OK)
4895 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4896 ++bot_lnum;
4897 }
4898
4899 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4900 {
4901 /* bottom part has more rows, fill with "+" */
4902 for (i = 0; i < width; ++i)
4903 textline[i] = '+';
4904 if (add_empty_scrollback(term, &term->tl_default_color,
4905 term->tl_top_diff_rows) == OK)
4906 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4907 ++lnum;
4908 ++bot_lnum;
4909 }
4910
4911 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004912
4913 /* looks better without wrapping */
4914 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004915 }
4916
4917theend:
4918 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004919 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004920 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004921 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004922 fclose(fd2);
4923}
4924
4925/*
4926 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4927 * bottom files.
4928 * Return FAIL when this is not possible.
4929 */
4930 int
4931term_swap_diff()
4932{
4933 term_T *term = curbuf->b_term;
4934 linenr_T line_count;
4935 linenr_T top_rows;
4936 linenr_T bot_rows;
4937 linenr_T bot_start;
4938 linenr_T lnum;
4939 char_u *p;
4940 sb_line_T *sb_line;
4941
4942 if (term == NULL
4943 || !term_is_finished(curbuf)
4944 || term->tl_top_diff_rows == 0
4945 || term->tl_scrollback.ga_len == 0)
4946 return FAIL;
4947
4948 line_count = curbuf->b_ml.ml_line_count;
4949 top_rows = term->tl_top_diff_rows;
4950 bot_rows = term->tl_bot_diff_rows;
4951 bot_start = line_count - bot_rows;
4952 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4953
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004954 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01004955 for (lnum = 1; lnum <= top_rows; ++lnum)
4956 {
4957 p = vim_strsave(ml_get(1));
4958 if (p == NULL)
4959 return OK;
4960 ml_append(bot_start, p, 0, FALSE);
4961 ml_delete(1, FALSE);
4962 vim_free(p);
4963 }
4964
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004965 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01004966 for (lnum = 1; lnum <= bot_rows; ++lnum)
4967 {
4968 p = vim_strsave(ml_get(bot_start + lnum));
4969 if (p == NULL)
4970 return OK;
4971 ml_delete(bot_start + lnum, FALSE);
4972 ml_append(lnum - 1, p, 0, FALSE);
4973 vim_free(p);
4974 }
4975
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01004976 // move top title to bottom
4977 p = vim_strsave(ml_get(bot_rows + 1));
4978 if (p == NULL)
4979 return OK;
4980 ml_append(line_count - top_rows - 1, p, 0, FALSE);
4981 ml_delete(bot_rows + 1, FALSE);
4982 vim_free(p);
4983
4984 // move bottom title to top
4985 p = vim_strsave(ml_get(line_count - top_rows));
4986 if (p == NULL)
4987 return OK;
4988 ml_delete(line_count - top_rows, FALSE);
4989 ml_append(bot_rows, p, 0, FALSE);
4990 vim_free(p);
4991
Bram Moolenaard96ff162018-02-18 22:13:29 +01004992 if (top_rows == bot_rows)
4993 {
4994 /* rows counts are equal, can swap cell properties */
4995 for (lnum = 0; lnum < top_rows; ++lnum)
4996 {
4997 sb_line_T temp;
4998
4999 temp = *(sb_line + lnum);
5000 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5001 *(sb_line + bot_start + lnum) = temp;
5002 }
5003 }
5004 else
5005 {
5006 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005007 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005008
5009 /* need to copy cell properties into temp memory */
5010 if (temp != NULL)
5011 {
5012 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5013 mch_memmove(term->tl_scrollback.ga_data,
5014 temp + bot_start,
5015 sizeof(sb_line_T) * bot_rows);
5016 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5017 temp + top_rows,
5018 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5019 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5020 + line_count - top_rows,
5021 temp,
5022 sizeof(sb_line_T) * top_rows);
5023 vim_free(temp);
5024 }
5025 }
5026
5027 term->tl_top_diff_rows = bot_rows;
5028 term->tl_bot_diff_rows = top_rows;
5029
5030 update_screen(NOT_VALID);
5031 return OK;
5032}
5033
5034/*
5035 * "term_dumpdiff(filename, filename, options)" function
5036 */
5037 void
5038f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5039{
5040 term_load_dump(argvars, rettv, TRUE);
5041}
5042
5043/*
5044 * "term_dumpload(filename, options)" function
5045 */
5046 void
5047f_term_dumpload(typval_T *argvars, typval_T *rettv)
5048{
5049 term_load_dump(argvars, rettv, FALSE);
5050}
5051
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005052/*
5053 * "term_getaltscreen(buf)" function
5054 */
5055 void
5056f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5057{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005058 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005059
5060 if (buf == NULL)
5061 return;
5062 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5063}
5064
5065/*
5066 * "term_getattr(attr, name)" function
5067 */
5068 void
5069f_term_getattr(typval_T *argvars, typval_T *rettv)
5070{
5071 int attr;
5072 size_t i;
5073 char_u *name;
5074
5075 static struct {
5076 char *name;
5077 int attr;
5078 } attrs[] = {
5079 {"bold", HL_BOLD},
5080 {"italic", HL_ITALIC},
5081 {"underline", HL_UNDERLINE},
5082 {"strike", HL_STRIKETHROUGH},
5083 {"reverse", HL_INVERSE},
5084 };
5085
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005086 attr = tv_get_number(&argvars[0]);
5087 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005088 if (name == NULL)
5089 return;
5090
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005091 if (attr > HL_ALL)
5092 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005093 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5094 if (STRCMP(name, attrs[i].name) == 0)
5095 {
5096 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5097 break;
5098 }
5099}
5100
5101/*
5102 * "term_getcursor(buf)" function
5103 */
5104 void
5105f_term_getcursor(typval_T *argvars, typval_T *rettv)
5106{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005107 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005108 term_T *term;
5109 list_T *l;
5110 dict_T *d;
5111
5112 if (rettv_list_alloc(rettv) == FAIL)
5113 return;
5114 if (buf == NULL)
5115 return;
5116 term = buf->b_term;
5117
5118 l = rettv->vval.v_list;
5119 list_append_number(l, term->tl_cursor_pos.row + 1);
5120 list_append_number(l, term->tl_cursor_pos.col + 1);
5121
5122 d = dict_alloc();
5123 if (d != NULL)
5124 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005125 dict_add_number(d, "visible", term->tl_cursor_visible);
5126 dict_add_number(d, "blink", blink_state_is_inverted()
5127 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5128 dict_add_number(d, "shape", term->tl_cursor_shape);
5129 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005130 list_append_dict(l, d);
5131 }
5132}
5133
5134/*
5135 * "term_getjob(buf)" function
5136 */
5137 void
5138f_term_getjob(typval_T *argvars, typval_T *rettv)
5139{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005140 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005141
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005142 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005143 {
5144 rettv->v_type = VAR_SPECIAL;
5145 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005146 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005147 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005148
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005149 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005150 rettv->vval.v_job = buf->b_term->tl_job;
5151 if (rettv->vval.v_job != NULL)
5152 ++rettv->vval.v_job->jv_refcount;
5153}
5154
5155 static int
5156get_row_number(typval_T *tv, term_T *term)
5157{
5158 if (tv->v_type == VAR_STRING
5159 && tv->vval.v_string != NULL
5160 && STRCMP(tv->vval.v_string, ".") == 0)
5161 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005162 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005163}
5164
5165/*
5166 * "term_getline(buf, row)" function
5167 */
5168 void
5169f_term_getline(typval_T *argvars, typval_T *rettv)
5170{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005171 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005172 term_T *term;
5173 int row;
5174
5175 rettv->v_type = VAR_STRING;
5176 if (buf == NULL)
5177 return;
5178 term = buf->b_term;
5179 row = get_row_number(&argvars[1], term);
5180
5181 if (term->tl_vterm == NULL)
5182 {
5183 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5184
5185 /* vterm is finished, get the text from the buffer */
5186 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5187 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5188 }
5189 else
5190 {
5191 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5192 VTermRect rect;
5193 int len;
5194 char_u *p;
5195
5196 if (row < 0 || row >= term->tl_rows)
5197 return;
5198 len = term->tl_cols * MB_MAXBYTES + 1;
5199 p = alloc(len);
5200 if (p == NULL)
5201 return;
5202 rettv->vval.v_string = p;
5203
5204 rect.start_col = 0;
5205 rect.end_col = term->tl_cols;
5206 rect.start_row = row;
5207 rect.end_row = row + 1;
5208 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5209 }
5210}
5211
5212/*
5213 * "term_getscrolled(buf)" function
5214 */
5215 void
5216f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5217{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005218 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005219
5220 if (buf == NULL)
5221 return;
5222 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5223}
5224
5225/*
5226 * "term_getsize(buf)" function
5227 */
5228 void
5229f_term_getsize(typval_T *argvars, typval_T *rettv)
5230{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005231 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005232 list_T *l;
5233
5234 if (rettv_list_alloc(rettv) == FAIL)
5235 return;
5236 if (buf == NULL)
5237 return;
5238
5239 l = rettv->vval.v_list;
5240 list_append_number(l, buf->b_term->tl_rows);
5241 list_append_number(l, buf->b_term->tl_cols);
5242}
5243
5244/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005245 * "term_setsize(buf, rows, cols)" function
5246 */
5247 void
5248f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5249{
5250 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5251 term_T *term;
5252 varnumber_T rows, cols;
5253
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005254 if (buf == NULL)
5255 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005256 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005257 return;
5258 }
5259 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005260 return;
5261 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005262 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005263 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005264 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005265 cols = cols <= 0 ? term->tl_cols : cols;
5266 vterm_set_size(term->tl_vterm, rows, cols);
5267 /* handle_resize() will resize the windows */
5268
5269 /* Get and remember the size we ended up with. Update the pty. */
5270 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5271 term_report_winsize(term, term->tl_rows, term->tl_cols);
5272}
5273
5274/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005275 * "term_getstatus(buf)" function
5276 */
5277 void
5278f_term_getstatus(typval_T *argvars, typval_T *rettv)
5279{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005280 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005281 term_T *term;
5282 char_u val[100];
5283
5284 rettv->v_type = VAR_STRING;
5285 if (buf == NULL)
5286 return;
5287 term = buf->b_term;
5288
5289 if (term_job_running(term))
5290 STRCPY(val, "running");
5291 else
5292 STRCPY(val, "finished");
5293 if (term->tl_normal_mode)
5294 STRCAT(val, ",normal");
5295 rettv->vval.v_string = vim_strsave(val);
5296}
5297
5298/*
5299 * "term_gettitle(buf)" function
5300 */
5301 void
5302f_term_gettitle(typval_T *argvars, typval_T *rettv)
5303{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005304 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005305
5306 rettv->v_type = VAR_STRING;
5307 if (buf == NULL)
5308 return;
5309
5310 if (buf->b_term->tl_title != NULL)
5311 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5312}
5313
5314/*
5315 * "term_gettty(buf)" function
5316 */
5317 void
5318f_term_gettty(typval_T *argvars, typval_T *rettv)
5319{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005320 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005321 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005322 int num = 0;
5323
5324 rettv->v_type = VAR_STRING;
5325 if (buf == NULL)
5326 return;
5327 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005328 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005329
5330 switch (num)
5331 {
5332 case 0:
5333 if (buf->b_term->tl_job != NULL)
5334 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005335 break;
5336 case 1:
5337 if (buf->b_term->tl_job != NULL)
5338 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005339 break;
5340 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005341 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005342 return;
5343 }
5344 if (p != NULL)
5345 rettv->vval.v_string = vim_strsave(p);
5346}
5347
5348/*
5349 * "term_list()" function
5350 */
5351 void
5352f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5353{
5354 term_T *tp;
5355 list_T *l;
5356
5357 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5358 return;
5359
5360 l = rettv->vval.v_list;
5361 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5362 if (tp != NULL && tp->tl_buffer != NULL)
5363 if (list_append_number(l,
5364 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5365 return;
5366}
5367
5368/*
5369 * "term_scrape(buf, row)" function
5370 */
5371 void
5372f_term_scrape(typval_T *argvars, typval_T *rettv)
5373{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005374 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005375 VTermScreen *screen = NULL;
5376 VTermPos pos;
5377 list_T *l;
5378 term_T *term;
5379 char_u *p;
5380 sb_line_T *line;
5381
5382 if (rettv_list_alloc(rettv) == FAIL)
5383 return;
5384 if (buf == NULL)
5385 return;
5386 term = buf->b_term;
5387
5388 l = rettv->vval.v_list;
5389 pos.row = get_row_number(&argvars[1], term);
5390
5391 if (term->tl_vterm != NULL)
5392 {
5393 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005394 if (screen == NULL) // can't really happen
5395 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005396 p = NULL;
5397 line = NULL;
5398 }
5399 else
5400 {
5401 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5402
5403 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5404 return;
5405 p = ml_get_buf(buf, lnum + 1, FALSE);
5406 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5407 }
5408
5409 for (pos.col = 0; pos.col < term->tl_cols; )
5410 {
5411 dict_T *dcell;
5412 int width;
5413 VTermScreenCellAttrs attrs;
5414 VTermColor fg, bg;
5415 char_u rgb[8];
5416 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5417 int off = 0;
5418 int i;
5419
5420 if (screen == NULL)
5421 {
5422 cellattr_T *cellattr;
5423 int len;
5424
5425 /* vterm has finished, get the cell from scrollback */
5426 if (pos.col >= line->sb_cols)
5427 break;
5428 cellattr = line->sb_cells + pos.col;
5429 width = cellattr->width;
5430 attrs = cellattr->attrs;
5431 fg = cellattr->fg;
5432 bg = cellattr->bg;
5433 len = MB_PTR2LEN(p);
5434 mch_memmove(mbs, p, len);
5435 mbs[len] = NUL;
5436 p += len;
5437 }
5438 else
5439 {
5440 VTermScreenCell cell;
5441 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5442 break;
5443 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5444 {
5445 if (cell.chars[i] == 0)
5446 break;
5447 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5448 }
5449 mbs[off] = NUL;
5450 width = cell.width;
5451 attrs = cell.attrs;
5452 fg = cell.fg;
5453 bg = cell.bg;
5454 }
5455 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005456 if (dcell == NULL)
5457 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005458 list_append_dict(l, dcell);
5459
Bram Moolenaare0be1672018-07-08 16:50:37 +02005460 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005461
5462 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5463 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005464 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005465 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5466 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005467 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005468
Bram Moolenaare0be1672018-07-08 16:50:37 +02005469 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5470 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005471
5472 ++pos.col;
5473 if (width == 2)
5474 ++pos.col;
5475 }
5476}
5477
5478/*
5479 * "term_sendkeys(buf, keys)" function
5480 */
5481 void
5482f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5483{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005484 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005485 char_u *msg;
5486 term_T *term;
5487
5488 rettv->v_type = VAR_UNKNOWN;
5489 if (buf == NULL)
5490 return;
5491
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005492 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493 if (msg == NULL)
5494 return;
5495 term = buf->b_term;
5496 if (term->tl_vterm == NULL)
5497 return;
5498
5499 while (*msg != NUL)
5500 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005501 int c;
5502
5503 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5504 {
5505 c = TO_SPECIAL(msg[1], msg[2]);
5506 msg += 3;
5507 }
5508 else
5509 {
5510 c = PTR2CHAR(msg);
5511 msg += MB_CPTR2LEN(msg);
5512 }
5513 send_keys_to_term(term, c, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005514 }
5515}
5516
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005517#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5518/*
5519 * "term_getansicolors(buf)" function
5520 */
5521 void
5522f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5523{
5524 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5525 term_T *term;
5526 VTermState *state;
5527 VTermColor color;
5528 char_u hexbuf[10];
5529 int index;
5530 list_T *list;
5531
5532 if (rettv_list_alloc(rettv) == FAIL)
5533 return;
5534
5535 if (buf == NULL)
5536 return;
5537 term = buf->b_term;
5538 if (term->tl_vterm == NULL)
5539 return;
5540
5541 list = rettv->vval.v_list;
5542 state = vterm_obtain_state(term->tl_vterm);
5543 for (index = 0; index < 16; index++)
5544 {
5545 vterm_state_get_palette_color(state, index, &color);
5546 sprintf((char *)hexbuf, "#%02x%02x%02x",
5547 color.red, color.green, color.blue);
5548 if (list_append_string(list, hexbuf, 7) == FAIL)
5549 return;
5550 }
5551}
5552
5553/*
5554 * "term_setansicolors(buf, list)" function
5555 */
5556 void
5557f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5558{
5559 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5560 term_T *term;
5561
5562 if (buf == NULL)
5563 return;
5564 term = buf->b_term;
5565 if (term->tl_vterm == NULL)
5566 return;
5567
5568 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5569 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005570 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005571 return;
5572 }
5573
5574 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005575 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005576}
5577#endif
5578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005579/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005580 * "term_setapi(buf, api)" function
5581 */
5582 void
5583f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5584{
5585 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5586 term_T *term;
5587 char_u *api;
5588
5589 if (buf == NULL)
5590 return;
5591 term = buf->b_term;
5592 vim_free(term->tl_api);
5593 api = tv_get_string_chk(&argvars[1]);
5594 if (api != NULL)
5595 term->tl_api = vim_strsave(api);
5596 else
5597 term->tl_api = NULL;
5598}
5599
5600/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005601 * "term_setrestore(buf, command)" function
5602 */
5603 void
5604f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5605{
5606#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005607 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005608 term_T *term;
5609 char_u *cmd;
5610
5611 if (buf == NULL)
5612 return;
5613 term = buf->b_term;
5614 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005615 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005616 if (cmd != NULL)
5617 term->tl_command = vim_strsave(cmd);
5618 else
5619 term->tl_command = NULL;
5620#endif
5621}
5622
5623/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005624 * "term_setkill(buf, how)" function
5625 */
5626 void
5627f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5628{
5629 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5630 term_T *term;
5631 char_u *how;
5632
5633 if (buf == NULL)
5634 return;
5635 term = buf->b_term;
5636 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005637 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005638 if (how != NULL)
5639 term->tl_kill = vim_strsave(how);
5640 else
5641 term->tl_kill = NULL;
5642}
5643
5644/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005645 * "term_start(command, options)" function
5646 */
5647 void
5648f_term_start(typval_T *argvars, typval_T *rettv)
5649{
5650 jobopt_T opt;
5651 buf_T *buf;
5652
5653 init_job_options(&opt);
5654 if (argvars[1].v_type != VAR_UNKNOWN
5655 && get_job_options(&argvars[1], &opt,
5656 JO_TIMEOUT_ALL + JO_STOPONEXIT
5657 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5658 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5659 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5660 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005661 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005662 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005663 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005664 return;
5665
Bram Moolenaar13568252018-03-16 20:46:58 +01005666 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005667
5668 if (buf != NULL && buf->b_term != NULL)
5669 rettv->vval.v_number = buf->b_fnum;
5670}
5671
5672/*
5673 * "term_wait" function
5674 */
5675 void
5676f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5677{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005678 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005679
5680 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005681 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005682 if (buf->b_term->tl_job == NULL)
5683 {
5684 ch_log(NULL, "term_wait(): no job to wait for");
5685 return;
5686 }
5687 if (buf->b_term->tl_job->jv_channel == NULL)
5688 /* channel is closed, nothing to do */
5689 return;
5690
5691 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005692 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005693 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5694 {
5695 /* The job is dead, keep reading channel I/O until the channel is
5696 * closed. buf->b_term may become NULL if the terminal was closed while
5697 * waiting. */
5698 ch_log(NULL, "term_wait(): waiting for channel to close");
5699 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5700 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005701 term_flush_messages();
5702
Bram Moolenaard45aa552018-05-21 22:50:29 +02005703 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005704 if (!buf_valid(buf))
5705 /* If the terminal is closed when the channel is closed the
5706 * buffer disappears. */
5707 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005708 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005709
5710 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005711 }
5712 else
5713 {
5714 long wait = 10L;
5715
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005716 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005717
5718 /* Wait for some time for any channel I/O. */
5719 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005720 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005721 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005722
5723 /* Flushing messages on channels is hopefully sufficient.
5724 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005725 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005726 }
5727}
5728
5729/*
5730 * Called when a channel has sent all the lines to a terminal.
5731 * Send a CTRL-D to mark the end of the text.
5732 */
5733 void
5734term_send_eof(channel_T *ch)
5735{
5736 term_T *term;
5737
5738 for (term = first_term; term != NULL; term = term->tl_next)
5739 if (term->tl_job == ch->ch_job)
5740 {
5741 if (term->tl_eof_chars != NULL)
5742 {
5743 channel_send(ch, PART_IN, term->tl_eof_chars,
5744 (int)STRLEN(term->tl_eof_chars), NULL);
5745 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5746 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005747# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005748 else
5749 /* Default: CTRL-D */
5750 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5751# endif
5752 }
5753}
5754
Bram Moolenaar113e1072019-01-20 15:30:40 +01005755#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005756 job_T *
5757term_getjob(term_T *term)
5758{
5759 return term != NULL ? term->tl_job : NULL;
5760}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005761#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005762
Bram Moolenaar4f974752019-02-17 17:44:42 +01005763# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005764
5765/**************************************
5766 * 2. MS-Windows implementation.
5767 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005768#ifdef PROTO
5769typedef int COORD;
5770typedef int DWORD;
5771typedef int HANDLE;
5772typedef int *DWORD_PTR;
5773typedef int HPCON;
5774typedef int HRESULT;
5775typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005776typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005777typedef int PSIZE_T;
5778typedef int PVOID;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005779typedef int WINAPI;
5780#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005781
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005782HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5783HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5784HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005785BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5786BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5787void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005788
5789 static int
5790dyn_conpty_init(int verbose)
5791{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005792 static HMODULE hKerneldll = NULL;
5793 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005794 static struct
5795 {
5796 char *name;
5797 FARPROC *ptr;
5798 } conpty_entry[] =
5799 {
5800 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5801 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5802 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5803 {"InitializeProcThreadAttributeList",
5804 (FARPROC*)&pInitializeProcThreadAttributeList},
5805 {"UpdateProcThreadAttribute",
5806 (FARPROC*)&pUpdateProcThreadAttribute},
5807 {"DeleteProcThreadAttributeList",
5808 (FARPROC*)&pDeleteProcThreadAttributeList},
5809 {NULL, NULL}
5810 };
5811
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005812 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005813 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005814 if (verbose)
5815 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005816 return FAIL;
5817 }
5818
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005819 // No need to initialize twice.
5820 if (hKerneldll)
5821 return OK;
5822
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005823 hKerneldll = vimLoadLib("kernel32.dll");
5824 for (i = 0; conpty_entry[i].name != NULL
5825 && conpty_entry[i].ptr != NULL; ++i)
5826 {
5827 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5828 conpty_entry[i].name)) == NULL)
5829 {
5830 if (verbose)
5831 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005832 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005833 return FAIL;
5834 }
5835 }
5836
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005837 return OK;
5838}
5839
5840 static int
5841conpty_term_and_job_init(
5842 term_T *term,
5843 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005844 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005845 jobopt_T *opt,
5846 jobopt_T *orig_opt)
5847{
5848 WCHAR *cmd_wchar = NULL;
5849 WCHAR *cmd_wchar_copy = NULL;
5850 WCHAR *cwd_wchar = NULL;
5851 WCHAR *env_wchar = NULL;
5852 channel_T *channel = NULL;
5853 job_T *job = NULL;
5854 HANDLE jo = NULL;
5855 garray_T ga_cmd, ga_env;
5856 char_u *cmd = NULL;
5857 HRESULT hr;
5858 COORD consize;
5859 SIZE_T breq;
5860 PROCESS_INFORMATION proc_info;
5861 HANDLE i_theirs = NULL;
5862 HANDLE o_theirs = NULL;
5863 HANDLE i_ours = NULL;
5864 HANDLE o_ours = NULL;
5865
5866 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5867 ga_init2(&ga_env, (int)sizeof(char*), 20);
5868
5869 if (argvar->v_type == VAR_STRING)
5870 {
5871 cmd = argvar->vval.v_string;
5872 }
5873 else if (argvar->v_type == VAR_LIST)
5874 {
5875 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5876 goto failed;
5877 cmd = ga_cmd.ga_data;
5878 }
5879 if (cmd == NULL || *cmd == NUL)
5880 {
5881 emsg(_(e_invarg));
5882 goto failed;
5883 }
5884
5885 term->tl_arg0_cmd = vim_strsave(cmd);
5886
5887 cmd_wchar = enc_to_utf16(cmd, NULL);
5888
5889 if (cmd_wchar != NULL)
5890 {
5891 /* Request by CreateProcessW */
5892 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005893 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005894 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5895 }
5896
5897 ga_clear(&ga_cmd);
5898 if (cmd_wchar == NULL)
5899 goto failed;
5900 if (opt->jo_cwd != NULL)
5901 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5902
5903 win32_build_env(opt->jo_env, &ga_env, TRUE);
5904 env_wchar = ga_env.ga_data;
5905
5906 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5907 goto failed;
5908 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5909 goto failed;
5910
5911 consize.X = term->tl_cols;
5912 consize.Y = term->tl_rows;
5913 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5914 &term->tl_conpty);
5915 if (FAILED(hr))
5916 goto failed;
5917
5918 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5919
5920 /* Set up pipe inheritance safely: Vista or later. */
5921 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005922 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005923 if (!term->tl_siex.lpAttributeList)
5924 goto failed;
5925 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5926 0, &breq))
5927 goto failed;
5928 if (!pUpdateProcThreadAttribute(
5929 term->tl_siex.lpAttributeList, 0,
5930 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5931 sizeof(HPCON), NULL, NULL))
5932 goto failed;
5933
5934 channel = add_channel();
5935 if (channel == NULL)
5936 goto failed;
5937
5938 job = job_alloc();
5939 if (job == NULL)
5940 goto failed;
5941 if (argvar->v_type == VAR_STRING)
5942 {
5943 int argc;
5944
5945 build_argv_from_string(cmd, &job->jv_argv, &argc);
5946 }
5947 else
5948 {
5949 int argc;
5950
5951 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5952 }
5953
5954 if (opt->jo_set & JO_IN_BUF)
5955 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5956
5957 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
5958 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
5959 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
5960 | CREATE_DEFAULT_ERROR_MODE,
5961 env_wchar, cwd_wchar,
5962 &term->tl_siex.StartupInfo, &proc_info))
5963 goto failed;
5964
5965 CloseHandle(i_theirs);
5966 CloseHandle(o_theirs);
5967
5968 channel_set_pipes(channel,
5969 (sock_T)i_ours,
5970 (sock_T)o_ours,
5971 (sock_T)o_ours);
5972
5973 /* Write lines with CR instead of NL. */
5974 channel->ch_write_text_mode = TRUE;
5975
5976 /* Use to explicitly delete anonymous pipe handle. */
5977 channel->ch_anonymous_pipe = TRUE;
5978
5979 jo = CreateJobObject(NULL, NULL);
5980 if (jo == NULL)
5981 goto failed;
5982
5983 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
5984 {
5985 /* Failed, switch the way to terminate process with TerminateProcess. */
5986 CloseHandle(jo);
5987 jo = NULL;
5988 }
5989
5990 ResumeThread(proc_info.hThread);
5991 CloseHandle(proc_info.hThread);
5992
5993 vim_free(cmd_wchar);
5994 vim_free(cmd_wchar_copy);
5995 vim_free(cwd_wchar);
5996 vim_free(env_wchar);
5997
5998 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
5999 goto failed;
6000
6001#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6002 if (opt->jo_set2 & JO2_ANSI_COLORS)
6003 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6004 else
6005 init_vterm_ansi_colors(term->tl_vterm);
6006#endif
6007
6008 channel_set_job(channel, job, opt);
6009 job_set_options(job, opt);
6010
6011 job->jv_channel = channel;
6012 job->jv_proc_info = proc_info;
6013 job->jv_job_object = jo;
6014 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006015 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006016 ++job->jv_refcount;
6017 term->tl_job = job;
6018
6019 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6020 * open the file here and handle it in. opt->jo_io was changed in
6021 * setup_job_options(), use the original flags here. */
6022 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6023 {
6024 char_u *fname = opt->jo_io_name[PART_OUT];
6025
6026 ch_log(channel, "Opening output file %s", fname);
6027 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6028 if (term->tl_out_fd == NULL)
6029 semsg(_(e_notopen), fname);
6030 }
6031
6032 return OK;
6033
6034failed:
6035 ga_clear(&ga_cmd);
6036 ga_clear(&ga_env);
6037 vim_free(cmd_wchar);
6038 vim_free(cmd_wchar_copy);
6039 vim_free(cwd_wchar);
6040 if (channel != NULL)
6041 channel_clear(channel);
6042 if (job != NULL)
6043 {
6044 job->jv_channel = NULL;
6045 job_cleanup(job);
6046 }
6047 term->tl_job = NULL;
6048 if (jo != NULL)
6049 CloseHandle(jo);
6050
6051 if (term->tl_siex.lpAttributeList != NULL)
6052 {
6053 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6054 vim_free(term->tl_siex.lpAttributeList);
6055 }
6056 term->tl_siex.lpAttributeList = NULL;
6057 if (o_theirs != NULL)
6058 CloseHandle(o_theirs);
6059 if (o_ours != NULL)
6060 CloseHandle(o_ours);
6061 if (i_ours != NULL)
6062 CloseHandle(i_ours);
6063 if (i_theirs != NULL)
6064 CloseHandle(i_theirs);
6065 if (term->tl_conpty != NULL)
6066 pClosePseudoConsole(term->tl_conpty);
6067 term->tl_conpty = NULL;
6068 return FAIL;
6069}
6070
6071 static void
6072conpty_term_report_winsize(term_T *term, int rows, int cols)
6073{
6074 COORD consize;
6075
6076 consize.X = cols;
6077 consize.Y = rows;
6078 pResizePseudoConsole(term->tl_conpty, consize);
6079}
6080
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006081 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006082term_free_conpty(term_T *term)
6083{
6084 if (term->tl_siex.lpAttributeList != NULL)
6085 {
6086 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6087 vim_free(term->tl_siex.lpAttributeList);
6088 }
6089 term->tl_siex.lpAttributeList = NULL;
6090 if (term->tl_conpty != NULL)
6091 pClosePseudoConsole(term->tl_conpty);
6092 term->tl_conpty = NULL;
6093}
6094
6095 int
6096use_conpty(void)
6097{
6098 return has_conpty;
6099}
6100
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006101# ifndef PROTO
6102
6103#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6104#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006105#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006106
6107void* (*winpty_config_new)(UINT64, void*);
6108void* (*winpty_open)(void*, void*);
6109void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6110BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6111void (*winpty_config_set_mouse_mode)(void*, int);
6112void (*winpty_config_set_initial_size)(void*, int, int);
6113LPCWSTR (*winpty_conin_name)(void*);
6114LPCWSTR (*winpty_conout_name)(void*);
6115LPCWSTR (*winpty_conerr_name)(void*);
6116void (*winpty_free)(void*);
6117void (*winpty_config_free)(void*);
6118void (*winpty_spawn_config_free)(void*);
6119void (*winpty_error_free)(void*);
6120LPCWSTR (*winpty_error_msg)(void*);
6121BOOL (*winpty_set_size)(void*, int, int, void*);
6122HANDLE (*winpty_agent_process)(void*);
6123
6124#define WINPTY_DLL "winpty.dll"
6125
6126static HINSTANCE hWinPtyDLL = NULL;
6127# endif
6128
6129 static int
6130dyn_winpty_init(int verbose)
6131{
6132 int i;
6133 static struct
6134 {
6135 char *name;
6136 FARPROC *ptr;
6137 } winpty_entry[] =
6138 {
6139 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6140 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6141 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6142 {"winpty_config_set_mouse_mode",
6143 (FARPROC*)&winpty_config_set_mouse_mode},
6144 {"winpty_config_set_initial_size",
6145 (FARPROC*)&winpty_config_set_initial_size},
6146 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6147 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6148 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6149 {"winpty_free", (FARPROC*)&winpty_free},
6150 {"winpty_open", (FARPROC*)&winpty_open},
6151 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6152 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6153 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6154 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6155 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6156 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6157 {NULL, NULL}
6158 };
6159
6160 /* No need to initialize twice. */
6161 if (hWinPtyDLL)
6162 return OK;
6163 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6164 * winpty.dll. */
6165 if (*p_winptydll != NUL)
6166 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6167 if (!hWinPtyDLL)
6168 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6169 if (!hWinPtyDLL)
6170 {
6171 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006172 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006173 : (char_u *)WINPTY_DLL);
6174 return FAIL;
6175 }
6176 for (i = 0; winpty_entry[i].name != NULL
6177 && winpty_entry[i].ptr != NULL; ++i)
6178 {
6179 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6180 winpty_entry[i].name)) == NULL)
6181 {
6182 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006183 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006184 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006185 return FAIL;
6186 }
6187 }
6188
6189 return OK;
6190}
6191
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006192 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006193winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194 term_T *term,
6195 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006196 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006197 jobopt_T *opt,
6198 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006199{
6200 WCHAR *cmd_wchar = NULL;
6201 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006202 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006203 channel_T *channel = NULL;
6204 job_T *job = NULL;
6205 DWORD error;
6206 HANDLE jo = NULL;
6207 HANDLE child_process_handle;
6208 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006209 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006210 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006211 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006212 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006213
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006214 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6215 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006216
6217 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006218 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006219 cmd = argvar->vval.v_string;
6220 }
6221 else if (argvar->v_type == VAR_LIST)
6222 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006223 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006224 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006225 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006226 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006227 if (cmd == NULL || *cmd == NUL)
6228 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006229 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006230 goto failed;
6231 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006232
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006233 term->tl_arg0_cmd = vim_strsave(cmd);
6234
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006235 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006236 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006237 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006238 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006239 if (opt->jo_cwd != NULL)
6240 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006241
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006242 win32_build_env(opt->jo_env, &ga_env, TRUE);
6243 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006244
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006245 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6246 if (term->tl_winpty_config == NULL)
6247 goto failed;
6248
6249 winpty_config_set_mouse_mode(term->tl_winpty_config,
6250 WINPTY_MOUSE_MODE_FORCE);
6251 winpty_config_set_initial_size(term->tl_winpty_config,
6252 term->tl_cols, term->tl_rows);
6253 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6254 if (term->tl_winpty == NULL)
6255 goto failed;
6256
6257 spawn_config = winpty_spawn_config_new(
6258 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6259 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6260 NULL,
6261 cmd_wchar,
6262 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006263 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006264 &winpty_err);
6265 if (spawn_config == NULL)
6266 goto failed;
6267
6268 channel = add_channel();
6269 if (channel == NULL)
6270 goto failed;
6271
6272 job = job_alloc();
6273 if (job == NULL)
6274 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006275 if (argvar->v_type == VAR_STRING)
6276 {
6277 int argc;
6278
6279 build_argv_from_string(cmd, &job->jv_argv, &argc);
6280 }
6281 else
6282 {
6283 int argc;
6284
6285 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6286 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006287
6288 if (opt->jo_set & JO_IN_BUF)
6289 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6290
6291 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6292 &child_thread_handle, &error, &winpty_err))
6293 goto failed;
6294
6295 channel_set_pipes(channel,
6296 (sock_T)CreateFileW(
6297 winpty_conin_name(term->tl_winpty),
6298 GENERIC_WRITE, 0, NULL,
6299 OPEN_EXISTING, 0, NULL),
6300 (sock_T)CreateFileW(
6301 winpty_conout_name(term->tl_winpty),
6302 GENERIC_READ, 0, NULL,
6303 OPEN_EXISTING, 0, NULL),
6304 (sock_T)CreateFileW(
6305 winpty_conerr_name(term->tl_winpty),
6306 GENERIC_READ, 0, NULL,
6307 OPEN_EXISTING, 0, NULL));
6308
6309 /* Write lines with CR instead of NL. */
6310 channel->ch_write_text_mode = TRUE;
6311
6312 jo = CreateJobObject(NULL, NULL);
6313 if (jo == NULL)
6314 goto failed;
6315
6316 if (!AssignProcessToJobObject(jo, child_process_handle))
6317 {
6318 /* Failed, switch the way to terminate process with TerminateProcess. */
6319 CloseHandle(jo);
6320 jo = NULL;
6321 }
6322
6323 winpty_spawn_config_free(spawn_config);
6324 vim_free(cmd_wchar);
6325 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006326 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006327
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006328 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6329 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006330
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006331#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6332 if (opt->jo_set2 & JO2_ANSI_COLORS)
6333 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6334 else
6335 init_vterm_ansi_colors(term->tl_vterm);
6336#endif
6337
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006338 channel_set_job(channel, job, opt);
6339 job_set_options(job, opt);
6340
6341 job->jv_channel = channel;
6342 job->jv_proc_info.hProcess = child_process_handle;
6343 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6344 job->jv_job_object = jo;
6345 job->jv_status = JOB_STARTED;
6346 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006347 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006348 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006349 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006350 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006351 ++job->jv_refcount;
6352 term->tl_job = job;
6353
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006354 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6355 * open the file here and handle it in. opt->jo_io was changed in
6356 * setup_job_options(), use the original flags here. */
6357 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6358 {
6359 char_u *fname = opt->jo_io_name[PART_OUT];
6360
6361 ch_log(channel, "Opening output file %s", fname);
6362 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6363 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006364 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006365 }
6366
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006367 return OK;
6368
6369failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006370 ga_clear(&ga_cmd);
6371 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006372 vim_free(cmd_wchar);
6373 vim_free(cwd_wchar);
6374 if (spawn_config != NULL)
6375 winpty_spawn_config_free(spawn_config);
6376 if (channel != NULL)
6377 channel_clear(channel);
6378 if (job != NULL)
6379 {
6380 job->jv_channel = NULL;
6381 job_cleanup(job);
6382 }
6383 term->tl_job = NULL;
6384 if (jo != NULL)
6385 CloseHandle(jo);
6386 if (term->tl_winpty != NULL)
6387 winpty_free(term->tl_winpty);
6388 term->tl_winpty = NULL;
6389 if (term->tl_winpty_config != NULL)
6390 winpty_config_free(term->tl_winpty_config);
6391 term->tl_winpty_config = NULL;
6392 if (winpty_err != NULL)
6393 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006394 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006395 (short_u *)winpty_error_msg(winpty_err), NULL);
6396
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006397 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006398 winpty_error_free(winpty_err);
6399 }
6400 return FAIL;
6401}
6402
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006403/*
6404 * Create a new terminal of "rows" by "cols" cells.
6405 * Store a reference in "term".
6406 * Return OK or FAIL.
6407 */
6408 static int
6409term_and_job_init(
6410 term_T *term,
6411 typval_T *argvar,
6412 char **argv UNUSED,
6413 jobopt_T *opt,
6414 jobopt_T *orig_opt)
6415{
6416 int use_winpty = FALSE;
6417 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006418 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006419
6420 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6421 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6422
6423 if (!has_winpty && !has_conpty)
6424 // If neither is available give the errors for winpty, since when
6425 // conpty is not available it can't be installed either.
6426 return dyn_winpty_init(TRUE);
6427
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006428 if (opt->jo_tty_type != NUL)
6429 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006430
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006431 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006432 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006433 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006434 use_conpty = TRUE;
6435 else if (has_winpty)
6436 use_winpty = TRUE;
6437 // else: error
6438 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006439 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006440 {
6441 if (has_winpty)
6442 use_winpty = TRUE;
6443 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006444 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006445 {
6446 if (has_conpty)
6447 use_conpty = TRUE;
6448 else
6449 return dyn_conpty_init(TRUE);
6450 }
6451
6452 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006453 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006454
6455 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006456 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006457
6458 // error
6459 return dyn_winpty_init(TRUE);
6460}
6461
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006462 static int
6463create_pty_only(term_T *term, jobopt_T *options)
6464{
6465 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6466 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6467 char in_name[80], out_name[80];
6468 channel_T *channel = NULL;
6469
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006470 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6471 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006472
6473 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6474 GetCurrentProcessId(),
6475 curbuf->b_fnum);
6476 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6477 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6478 PIPE_UNLIMITED_INSTANCES,
6479 0, 0, NMPWAIT_NOWAIT, NULL);
6480 if (hPipeIn == INVALID_HANDLE_VALUE)
6481 goto failed;
6482
6483 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6484 GetCurrentProcessId(),
6485 curbuf->b_fnum);
6486 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6487 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6488 PIPE_UNLIMITED_INSTANCES,
6489 0, 0, 0, NULL);
6490 if (hPipeOut == INVALID_HANDLE_VALUE)
6491 goto failed;
6492
6493 ConnectNamedPipe(hPipeIn, NULL);
6494 ConnectNamedPipe(hPipeOut, NULL);
6495
6496 term->tl_job = job_alloc();
6497 if (term->tl_job == NULL)
6498 goto failed;
6499 ++term->tl_job->jv_refcount;
6500
6501 /* behave like the job is already finished */
6502 term->tl_job->jv_status = JOB_FINISHED;
6503
6504 channel = add_channel();
6505 if (channel == NULL)
6506 goto failed;
6507 term->tl_job->jv_channel = channel;
6508 channel->ch_keep_open = TRUE;
6509 channel->ch_named_pipe = TRUE;
6510
6511 channel_set_pipes(channel,
6512 (sock_T)hPipeIn,
6513 (sock_T)hPipeOut,
6514 (sock_T)hPipeOut);
6515 channel_set_job(channel, term->tl_job, options);
6516 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6517 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6518
6519 return OK;
6520
6521failed:
6522 if (hPipeIn != NULL)
6523 CloseHandle(hPipeIn);
6524 if (hPipeOut != NULL)
6525 CloseHandle(hPipeOut);
6526 return FAIL;
6527}
6528
6529/*
6530 * Free the terminal emulator part of "term".
6531 */
6532 static void
6533term_free_vterm(term_T *term)
6534{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006535 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006536 if (term->tl_winpty != NULL)
6537 winpty_free(term->tl_winpty);
6538 term->tl_winpty = NULL;
6539 if (term->tl_winpty_config != NULL)
6540 winpty_config_free(term->tl_winpty_config);
6541 term->tl_winpty_config = NULL;
6542 if (term->tl_vterm != NULL)
6543 vterm_free(term->tl_vterm);
6544 term->tl_vterm = NULL;
6545}
6546
6547/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006548 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006549 */
6550 static void
6551term_report_winsize(term_T *term, int rows, int cols)
6552{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006553 if (term->tl_conpty)
6554 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006555 if (term->tl_winpty)
6556 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6557}
6558
6559 int
6560terminal_enabled(void)
6561{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006562 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006563}
6564
6565# else
6566
6567/**************************************
6568 * 3. Unix-like implementation.
6569 */
6570
6571/*
6572 * Create a new terminal of "rows" by "cols" cells.
6573 * Start job for "cmd".
6574 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006575 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006576 * Return OK or FAIL.
6577 */
6578 static int
6579term_and_job_init(
6580 term_T *term,
6581 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006582 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006583 jobopt_T *opt,
6584 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006585{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006586 term->tl_arg0_cmd = NULL;
6587
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006588 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6589 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006590
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006591#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6592 if (opt->jo_set2 & JO2_ANSI_COLORS)
6593 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6594 else
6595 init_vterm_ansi_colors(term->tl_vterm);
6596#endif
6597
Bram Moolenaar13568252018-03-16 20:46:58 +01006598 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006599 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006600 if (term->tl_job != NULL)
6601 ++term->tl_job->jv_refcount;
6602
6603 return term->tl_job != NULL
6604 && term->tl_job->jv_channel != NULL
6605 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6606}
6607
6608 static int
6609create_pty_only(term_T *term, jobopt_T *opt)
6610{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006611 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6612 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006613
6614 term->tl_job = job_alloc();
6615 if (term->tl_job == NULL)
6616 return FAIL;
6617 ++term->tl_job->jv_refcount;
6618
6619 /* behave like the job is already finished */
6620 term->tl_job->jv_status = JOB_FINISHED;
6621
6622 return mch_create_pty_channel(term->tl_job, opt);
6623}
6624
6625/*
6626 * Free the terminal emulator part of "term".
6627 */
6628 static void
6629term_free_vterm(term_T *term)
6630{
6631 if (term->tl_vterm != NULL)
6632 vterm_free(term->tl_vterm);
6633 term->tl_vterm = NULL;
6634}
6635
6636/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006637 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006638 */
6639 static void
6640term_report_winsize(term_T *term, int rows, int cols)
6641{
6642 /* Use an ioctl() to report the new window size to the job. */
6643 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6644 {
6645 int fd = -1;
6646 int part;
6647
6648 for (part = PART_OUT; part < PART_COUNT; ++part)
6649 {
6650 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006651 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006652 break;
6653 }
6654 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6655 mch_signal_job(term->tl_job, (char_u *)"winch");
6656 }
6657}
6658
6659# endif
6660
6661#endif /* FEAT_TERMINAL */