blob: 290d7c7bafa0109f6667c91d7b88d5269891726b [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 Moolenaar28ed4df2019-10-26 16:21:40 +0200693 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
694 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200695 return newbuf;
696}
697
698/*
699 * ":terminal": open a terminal window and execute a job in it.
700 */
701 void
702ex_terminal(exarg_T *eap)
703{
704 typval_T argvar[2];
705 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100706 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 char_u *cmd;
708 char_u *tofree = NULL;
709
710 init_job_options(&opt);
711
712 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100713 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200714 {
715 char_u *p, *ep;
716
717 cmd += 2;
718 p = skiptowhite(cmd);
719 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200720 if (ep != NULL)
721 {
722 if (ep < p)
723 p = ep;
724 else
725 ep = NULL;
726 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200727
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200728# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
729 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
730 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200731 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200732 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100733 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200734 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200735 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200736 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200737 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200738 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200740 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100741 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100742 else if (OPTARG_HAS("shell"))
743 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200744 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100745 {
746 opt.jo_set2 |= JO2_TERM_KILL;
747 opt.jo_term_kill = ep + 1;
748 p = skiptowhite(cmd);
749 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200750 else if (OPTARG_HAS("api"))
751 {
752 opt.jo_set2 |= JO2_TERM_API;
753 if (ep != NULL)
754 {
755 opt.jo_term_api = ep + 1;
756 p = skiptowhite(cmd);
757 }
758 else
759 opt.jo_term_api = NULL;
760 }
761 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 {
763 opt.jo_set2 |= JO2_TERM_ROWS;
764 opt.jo_term_rows = atoi((char *)ep + 1);
765 p = skiptowhite(cmd);
766 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200767 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200768 {
769 opt.jo_set2 |= JO2_TERM_COLS;
770 opt.jo_term_cols = atoi((char *)ep + 1);
771 p = skiptowhite(cmd);
772 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200773 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200774 {
775 char_u *buf = NULL;
776 char_u *keys;
777
778 p = skiptowhite(cmd);
779 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200780 keys = replace_termcodes(ep + 1, &buf,
781 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200782 opt.jo_set2 |= JO2_EOF_CHARS;
783 opt.jo_eof_chars = vim_strsave(keys);
784 vim_free(buf);
785 *p = ' ';
786 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100787#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100788 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
789 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100790 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100791 int tty_type = NUL;
792
793 p = skiptowhite(cmd);
794 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
795 tty_type = 'w';
796 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
797 tty_type = 'c';
798 else
799 {
800 semsg(e_invargval, "type");
801 goto theend;
802 }
803 opt.jo_set2 |= JO2_TTY_TYPE;
804 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100805 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100806#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200807 else
808 {
809 if (*p)
810 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100811 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100812 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200814# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200815 cmd = skipwhite(p);
816 }
817 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100818 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200819 /* Make a copy of 'shell', an autocommand may change the option. */
820 tofree = cmd = vim_strsave(p_sh);
821
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100822 /* default to close when the shell exits */
823 if (opt.jo_term_finish == NUL)
824 opt.jo_term_finish = 'c';
825 }
826
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200827 if (eap->addr_count > 0)
828 {
829 /* Write lines from current buffer to the job. */
830 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
831 opt.jo_io[PART_IN] = JIO_BUFFER;
832 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
833 opt.jo_in_top = eap->line1;
834 opt.jo_in_bot = eap->line2;
835 }
836
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100837 if (opt_shell && tofree == NULL)
838 {
839#ifdef UNIX
840 char **argv = NULL;
841 char_u *tofree1 = NULL;
842 char_u *tofree2 = NULL;
843
844 // :term ++shell command
845 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
846 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
847 vim_free(tofree1);
848 vim_free(tofree2);
849#else
850 emsg(_("E279: Sorry, ++shell is not supported on this system"));
851#endif
852 }
853 else
854 {
855 argvar[0].v_type = VAR_STRING;
856 argvar[0].vval.v_string = cmd;
857 argvar[1].v_type = VAR_UNKNOWN;
858 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
859 }
860
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200861 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100862
863theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200864 vim_free(opt.jo_eof_chars);
865}
866
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100867#if defined(FEAT_SESSION) || defined(PROTO)
868/*
869 * Write a :terminal command to the session file to restore the terminal in
870 * window "wp".
871 * Return FAIL if writing fails.
872 */
873 int
874term_write_session(FILE *fd, win_T *wp)
875{
876 term_T *term = wp->w_buffer->b_term;
877
878 /* Create the terminal and run the command. This is not without
879 * risk, but let's assume the user only creates a session when this
880 * will be OK. */
881 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
882 term->tl_cols, term->tl_rows) < 0)
883 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100884#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100885 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
886 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100887#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100888 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
889 return FAIL;
890
891 return put_eol(fd);
892}
893
894/*
895 * Return TRUE if "buf" has a terminal that should be restored.
896 */
897 int
898term_should_restore(buf_T *buf)
899{
900 term_T *term = buf->b_term;
901
902 return term != NULL && (term->tl_command == NULL
903 || STRCMP(term->tl_command, "NONE") != 0);
904}
905#endif
906
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200907/*
908 * Free the scrollback buffer for "term".
909 */
910 static void
911free_scrollback(term_T *term)
912{
913 int i;
914
915 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
916 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
917 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100918 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
919 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
920 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200921}
922
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100923
924// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200925static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100926
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200927/*
928 * Free a terminal and everything it refers to.
929 * Kills the job if there is one.
930 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100931 * The actual terminal structure is freed later in free_unused_terminals(),
932 * because callbacks may wipe out a buffer while the terminal is still
933 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200934 */
935 void
936free_terminal(buf_T *buf)
937{
938 term_T *term = buf->b_term;
939 term_T *tp;
940
941 if (term == NULL)
942 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100943
944 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200945 if (first_term == term)
946 first_term = term->tl_next;
947 else
948 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
949 if (tp->tl_next == term)
950 {
951 tp->tl_next = term->tl_next;
952 break;
953 }
954
955 if (term->tl_job != NULL)
956 {
957 if (term->tl_job->jv_status != JOB_ENDED
958 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100959 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200960 job_stop(term->tl_job, NULL, "kill");
961 job_unref(term->tl_job);
962 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100963 term->tl_next = terminals_to_free;
964 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200965
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200966 buf->b_term = NULL;
967 if (in_terminal_loop == term)
968 in_terminal_loop = NULL;
969}
970
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100971 void
972free_unused_terminals()
973{
974 while (terminals_to_free != NULL)
975 {
976 term_T *term = terminals_to_free;
977
978 terminals_to_free = term->tl_next;
979
980 free_scrollback(term);
981
982 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200983 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100984 vim_free(term->tl_title);
985#ifdef FEAT_SESSION
986 vim_free(term->tl_command);
987#endif
988 vim_free(term->tl_kill);
989 vim_free(term->tl_status_text);
990 vim_free(term->tl_opencmd);
991 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100992 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100993#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100994 if (term->tl_out_fd != NULL)
995 fclose(term->tl_out_fd);
996#endif
997 vim_free(term->tl_cursor_color);
998 vim_free(term);
999 }
1000}
1001
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001002/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001003 * Get the part that is connected to the tty. Normally this is PART_IN, but
1004 * when writing buffer lines to the job it can be another. This makes it
1005 * possible to do "1,5term vim -".
1006 */
1007 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001008get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001009{
1010#ifdef UNIX
1011 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1012 int i;
1013
1014 for (i = 0; i < 3; ++i)
1015 {
1016 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1017
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001018 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001019 return parts[i];
1020 }
1021#endif
1022 return PART_IN;
1023}
1024
1025/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001026 * Write job output "msg[len]" to the vterm.
1027 */
1028 static void
1029term_write_job_output(term_T *term, char_u *msg, size_t len)
1030{
1031 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001032 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001033
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001034 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001035
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001036 /* flush vterm buffer when vterm responded to control sequence */
1037 if (prevlen != vterm_output_get_buffer_current(vterm))
1038 {
1039 char buf[KEY_BUF_LEN];
1040 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1041
1042 if (curlen > 0)
1043 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1044 (char_u *)buf, (int)curlen, NULL);
1045 }
1046
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001047 /* this invokes the damage callbacks */
1048 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1049}
1050
1051 static void
1052update_cursor(term_T *term, int redraw)
1053{
1054 if (term->tl_normal_mode)
1055 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001056#ifdef FEAT_GUI
1057 if (term->tl_system)
1058 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1059 term->tl_cursor_pos.col);
1060 else
1061#endif
1062 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001063 if (redraw)
1064 {
1065 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1066 cursor_on();
1067 out_flush();
1068#ifdef FEAT_GUI
1069 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001070 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001072 gui_mch_flush();
1073 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001074#endif
1075 }
1076}
1077
1078/*
1079 * Invoked when "msg" output from a job was received. Write it to the terminal
1080 * of "buffer".
1081 */
1082 void
1083write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1084{
1085 size_t len = STRLEN(msg);
1086 term_T *term = buffer->b_term;
1087
Bram Moolenaar4f974752019-02-17 17:44:42 +01001088#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001089 /* Win32: Cannot redirect output of the job, intercept it here and write to
1090 * the file. */
1091 if (term->tl_out_fd != NULL)
1092 {
1093 ch_log(channel, "Writing %d bytes to output file", (int)len);
1094 fwrite(msg, len, 1, term->tl_out_fd);
1095 return;
1096 }
1097#endif
1098
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001099 if (term->tl_vterm == NULL)
1100 {
1101 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1102 return;
1103 }
1104 ch_log(channel, "writing %d bytes to terminal", (int)len);
1105 term_write_job_output(term, msg, len);
1106
Bram Moolenaar13568252018-03-16 20:46:58 +01001107#ifdef FEAT_GUI
1108 if (term->tl_system)
1109 {
1110 /* show system output, scrolling up the screen as needed */
1111 update_system_term(term);
1112 update_cursor(term, TRUE);
1113 }
1114 else
1115#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001116 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1117 * contents, thus no screen update is needed. */
1118 if (!term->tl_normal_mode)
1119 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001120 // Don't use update_screen() when editing the command line, it gets
1121 // cleared.
1122 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001123 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001124 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001125 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001126 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001127 /* update_screen() can be slow, check the terminal wasn't closed
1128 * already */
1129 if (buffer == curbuf && curbuf->b_term != NULL)
1130 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001131 }
1132 else
1133 redraw_after_callback(TRUE);
1134 }
1135}
1136
1137/*
1138 * Send a mouse position and click to the vterm
1139 */
1140 static int
1141term_send_mouse(VTerm *vterm, int button, int pressed)
1142{
1143 VTermModifier mod = VTERM_MOD_NONE;
1144
1145 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001146 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001147 if (button != 0)
1148 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001149 return TRUE;
1150}
1151
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001152static int enter_mouse_col = -1;
1153static int enter_mouse_row = -1;
1154
1155/*
1156 * Handle a mouse click, drag or release.
1157 * Return TRUE when a mouse event is sent to the terminal.
1158 */
1159 static int
1160term_mouse_click(VTerm *vterm, int key)
1161{
1162#if defined(FEAT_CLIPBOARD)
1163 /* For modeless selection mouse drag and release events are ignored, unless
1164 * they are preceded with a mouse down event */
1165 static int ignore_drag_release = TRUE;
1166 VTermMouseState mouse_state;
1167
1168 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1169 if (mouse_state.flags == 0)
1170 {
1171 /* Terminal is not using the mouse, use modeless selection. */
1172 switch (key)
1173 {
1174 case K_LEFTDRAG:
1175 case K_LEFTRELEASE:
1176 case K_RIGHTDRAG:
1177 case K_RIGHTRELEASE:
1178 /* Ignore drag and release events when the button-down wasn't
1179 * seen before. */
1180 if (ignore_drag_release)
1181 {
1182 int save_mouse_col, save_mouse_row;
1183
1184 if (enter_mouse_col < 0)
1185 break;
1186
1187 /* mouse click in the window gave us focus, handle that
1188 * click now */
1189 save_mouse_col = mouse_col;
1190 save_mouse_row = mouse_row;
1191 mouse_col = enter_mouse_col;
1192 mouse_row = enter_mouse_row;
1193 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1194 mouse_col = save_mouse_col;
1195 mouse_row = save_mouse_row;
1196 }
1197 /* FALLTHROUGH */
1198 case K_LEFTMOUSE:
1199 case K_RIGHTMOUSE:
1200 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1201 ignore_drag_release = TRUE;
1202 else
1203 ignore_drag_release = FALSE;
1204 /* Should we call mouse_has() here? */
1205 if (clip_star.available)
1206 {
1207 int button, is_click, is_drag;
1208
1209 button = get_mouse_button(KEY2TERMCAP1(key),
1210 &is_click, &is_drag);
1211 if (mouse_model_popup() && button == MOUSE_LEFT
1212 && (mod_mask & MOD_MASK_SHIFT))
1213 {
1214 /* Translate shift-left to right button. */
1215 button = MOUSE_RIGHT;
1216 mod_mask &= ~MOD_MASK_SHIFT;
1217 }
1218 clip_modeless(button, is_click, is_drag);
1219 }
1220 break;
1221
1222 case K_MIDDLEMOUSE:
1223 if (clip_star.available)
1224 insert_reg('*', TRUE);
1225 break;
1226 }
1227 enter_mouse_col = -1;
1228 return FALSE;
1229 }
1230#endif
1231 enter_mouse_col = -1;
1232
1233 switch (key)
1234 {
1235 case K_LEFTMOUSE:
1236 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1237 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1238 case K_LEFTRELEASE:
1239 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1240 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1241 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1242 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1243 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1244 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1245 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1246 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1247 }
1248 return TRUE;
1249}
1250
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001251/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001252 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1253 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001254 * Return the number of bytes in "buf".
1255 */
1256 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001257term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001258{
1259 VTerm *vterm = term->tl_vterm;
1260 VTermKey key = VTERM_KEY_NONE;
1261 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001262 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001263
1264 switch (c)
1265 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001266 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1267
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001268 /* don't use VTERM_KEY_BACKSPACE, it always
1269 * becomes 0x7f DEL */
1270 case K_BS: c = term_backspace_char; break;
1271
1272 case ESC: key = VTERM_KEY_ESCAPE; break;
1273 case K_DEL: key = VTERM_KEY_DEL; break;
1274 case K_DOWN: key = VTERM_KEY_DOWN; break;
1275 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1276 key = VTERM_KEY_DOWN; break;
1277 case K_END: key = VTERM_KEY_END; break;
1278 case K_S_END: mod = VTERM_MOD_SHIFT;
1279 key = VTERM_KEY_END; break;
1280 case K_C_END: mod = VTERM_MOD_CTRL;
1281 key = VTERM_KEY_END; break;
1282 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1283 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1284 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1285 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1286 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1287 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1288 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1289 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1290 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1291 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1292 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1293 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1294 case K_HOME: key = VTERM_KEY_HOME; break;
1295 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1296 key = VTERM_KEY_HOME; break;
1297 case K_C_HOME: mod = VTERM_MOD_CTRL;
1298 key = VTERM_KEY_HOME; break;
1299 case K_INS: key = VTERM_KEY_INS; break;
1300 case K_K0: key = VTERM_KEY_KP_0; break;
1301 case K_K1: key = VTERM_KEY_KP_1; break;
1302 case K_K2: key = VTERM_KEY_KP_2; break;
1303 case K_K3: key = VTERM_KEY_KP_3; break;
1304 case K_K4: key = VTERM_KEY_KP_4; break;
1305 case K_K5: key = VTERM_KEY_KP_5; break;
1306 case K_K6: key = VTERM_KEY_KP_6; break;
1307 case K_K7: key = VTERM_KEY_KP_7; break;
1308 case K_K8: key = VTERM_KEY_KP_8; break;
1309 case K_K9: key = VTERM_KEY_KP_9; break;
1310 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1311 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1312 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1313 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1314 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1315 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1316 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1317 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1318 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1319 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1320 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1321 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1322 case K_LEFT: key = VTERM_KEY_LEFT; break;
1323 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1324 key = VTERM_KEY_LEFT; break;
1325 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1326 key = VTERM_KEY_LEFT; break;
1327 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1328 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1329 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1330 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1331 key = VTERM_KEY_RIGHT; break;
1332 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1333 key = VTERM_KEY_RIGHT; break;
1334 case K_UP: key = VTERM_KEY_UP; break;
1335 case K_S_UP: mod = VTERM_MOD_SHIFT;
1336 key = VTERM_KEY_UP; break;
1337 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001338 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1339 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001340
Bram Moolenaara42ad572017-11-16 13:08:04 +01001341 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1342 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001343 case K_MOUSELEFT: /* TODO */ return 0;
1344 case K_MOUSERIGHT: /* TODO */ return 0;
1345
1346 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001347 case K_LEFTMOUSE_NM:
1348 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001349 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001350 case K_LEFTRELEASE_NM:
1351 case K_MOUSEMOVE:
1352 case K_MIDDLEMOUSE:
1353 case K_MIDDLEDRAG:
1354 case K_MIDDLERELEASE:
1355 case K_RIGHTMOUSE:
1356 case K_RIGHTDRAG:
1357 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1358 return 0;
1359 other = TRUE;
1360 break;
1361
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 case K_X1MOUSE: /* TODO */ return 0;
1363 case K_X1DRAG: /* TODO */ return 0;
1364 case K_X1RELEASE: /* TODO */ return 0;
1365 case K_X2MOUSE: /* TODO */ return 0;
1366 case K_X2DRAG: /* TODO */ return 0;
1367 case K_X2RELEASE: /* TODO */ return 0;
1368
1369 case K_IGNORE: return 0;
1370 case K_NOP: return 0;
1371 case K_UNDO: return 0;
1372 case K_HELP: return 0;
1373 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1374 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1375 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1376 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1377 case K_SELECT: return 0;
1378#ifdef FEAT_GUI
1379 case K_VER_SCROLLBAR: return 0;
1380 case K_HOR_SCROLLBAR: return 0;
1381#endif
1382#ifdef FEAT_GUI_TABLINE
1383 case K_TABLINE: return 0;
1384 case K_TABMENU: return 0;
1385#endif
1386#ifdef FEAT_NETBEANS_INTG
1387 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1388#endif
1389#ifdef FEAT_DND
1390 case K_DROP: return 0;
1391#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001392 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001393 case K_PS: vterm_keyboard_start_paste(vterm);
1394 other = TRUE;
1395 break;
1396 case K_PE: vterm_keyboard_end_paste(vterm);
1397 other = TRUE;
1398 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001399 }
1400
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001401 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001402 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001403 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001404 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001405 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001406 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001407 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001408
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001409 /*
1410 * Convert special keys to vterm keys:
1411 * - Write keys to vterm: vterm_keyboard_key()
1412 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001413 */
1414 if (key != VTERM_KEY_NONE)
1415 /* Special key, let vterm convert it. */
1416 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001417 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001418 /* Normal character, let vterm convert it. */
1419 vterm_keyboard_unichar(vterm, c, mod);
1420
1421 /* Read back the converted escape sequence. */
1422 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1423}
1424
1425/*
1426 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001427 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001428 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001429 */
1430 static int
1431term_job_running_check(term_T *term, int check_job_status)
1432{
1433 /* Also consider the job finished when the channel is closed, to avoid a
1434 * race condition when updating the title. */
1435 if (term != NULL
1436 && term->tl_job != NULL
1437 && channel_is_open(term->tl_job->jv_channel))
1438 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001439 job_T *job = term->tl_job;
1440
1441 // Careful: Checking the job status may invoked callbacks, which close
1442 // the buffer and terminate "term". However, "job" will not be freed
1443 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001444 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001445 job_status(job);
1446 return (job->jv_status == JOB_STARTED
1447 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001448 }
1449 return FALSE;
1450}
1451
1452/*
1453 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001454 */
1455 int
1456term_job_running(term_T *term)
1457{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001458 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001459}
1460
1461/*
1462 * Return TRUE if "term" has an active channel and used ":term NONE".
1463 */
1464 int
1465term_none_open(term_T *term)
1466{
1467 /* Also consider the job finished when the channel is closed, to avoid a
1468 * race condition when updating the title. */
1469 return term != NULL
1470 && term->tl_job != NULL
1471 && channel_is_open(term->tl_job->jv_channel)
1472 && term->tl_job->jv_channel->ch_keep_open;
1473}
1474
1475/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001476 * Used when exiting: kill the job in "buf" if so desired.
1477 * Return OK when the job finished.
1478 * Return FAIL when the job is still running.
1479 */
1480 int
1481term_try_stop_job(buf_T *buf)
1482{
1483 int count;
1484 char *how = (char *)buf->b_term->tl_kill;
1485
1486#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1487 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1488 {
1489 char_u buff[DIALOG_MSG_SIZE];
1490 int ret;
1491
1492 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1493 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1494 if (ret == VIM_YES)
1495 how = "kill";
1496 else if (ret == VIM_CANCEL)
1497 return FAIL;
1498 }
1499#endif
1500 if (how == NULL || *how == NUL)
1501 return FAIL;
1502
1503 job_stop(buf->b_term->tl_job, NULL, how);
1504
Bram Moolenaar9172d232019-01-29 23:06:54 +01001505 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001506 for (count = 0; count < 100; ++count)
1507 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001508 job_T *job;
1509
1510 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001511 if (!buf_valid(buf)
1512 || buf->b_term == NULL
1513 || buf->b_term->tl_job == NULL)
1514 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001515 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001516
Bram Moolenaar9172d232019-01-29 23:06:54 +01001517 // Call job_status() to update jv_status. It may cause the job to be
1518 // cleaned up but it won't be freed.
1519 job_status(job);
1520 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001521 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001522
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001523 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001524 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001525 }
1526 return FAIL;
1527}
1528
1529/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001530 * Add the last line of the scrollback buffer to the buffer in the window.
1531 */
1532 static void
1533add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1534{
1535 buf_T *buf = term->tl_buffer;
1536 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1537 linenr_T lnum = buf->b_ml.ml_line_count;
1538
Bram Moolenaar4f974752019-02-17 17:44:42 +01001539#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001540 if (!enc_utf8 && enc_codepage > 0)
1541 {
1542 WCHAR *ret = NULL;
1543 int length = 0;
1544
1545 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1546 &ret, &length);
1547 if (ret != NULL)
1548 {
1549 WideCharToMultiByte_alloc(enc_codepage, 0,
1550 ret, length, (char **)&text, &len, 0, 0);
1551 vim_free(ret);
1552 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1553 vim_free(text);
1554 }
1555 }
1556 else
1557#endif
1558 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1559 if (empty)
1560 {
1561 /* Delete the empty line that was in the empty buffer. */
1562 curbuf = buf;
1563 ml_delete(1, FALSE);
1564 curbuf = curwin->w_buffer;
1565 }
1566}
1567
1568 static void
1569cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1570{
1571 attr->width = cell->width;
1572 attr->attrs = cell->attrs;
1573 attr->fg = cell->fg;
1574 attr->bg = cell->bg;
1575}
1576
1577 static int
1578equal_celattr(cellattr_T *a, cellattr_T *b)
1579{
1580 /* Comparing the colors should be sufficient. */
1581 return a->fg.red == b->fg.red
1582 && a->fg.green == b->fg.green
1583 && a->fg.blue == b->fg.blue
1584 && a->bg.red == b->bg.red
1585 && a->bg.green == b->bg.green
1586 && a->bg.blue == b->bg.blue;
1587}
1588
Bram Moolenaard96ff162018-02-18 22:13:29 +01001589/*
1590 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1591 * line at this position. Otherwise at the end.
1592 */
1593 static int
1594add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1595{
1596 if (ga_grow(&term->tl_scrollback, 1) == OK)
1597 {
1598 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1599 + term->tl_scrollback.ga_len;
1600
1601 if (lnum > 0)
1602 {
1603 int i;
1604
1605 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1606 {
1607 *line = *(line - 1);
1608 --line;
1609 }
1610 }
1611 line->sb_cols = 0;
1612 line->sb_cells = NULL;
1613 line->sb_fill_attr = *fill_attr;
1614 ++term->tl_scrollback.ga_len;
1615 return OK;
1616 }
1617 return FALSE;
1618}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001619
1620/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001621 * Remove the terminal contents from the scrollback and the buffer.
1622 * Used before adding a new scrollback line or updating the buffer for lines
1623 * displayed in the terminal.
1624 */
1625 static void
1626cleanup_scrollback(term_T *term)
1627{
1628 sb_line_T *line;
1629 garray_T *gap;
1630
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001631 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001632 gap = &term->tl_scrollback;
1633 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1634 && gap->ga_len > 0)
1635 {
1636 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1637 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1638 vim_free(line->sb_cells);
1639 --gap->ga_len;
1640 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001641 curbuf = curwin->w_buffer;
1642 if (curbuf == term->tl_buffer)
1643 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001644}
1645
1646/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001647 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001648 */
1649 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001650update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001651{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001652 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653 int len;
1654 int lines_skipped = 0;
1655 VTermPos pos;
1656 VTermScreenCell cell;
1657 cellattr_T fill_attr, new_fill_attr;
1658 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001659
1660 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1661 "Adding terminal window snapshot to buffer");
1662
1663 /* First remove the lines that were appended before, they might be
1664 * outdated. */
1665 cleanup_scrollback(term);
1666
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001667 screen = vterm_obtain_screen(term->tl_vterm);
1668 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001669 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1670 {
1671 len = 0;
1672 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1673 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1674 && cell.chars[0] != NUL)
1675 {
1676 len = pos.col + 1;
1677 new_fill_attr = term->tl_default_color;
1678 }
1679 else
1680 /* Assume the last attr is the filler attr. */
1681 cell2cellattr(&cell, &new_fill_attr);
1682
1683 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1684 ++lines_skipped;
1685 else
1686 {
1687 while (lines_skipped > 0)
1688 {
1689 /* Line was skipped, add an empty line. */
1690 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001691 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001692 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693 }
1694
1695 if (len == 0)
1696 p = NULL;
1697 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001698 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001699 if ((p != NULL || len == 0)
1700 && ga_grow(&term->tl_scrollback, 1) == OK)
1701 {
1702 garray_T ga;
1703 int width;
1704 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1705 + term->tl_scrollback.ga_len;
1706
1707 ga_init2(&ga, 1, 100);
1708 for (pos.col = 0; pos.col < len; pos.col += width)
1709 {
1710 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1711 {
1712 width = 1;
1713 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1714 if (ga_grow(&ga, 1) == OK)
1715 ga.ga_len += utf_char2bytes(' ',
1716 (char_u *)ga.ga_data + ga.ga_len);
1717 }
1718 else
1719 {
1720 width = cell.width;
1721
1722 cell2cellattr(&cell, &p[pos.col]);
1723
Bram Moolenaara79fd562018-12-20 20:47:32 +01001724 // Each character can be up to 6 bytes.
1725 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 {
1727 int i;
1728 int c;
1729
1730 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1731 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1732 (char_u *)ga.ga_data + ga.ga_len);
1733 }
1734 }
1735 }
1736 line->sb_cols = len;
1737 line->sb_cells = p;
1738 line->sb_fill_attr = new_fill_attr;
1739 fill_attr = new_fill_attr;
1740 ++term->tl_scrollback.ga_len;
1741
1742 if (ga_grow(&ga, 1) == FAIL)
1743 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1744 else
1745 {
1746 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1747 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1748 }
1749 ga_clear(&ga);
1750 }
1751 else
1752 vim_free(p);
1753 }
1754 }
1755
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001756 // Add trailing empty lines.
1757 for (pos.row = term->tl_scrollback.ga_len;
1758 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1759 ++pos.row)
1760 {
1761 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1762 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1763 }
1764
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001765 term->tl_dirty_snapshot = FALSE;
1766#ifdef FEAT_TIMERS
1767 term->tl_timer_set = FALSE;
1768#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001769}
1770
1771/*
1772 * If needed, add the current lines of the terminal to scrollback and to the
1773 * buffer. Called after the job has ended and when switching to
1774 * Terminal-Normal mode.
1775 * When "redraw" is TRUE redraw the windows that show the terminal.
1776 */
1777 static void
1778may_move_terminal_to_buffer(term_T *term, int redraw)
1779{
1780 win_T *wp;
1781
1782 if (term->tl_vterm == NULL)
1783 return;
1784
1785 /* Update the snapshot only if something changes or the buffer does not
1786 * have all the lines. */
1787 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1788 <= term->tl_scrollback_scrolled)
1789 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001790
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001791 /* Obtain the current background color. */
1792 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1793 &term->tl_default_color.fg, &term->tl_default_color.bg);
1794
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001795 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001796 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001797 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001798 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001800 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1801 wp->w_cursor.col = 0;
1802 wp->w_valid = 0;
1803 if (wp->w_cursor.lnum >= wp->w_height)
1804 {
1805 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001806
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001807 if (wp->w_topline < min_topline)
1808 wp->w_topline = min_topline;
1809 }
1810 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001811 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001813}
1814
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001815#if defined(FEAT_TIMERS) || defined(PROTO)
1816/*
1817 * Check if any terminal timer expired. If so, copy text from the terminal to
1818 * the buffer.
1819 * Return the time until the next timer will expire.
1820 */
1821 int
1822term_check_timers(int next_due_arg, proftime_T *now)
1823{
1824 term_T *term;
1825 int next_due = next_due_arg;
1826
1827 for (term = first_term; term != NULL; term = term->tl_next)
1828 {
1829 if (term->tl_timer_set && !term->tl_normal_mode)
1830 {
1831 long this_due = proftime_time_left(&term->tl_timer_due, now);
1832
1833 if (this_due <= 1)
1834 {
1835 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001836 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001837 }
1838 else if (next_due == -1 || next_due > this_due)
1839 next_due = this_due;
1840 }
1841 }
1842
1843 return next_due;
1844}
1845#endif
1846
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001847/*
1848 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1849 * otherwise end it.
1850 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001851 static void
1852set_terminal_mode(term_T *term, int normal_mode)
1853{
1854 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001855 if (!normal_mode)
1856 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001857 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001858 if (term->tl_buffer == curbuf)
1859 maketitle();
1860}
1861
1862/*
1863 * Called after the job if finished and Terminal mode is not active:
1864 * Move the vterm contents into the scrollback buffer and free the vterm.
1865 */
1866 static void
1867cleanup_vterm(term_T *term)
1868{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001869 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001870 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001871 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001872 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873}
1874
1875/*
1876 * Switch from Terminal-Job mode to Terminal-Normal mode.
1877 * Suspends updating the terminal window.
1878 */
1879 static void
1880term_enter_normal_mode(void)
1881{
1882 term_T *term = curbuf->b_term;
1883
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001884 set_terminal_mode(term, TRUE);
1885
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001887 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001888
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001889 /* Move the window cursor to the position of the cursor in the
1890 * terminal. */
1891 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1892 + term->tl_cursor_pos.row + 1;
1893 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001894 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1895 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001896
1897 /* Display the same lines as in the terminal. */
1898 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1899}
1900
1901/*
1902 * Returns TRUE if the current window contains a terminal and we are in
1903 * Terminal-Normal mode.
1904 */
1905 int
1906term_in_normal_mode(void)
1907{
1908 term_T *term = curbuf->b_term;
1909
1910 return term != NULL && term->tl_normal_mode;
1911}
1912
1913/*
1914 * Switch from Terminal-Normal mode to Terminal-Job mode.
1915 * Restores updating the terminal window.
1916 */
1917 void
1918term_enter_job_mode()
1919{
1920 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921
1922 set_terminal_mode(term, FALSE);
1923
1924 if (term->tl_channel_closed)
1925 cleanup_vterm(term);
1926 redraw_buf_and_status_later(curbuf, NOT_VALID);
1927}
1928
1929/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001930 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 * Note: while waiting a terminal may be closed and freed if the channel is
1932 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001933 */
1934 static int
1935term_vgetc()
1936{
1937 int c;
1938 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001939 int modify_other_keys =
1940 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001941
1942 State = TERMINAL;
1943 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001944#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001945 ctrl_break_was_pressed = FALSE;
1946#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001947 if (modify_other_keys)
1948 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001949 c = vgetc();
1950 got_int = FALSE;
1951 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001952 if (modify_other_keys)
1953 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001954 return c;
1955}
1956
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001957static int mouse_was_outside = FALSE;
1958
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001959/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001960 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961 * Return FAIL when the key needs to be handled in Normal mode.
1962 * Return OK when the key was dropped or sent to the terminal.
1963 */
1964 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001965send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001966{
1967 char msg[KEY_BUF_LEN];
1968 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001969 int dragging_outside = FALSE;
1970
1971 /* Catch keys that need to be handled as in Normal mode. */
1972 switch (c)
1973 {
1974 case NUL:
1975 case K_ZERO:
1976 if (typed)
1977 stuffcharReadbuff(c);
1978 return FAIL;
1979
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001980 case K_TABLINE:
1981 stuffcharReadbuff(c);
1982 return FAIL;
1983
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001984 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001985 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001986 return FAIL;
1987
1988 case K_LEFTDRAG:
1989 case K_MIDDLEDRAG:
1990 case K_RIGHTDRAG:
1991 case K_X1DRAG:
1992 case K_X2DRAG:
1993 dragging_outside = mouse_was_outside;
1994 /* FALLTHROUGH */
1995 case K_LEFTMOUSE:
1996 case K_LEFTMOUSE_NM:
1997 case K_LEFTRELEASE:
1998 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001999 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002000 case K_MIDDLEMOUSE:
2001 case K_MIDDLERELEASE:
2002 case K_RIGHTMOUSE:
2003 case K_RIGHTRELEASE:
2004 case K_X1MOUSE:
2005 case K_X1RELEASE:
2006 case K_X2MOUSE:
2007 case K_X2RELEASE:
2008
2009 case K_MOUSEUP:
2010 case K_MOUSEDOWN:
2011 case K_MOUSELEFT:
2012 case K_MOUSERIGHT:
2013 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002014 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02002015 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002016 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002017 || dragging_outside)
2018 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01002019 /* click or scroll outside the current window or on status line
2020 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 if (typed)
2022 {
2023 stuffcharReadbuff(c);
2024 mouse_was_outside = TRUE;
2025 }
2026 return FAIL;
2027 }
2028 }
2029 if (typed)
2030 mouse_was_outside = FALSE;
2031
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002032 // Convert the typed key to a sequence of bytes for the job.
2033 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002035 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002036 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2037 (char_u *)msg, (int)len, NULL);
2038
2039 return OK;
2040}
2041
2042 static void
2043position_cursor(win_T *wp, VTermPos *pos)
2044{
2045 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2046 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2047 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2048}
2049
2050/*
2051 * Handle CTRL-W "": send register contents to the job.
2052 */
2053 static void
2054term_paste_register(int prev_c UNUSED)
2055{
2056 int c;
2057 list_T *l;
2058 listitem_T *item;
2059 long reglen = 0;
2060 int type;
2061
2062#ifdef FEAT_CMDL_INFO
2063 if (add_to_showcmd(prev_c))
2064 if (add_to_showcmd('"'))
2065 out_flush();
2066#endif
2067 c = term_vgetc();
2068#ifdef FEAT_CMDL_INFO
2069 clear_showcmd();
2070#endif
2071 if (!term_use_loop())
2072 /* job finished while waiting for a character */
2073 return;
2074
2075 /* CTRL-W "= prompt for expression to evaluate. */
2076 if (c == '=' && get_expr_register() != '=')
2077 return;
2078 if (!term_use_loop())
2079 /* job finished while waiting for a character */
2080 return;
2081
2082 l = (list_T *)get_reg_contents(c, GREG_LIST);
2083 if (l != NULL)
2084 {
2085 type = get_reg_type(c, &reglen);
2086 for (item = l->lv_first; item != NULL; item = item->li_next)
2087 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002088 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002089#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002090 char_u *tmp = s;
2091
2092 if (!enc_utf8 && enc_codepage > 0)
2093 {
2094 WCHAR *ret = NULL;
2095 int length = 0;
2096
2097 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2098 (int)STRLEN(s), &ret, &length);
2099 if (ret != NULL)
2100 {
2101 WideCharToMultiByte_alloc(CP_UTF8, 0,
2102 ret, length, (char **)&s, &length, 0, 0);
2103 vim_free(ret);
2104 }
2105 }
2106#endif
2107 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2108 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002109#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002110 if (tmp != s)
2111 vim_free(s);
2112#endif
2113
2114 if (item->li_next != NULL || type == MLINE)
2115 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2116 (char_u *)"\r", 1, NULL);
2117 }
2118 list_free(l);
2119 }
2120}
2121
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002122/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002123 * Return TRUE when waiting for a character in the terminal, the cursor of the
2124 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002125 */
2126 int
2127terminal_is_active()
2128{
2129 return in_terminal_loop != NULL;
2130}
2131
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002132#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002133 cursorentry_T *
2134term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2135{
2136 term_T *term = in_terminal_loop;
2137 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002138 int id;
2139 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140
2141 vim_memset(&entry, 0, sizeof(entry));
2142 entry.shape = entry.mshape =
2143 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2144 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2145 SHAPE_BLOCK;
2146 entry.percentage = 20;
2147 if (term->tl_cursor_blink)
2148 {
2149 entry.blinkwait = 700;
2150 entry.blinkon = 400;
2151 entry.blinkoff = 250;
2152 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002153
2154 /* The "Terminal" highlight group overrules the defaults. */
2155 id = syn_name2id((char_u *)"Terminal");
2156 if (id != 0)
2157 {
2158 syn_id2colors(id, &term_fg, &term_bg);
2159 *fg = term_bg;
2160 }
2161 else
2162 *fg = gui.back_pixel;
2163
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002164 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002165 {
2166 if (id != 0)
2167 *bg = term_fg;
2168 else
2169 *bg = gui.norm_pixel;
2170 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002171 else
2172 *bg = color_name2handle(term->tl_cursor_color);
2173 entry.name = "n";
2174 entry.used_for = SHAPE_CURSOR;
2175
2176 return &entry;
2177}
2178#endif
2179
Bram Moolenaard317b382018-02-08 22:33:31 +01002180 static void
2181may_output_cursor_props(void)
2182{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002183 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002184 || last_set_cursor_shape != desired_cursor_shape
2185 || last_set_cursor_blink != desired_cursor_blink)
2186 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002187 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002188 last_set_cursor_shape = desired_cursor_shape;
2189 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002190 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002191 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2192 /* this will restore the initial cursor style, if possible */
2193 ui_cursor_shape_forced(TRUE);
2194 else
2195 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2196 }
2197}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002198
Bram Moolenaard317b382018-02-08 22:33:31 +01002199/*
2200 * Set the cursor color and shape, if not last set to these.
2201 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202 static void
2203may_set_cursor_props(term_T *term)
2204{
2205#ifdef FEAT_GUI
2206 /* For the GUI the cursor properties are obtained with
2207 * term_get_cursor_shape(). */
2208 if (gui.in_use)
2209 return;
2210#endif
2211 if (in_terminal_loop == term)
2212 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002213 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002214 desired_cursor_shape = term->tl_cursor_shape;
2215 desired_cursor_blink = term->tl_cursor_blink;
2216 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002217 }
2218}
2219
Bram Moolenaard317b382018-02-08 22:33:31 +01002220/*
2221 * Reset the desired cursor properties and restore them when needed.
2222 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002223 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002224prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002225{
2226#ifdef FEAT_GUI
2227 if (gui.in_use)
2228 return;
2229#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002230 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002231 desired_cursor_shape = -1;
2232 desired_cursor_blink = -1;
2233 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002234}
2235
2236/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002237 * Returns TRUE if the current window contains a terminal and we are sending
2238 * keys to the job.
2239 * If "check_job_status" is TRUE update the job status.
2240 */
2241 static int
2242term_use_loop_check(int check_job_status)
2243{
2244 term_T *term = curbuf->b_term;
2245
2246 return term != NULL
2247 && !term->tl_normal_mode
2248 && term->tl_vterm != NULL
2249 && term_job_running_check(term, check_job_status);
2250}
2251
2252/*
2253 * Returns TRUE if the current window contains a terminal and we are sending
2254 * keys to the job.
2255 */
2256 int
2257term_use_loop(void)
2258{
2259 return term_use_loop_check(FALSE);
2260}
2261
2262/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002263 * Called when entering a window with the mouse. If this is a terminal window
2264 * we may want to change state.
2265 */
2266 void
2267term_win_entered()
2268{
2269 term_T *term = curbuf->b_term;
2270
2271 if (term != NULL)
2272 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002273 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002274 {
2275 reset_VIsual_and_resel();
2276 if (State & INSERT)
2277 stop_insert_mode = TRUE;
2278 }
2279 mouse_was_outside = FALSE;
2280 enter_mouse_col = mouse_col;
2281 enter_mouse_row = mouse_row;
2282 }
2283}
2284
2285/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002286 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2287 * Return the Ctrl-key value in that case.
2288 */
2289 static int
2290raw_c_to_ctrl(int c)
2291{
2292 if ((mod_mask & MOD_MASK_CTRL)
2293 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2294 return c & 0x1f;
2295 return c;
2296}
2297
2298/*
2299 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2300 * May set "mod_mask".
2301 */
2302 static int
2303ctrl_to_raw_c(int c)
2304{
2305 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2306 {
2307 mod_mask |= MOD_MASK_CTRL;
2308 return c + '@';
2309 }
2310 return c;
2311}
2312
2313/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002314 * Wait for input and send it to the job.
2315 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2316 * when there is no more typahead.
2317 * Return when the start of a CTRL-W command is typed or anything else that
2318 * should be handled as a Normal mode command.
2319 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2320 * the terminal was closed.
2321 */
2322 int
2323terminal_loop(int blocking)
2324{
2325 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002326 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002327 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002328 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002329#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002330 int tty_fd = curbuf->b_term->tl_job->jv_channel
2331 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002332#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002333 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002334
2335 /* Remember the terminal we are sending keys to. However, the terminal
2336 * might be closed while waiting for a character, e.g. typing "exit" in a
2337 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2338 * stored reference. */
2339 in_terminal_loop = curbuf->b_term;
2340
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002341 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002342 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002343 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002344 if (termwinkey == Ctrl_W)
2345 termwinkey = 0;
2346 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002347 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2348 may_set_cursor_props(curbuf->b_term);
2349
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002350 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002352#ifdef FEAT_GUI
2353 if (!curbuf->b_term->tl_system)
2354#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002355 // TODO: skip screen update when handling a sequence of keys.
2356 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002357 while (must_redraw != 0)
2358 if (update_screen(0) == FAIL)
2359 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002360 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002361 /* job finished while redrawing */
2362 break;
2363
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002364 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002365 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002366
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002367 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002368 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002369 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002370 /* Job finished while waiting for a character. Push back the
2371 * received character. */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002372 if (raw_c != K_IGNORE)
2373 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002375 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002376 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002378 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002379
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002380#ifdef UNIX
2381 /*
2382 * The shell or another program may change the tty settings. Getting
2383 * them for every typed character is a bit of overhead, but it's needed
2384 * for the first character typed, e.g. when Vim starts in a shell.
2385 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002386 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002387 {
2388 ttyinfo_T info;
2389
2390 /* Get the current backspace character of the pty. */
2391 if (get_tty_info(tty_fd, &info) == OK)
2392 term_backspace_char = info.backspace;
2393 }
2394#endif
2395
Bram Moolenaar4f974752019-02-17 17:44:42 +01002396#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002397 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2398 * Use CTRL-BREAK to kill the job. */
2399 if (ctrl_break_was_pressed)
2400 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2401#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002402 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002403 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002404 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002405#ifdef FEAT_GUI
2406 && !curbuf->b_term->tl_system
2407#endif
2408 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002409 {
2410 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002411 int prev_raw_c = raw_c;
2412 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002413
2414#ifdef FEAT_CMDL_INFO
2415 if (add_to_showcmd(c))
2416 out_flush();
2417#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002418 raw_c = term_vgetc();
2419 c = raw_c_to_ctrl(raw_c);
2420
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002421#ifdef FEAT_CMDL_INFO
2422 clear_showcmd();
2423#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002424 if (!term_use_loop_check(TRUE)
2425 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 /* job finished while waiting for a character */
2427 break;
2428
2429 if (prev_c == Ctrl_BSL)
2430 {
2431 if (c == Ctrl_N)
2432 {
2433 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2434 term_enter_normal_mode();
2435 ret = FAIL;
2436 goto theend;
2437 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002438 // Send both keys to the terminal, first one here, second one
2439 // below.
2440 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2441 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442 }
2443 else if (c == Ctrl_C)
2444 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002445 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002446 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2447 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002448 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002449 {
2450 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002451 /* "'termwinkey' .": send 'termwinkey' to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002452 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002454 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002455 {
2456 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002457 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002458 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002459 else if (c == 'N')
2460 {
2461 /* CTRL-W N : go to Terminal-Normal mode. */
2462 term_enter_normal_mode();
2463 ret = FAIL;
2464 goto theend;
2465 }
2466 else if (c == '"')
2467 {
2468 term_paste_register(prev_c);
2469 continue;
2470 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002471 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002473 char_u buf[MB_MAXBYTES + 2];
2474
2475 // Put the command into the typeahead buffer, when using the
2476 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2477 buf[0] = Ctrl_W;
2478 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2479 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 ret = OK;
2481 goto theend;
2482 }
2483 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002484# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002485 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002486 {
2487 WCHAR wc;
2488 char_u mb[3];
2489
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002490 mb[0] = (unsigned)raw_c >> 8;
2491 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002492 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002493 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002494 }
2495# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002496 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002497 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002498 if (raw_c == K_MOUSEMOVE)
Bram Moolenaard317b382018-02-08 22:33:31 +01002499 /* We are sure to come back here, don't reset the cursor color
2500 * and shape to avoid flickering. */
2501 restore_cursor = FALSE;
2502
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002503 ret = OK;
2504 goto theend;
2505 }
2506 }
2507 ret = FAIL;
2508
2509theend:
2510 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002511 if (restore_cursor)
2512 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002513
2514 /* Move a snapshot of the screen contents to the buffer, so that completion
2515 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002516 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2517 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002518
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002519 return ret;
2520}
2521
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522 static void
2523may_toggle_cursor(term_T *term)
2524{
2525 if (in_terminal_loop == term)
2526 {
2527 if (term->tl_cursor_visible)
2528 cursor_on();
2529 else
2530 cursor_off();
2531 }
2532}
2533
2534/*
2535 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002536 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002537 */
2538 static int
2539color2index(VTermColor *color, int fg, int *boldp)
2540{
2541 int red = color->red;
2542 int blue = color->blue;
2543 int green = color->green;
2544
Bram Moolenaar46359e12017-11-29 22:33:38 +01002545 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002546 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002547 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002548 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002549 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002550 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002551 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002552 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2553 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2554 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002555 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002556 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2557 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2558 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2559 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2560 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2561 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2562 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2563 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2564 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2565 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2566 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 }
2568 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002569
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570 if (t_colors >= 256)
2571 {
2572 if (red == blue && red == green)
2573 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002574 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002575 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002576 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2577 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2578 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002579 int i;
2580
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002581 if (red < 5)
2582 return 17; /* 00/00/00 */
2583 if (red > 245) /* ff/ff/ff */
2584 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002585 for (i = 0; i < 23; ++i)
2586 if (red < cutoff[i])
2587 return i + 233;
2588 return 256;
2589 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002590 {
2591 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2592 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002594 /* 216-color cube */
2595 for (ri = 0; ri < 5; ++ri)
2596 if (red < cutoff[ri])
2597 break;
2598 for (gi = 0; gi < 5; ++gi)
2599 if (green < cutoff[gi])
2600 break;
2601 for (bi = 0; bi < 5; ++bi)
2602 if (blue < cutoff[bi])
2603 break;
2604 return 17 + ri * 36 + gi * 6 + bi;
2605 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002606 }
2607 return 0;
2608}
2609
2610/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002611 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002612 */
2613 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002614vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002615{
2616 int attr = 0;
2617
2618 if (cellattrs.bold)
2619 attr |= HL_BOLD;
2620 if (cellattrs.underline)
2621 attr |= HL_UNDERLINE;
2622 if (cellattrs.italic)
2623 attr |= HL_ITALIC;
2624 if (cellattrs.strike)
2625 attr |= HL_STRIKETHROUGH;
2626 if (cellattrs.reverse)
2627 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002628 return attr;
2629}
2630
2631/*
2632 * Store Vterm attributes in "cell" from highlight flags.
2633 */
2634 static void
2635hl2vtermAttr(int attr, cellattr_T *cell)
2636{
2637 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2638 if (attr & HL_BOLD)
2639 cell->attrs.bold = 1;
2640 if (attr & HL_UNDERLINE)
2641 cell->attrs.underline = 1;
2642 if (attr & HL_ITALIC)
2643 cell->attrs.italic = 1;
2644 if (attr & HL_STRIKETHROUGH)
2645 cell->attrs.strike = 1;
2646 if (attr & HL_INVERSE)
2647 cell->attrs.reverse = 1;
2648}
2649
2650/*
2651 * Convert the attributes of a vterm cell into an attribute index.
2652 */
2653 static int
2654cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2655{
2656 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002657
2658#ifdef FEAT_GUI
2659 if (gui.in_use)
2660 {
2661 guicolor_T fg, bg;
2662
2663 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2664 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2665 return get_gui_attr_idx(attr, fg, bg);
2666 }
2667 else
2668#endif
2669#ifdef FEAT_TERMGUICOLORS
2670 if (p_tgc)
2671 {
2672 guicolor_T fg, bg;
2673
2674 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2675 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2676
2677 return get_tgc_attr_idx(attr, fg, bg);
2678 }
2679 else
2680#endif
2681 {
2682 int bold = MAYBE;
2683 int fg = color2index(&cellfg, TRUE, &bold);
2684 int bg = color2index(&cellbg, FALSE, &bold);
2685
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002686 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002687 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002688 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002689 if (fg == 0 && term_default_cterm_fg >= 0)
2690 fg = term_default_cterm_fg + 1;
2691 if (bg == 0 && term_default_cterm_bg >= 0)
2692 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002693 }
2694
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002695 /* with 8 colors set the bold attribute to get a bright foreground */
2696 if (bold == TRUE)
2697 attr |= HL_BOLD;
2698 return get_cterm_attr_idx(attr, fg, bg);
2699 }
2700 return 0;
2701}
2702
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002703 static void
2704set_dirty_snapshot(term_T *term)
2705{
2706 term->tl_dirty_snapshot = TRUE;
2707#ifdef FEAT_TIMERS
2708 if (!term->tl_normal_mode)
2709 {
2710 /* Update the snapshot after 100 msec of not getting updates. */
2711 profile_setlimit(100L, &term->tl_timer_due);
2712 term->tl_timer_set = TRUE;
2713 }
2714#endif
2715}
2716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 static int
2718handle_damage(VTermRect rect, void *user)
2719{
2720 term_T *term = (term_T *)user;
2721
2722 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2723 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002724 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002725 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002726 return 1;
2727}
2728
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002729 static void
2730term_scroll_up(term_T *term, int start_row, int count)
2731{
2732 win_T *wp;
2733 VTermColor fg, bg;
2734 VTermScreenCellAttrs attr;
2735 int clear_attr;
2736
2737 /* Set the color to clear lines with. */
2738 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2739 &fg, &bg);
2740 vim_memset(&attr, 0, sizeof(attr));
2741 clear_attr = cell2attr(attr, fg, bg);
2742
2743 FOR_ALL_WINDOWS(wp)
2744 {
2745 if (wp->w_buffer == term->tl_buffer)
2746 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2747 }
2748}
2749
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002750 static int
2751handle_moverect(VTermRect dest, VTermRect src, void *user)
2752{
2753 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002754 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002755
2756 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002757 * redrawing the text. But avoid doing this multiple times, postpone until
2758 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002759 if (dest.start_col == src.start_col
2760 && dest.end_col == src.end_col
2761 && dest.start_row < src.start_row)
2762 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002763 if (dest.start_row == 0)
2764 term->tl_postponed_scroll += count;
2765 else
2766 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002767 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002768
2769 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2770 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002771 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002772
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002773 /* Note sure if the scrolling will work correctly, let's do a complete
2774 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002775 redraw_buf_later(term->tl_buffer, NOT_VALID);
2776 return 1;
2777}
2778
2779 static int
2780handle_movecursor(
2781 VTermPos pos,
2782 VTermPos oldpos UNUSED,
2783 int visible,
2784 void *user)
2785{
2786 term_T *term = (term_T *)user;
2787 win_T *wp;
2788
2789 term->tl_cursor_pos = pos;
2790 term->tl_cursor_visible = visible;
2791
2792 FOR_ALL_WINDOWS(wp)
2793 {
2794 if (wp->w_buffer == term->tl_buffer)
2795 position_cursor(wp, &pos);
2796 }
2797 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2798 {
2799 may_toggle_cursor(term);
2800 update_cursor(term, term->tl_cursor_visible);
2801 }
2802
2803 return 1;
2804}
2805
2806 static int
2807handle_settermprop(
2808 VTermProp prop,
2809 VTermValue *value,
2810 void *user)
2811{
2812 term_T *term = (term_T *)user;
2813
2814 switch (prop)
2815 {
2816 case VTERM_PROP_TITLE:
2817 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002818 // a blank title isn't useful, make it empty, so that "running" is
2819 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002820 if (*skipwhite((char_u *)value->string) == NUL)
2821 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002822 // Same as blank
2823 else if (term->tl_arg0_cmd != NULL
2824 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2825 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2826 term->tl_title = NULL;
2827 // Empty corrupted data of winpty
2828 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2829 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002830#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002831 else if (!enc_utf8 && enc_codepage > 0)
2832 {
2833 WCHAR *ret = NULL;
2834 int length = 0;
2835
2836 MultiByteToWideChar_alloc(CP_UTF8, 0,
2837 (char*)value->string, (int)STRLEN(value->string),
2838 &ret, &length);
2839 if (ret != NULL)
2840 {
2841 WideCharToMultiByte_alloc(enc_codepage, 0,
2842 ret, length, (char**)&term->tl_title,
2843 &length, 0, 0);
2844 vim_free(ret);
2845 }
2846 }
2847#endif
2848 else
2849 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002850 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002851 if (term == curbuf->b_term)
2852 maketitle();
2853 break;
2854
2855 case VTERM_PROP_CURSORVISIBLE:
2856 term->tl_cursor_visible = value->boolean;
2857 may_toggle_cursor(term);
2858 out_flush();
2859 break;
2860
2861 case VTERM_PROP_CURSORBLINK:
2862 term->tl_cursor_blink = value->boolean;
2863 may_set_cursor_props(term);
2864 break;
2865
2866 case VTERM_PROP_CURSORSHAPE:
2867 term->tl_cursor_shape = value->number;
2868 may_set_cursor_props(term);
2869 break;
2870
2871 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002872 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002873 may_set_cursor_props(term);
2874 break;
2875
2876 case VTERM_PROP_ALTSCREEN:
2877 /* TODO: do anything else? */
2878 term->tl_using_altscreen = value->boolean;
2879 break;
2880
2881 default:
2882 break;
2883 }
2884 /* Always return 1, otherwise vterm doesn't store the value internally. */
2885 return 1;
2886}
2887
2888/*
2889 * The job running in the terminal resized the terminal.
2890 */
2891 static int
2892handle_resize(int rows, int cols, void *user)
2893{
2894 term_T *term = (term_T *)user;
2895 win_T *wp;
2896
2897 term->tl_rows = rows;
2898 term->tl_cols = cols;
2899 if (term->tl_vterm_size_changed)
2900 /* Size was set by vterm_set_size(), don't set the window size. */
2901 term->tl_vterm_size_changed = FALSE;
2902 else
2903 {
2904 FOR_ALL_WINDOWS(wp)
2905 {
2906 if (wp->w_buffer == term->tl_buffer)
2907 {
2908 win_setheight_win(rows, wp);
2909 win_setwidth_win(cols, wp);
2910 }
2911 }
2912 redraw_buf_later(term->tl_buffer, NOT_VALID);
2913 }
2914 return 1;
2915}
2916
2917/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002918 * If the number of lines that are stored goes over 'termscrollback' then
2919 * delete the first 10%.
2920 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2921 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002922 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002923 static void
2924limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002925{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002926 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002927 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002928 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002929 int i;
2930
2931 curbuf = term->tl_buffer;
2932 for (i = 0; i < todo; ++i)
2933 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002934 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2935 if (update_buffer)
2936 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002937 }
2938 curbuf = curwin->w_buffer;
2939
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002940 gap->ga_len -= todo;
2941 mch_memmove(gap->ga_data,
2942 (sb_line_T *)gap->ga_data + todo,
2943 sizeof(sb_line_T) * gap->ga_len);
2944 if (update_buffer)
2945 term->tl_scrollback_scrolled -= todo;
2946 }
2947}
2948
2949/*
2950 * Handle a line that is pushed off the top of the screen.
2951 */
2952 static int
2953handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2954{
2955 term_T *term = (term_T *)user;
2956 garray_T *gap;
2957 int update_buffer;
2958
2959 if (term->tl_normal_mode)
2960 {
2961 // In Terminal-Normal mode the user interacts with the buffer, thus we
2962 // must not change it. Postpone adding the scrollback lines.
2963 gap = &term->tl_scrollback_postponed;
2964 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002965 }
2966 else
2967 {
2968 // First remove the lines that were appended before, the pushed line
2969 // goes above it.
2970 cleanup_scrollback(term);
2971 gap = &term->tl_scrollback;
2972 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002973 }
2974
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002975 limit_scrollback(term, gap, update_buffer);
2976
2977 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002978 {
2979 cellattr_T *p = NULL;
2980 int len = 0;
2981 int i;
2982 int c;
2983 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002984 int text_len;
2985 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002986 sb_line_T *line;
2987 garray_T ga;
2988 cellattr_T fill_attr = term->tl_default_color;
2989
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002990 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002991 for (i = 0; i < cols; ++i)
2992 if (cells[i].chars[0] != 0)
2993 len = i + 1;
2994 else
2995 cell2cellattr(&cells[i], &fill_attr);
2996
2997 ga_init2(&ga, 1, 100);
2998 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002999 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 if (p != NULL)
3001 {
3002 for (col = 0; col < len; col += cells[col].width)
3003 {
3004 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3005 {
3006 ga.ga_len = 0;
3007 break;
3008 }
3009 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3010 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3011 (char_u *)ga.ga_data + ga.ga_len);
3012 cell2cellattr(&cells[col], &p[col]);
3013 }
3014 }
3015 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003016 {
3017 if (update_buffer)
3018 text = (char_u *)"";
3019 else
3020 text = vim_strsave((char_u *)"");
3021 text_len = 0;
3022 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003023 else
3024 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003025 text = ga.ga_data;
3026 text_len = ga.ga_len;
3027 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003028 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003029 if (update_buffer)
3030 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003031
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003032 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003033 line->sb_cols = len;
3034 line->sb_cells = p;
3035 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003036 if (update_buffer)
3037 {
3038 line->sb_text = NULL;
3039 ++term->tl_scrollback_scrolled;
3040 ga_clear(&ga); // free the text
3041 }
3042 else
3043 {
3044 line->sb_text = text;
3045 ga_init(&ga); // text is kept in tl_scrollback_postponed
3046 }
3047 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003048 }
3049 return 0; /* ignored */
3050}
3051
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003052/*
3053 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3054 * received and stored in tl_scrollback_postponed.
3055 */
3056 static void
3057handle_postponed_scrollback(term_T *term)
3058{
3059 int i;
3060
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003061 if (term->tl_scrollback_postponed.ga_len == 0)
3062 return;
3063 ch_log(NULL, "Moving postponed scrollback to scrollback");
3064
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003065 // First remove the lines that were appended before, the pushed lines go
3066 // above it.
3067 cleanup_scrollback(term);
3068
3069 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3070 {
3071 char_u *text;
3072 sb_line_T *pp_line;
3073 sb_line_T *line;
3074
3075 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3076 break;
3077 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3078
3079 text = pp_line->sb_text;
3080 if (text == NULL)
3081 text = (char_u *)"";
3082 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3083 vim_free(pp_line->sb_text);
3084
3085 line = (sb_line_T *)term->tl_scrollback.ga_data
3086 + term->tl_scrollback.ga_len;
3087 line->sb_cols = pp_line->sb_cols;
3088 line->sb_cells = pp_line->sb_cells;
3089 line->sb_fill_attr = pp_line->sb_fill_attr;
3090 line->sb_text = NULL;
3091 ++term->tl_scrollback_scrolled;
3092 ++term->tl_scrollback.ga_len;
3093 }
3094
3095 ga_clear(&term->tl_scrollback_postponed);
3096 limit_scrollback(term, &term->tl_scrollback, TRUE);
3097}
3098
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003099static VTermScreenCallbacks screen_callbacks = {
3100 handle_damage, /* damage */
3101 handle_moverect, /* moverect */
3102 handle_movecursor, /* movecursor */
3103 handle_settermprop, /* settermprop */
3104 NULL, /* bell */
3105 handle_resize, /* resize */
3106 handle_pushline, /* sb_pushline */
3107 NULL /* sb_popline */
3108};
3109
3110/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003111 * Do the work after the channel of a terminal was closed.
3112 * Must be called only when updating_screen is FALSE.
3113 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3114 */
3115 static int
3116term_after_channel_closed(term_T *term)
3117{
3118 /* Unless in Terminal-Normal mode: clear the vterm. */
3119 if (!term->tl_normal_mode)
3120 {
3121 int fnum = term->tl_buffer->b_fnum;
3122
3123 cleanup_vterm(term);
3124
3125 if (term->tl_finish == TL_FINISH_CLOSE)
3126 {
3127 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003128 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003129
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003130 // If this is the last normal window: exit Vim.
3131 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3132 {
3133 exarg_T ea;
3134
3135 vim_memset(&ea, 0, sizeof(ea));
3136 ex_quit(&ea);
3137 return TRUE;
3138 }
3139
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003140 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003141 ch_log(NULL, "terminal job finished, closing window");
3142 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003143 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003144 if (curwin == aucmd_win)
3145 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003146 if (do_set_w_closing)
3147 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003148 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003149 if (do_set_w_closing)
3150 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003151 aucmd_restbuf(&aco);
3152 return TRUE;
3153 }
3154 if (term->tl_finish == TL_FINISH_OPEN
3155 && term->tl_buffer->b_nwindows == 0)
3156 {
3157 char buf[50];
3158
3159 /* TODO: use term_opencmd */
3160 ch_log(NULL, "terminal job finished, opening window");
3161 vim_snprintf(buf, sizeof(buf),
3162 term->tl_opencmd == NULL
3163 ? "botright sbuf %d"
3164 : (char *)term->tl_opencmd, fnum);
3165 do_cmdline_cmd((char_u *)buf);
3166 }
3167 else
3168 ch_log(NULL, "terminal job finished");
3169 }
3170
3171 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3172 return FALSE;
3173}
3174
3175/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003176 * Called when a channel has been closed.
3177 * If this was a channel for a terminal window then finish it up.
3178 */
3179 void
3180term_channel_closed(channel_T *ch)
3181{
3182 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003183 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003184 int did_one = FALSE;
3185
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003186 for (term = first_term; term != NULL; term = next_term)
3187 {
3188 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003189 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003190 {
3191 term->tl_channel_closed = TRUE;
3192 did_one = TRUE;
3193
Bram Moolenaard23a8232018-02-10 18:45:26 +01003194 VIM_CLEAR(term->tl_title);
3195 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003196#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003197 if (term->tl_out_fd != NULL)
3198 {
3199 fclose(term->tl_out_fd);
3200 term->tl_out_fd = NULL;
3201 }
3202#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003203
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003204 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003205 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003206 /* Cannot open or close windows now. Can happen when
3207 * 'lazyredraw' is set. */
3208 term->tl_channel_recently_closed = TRUE;
3209 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003210 }
3211
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003212 if (term_after_channel_closed(term))
3213 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003214 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003215 }
3216
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003217 if (did_one)
3218 {
3219 redraw_statuslines();
3220
3221 /* Need to break out of vgetc(). */
3222 ins_char_typebuf(K_IGNORE);
3223 typebuf_was_filled = TRUE;
3224
3225 term = curbuf->b_term;
3226 if (term != NULL)
3227 {
3228 if (term->tl_job == ch->ch_job)
3229 maketitle();
3230 update_cursor(term, term->tl_cursor_visible);
3231 }
3232 }
3233}
3234
3235/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003236 * To be called after resetting updating_screen: handle any terminal where the
3237 * channel was closed.
3238 */
3239 void
3240term_check_channel_closed_recently()
3241{
3242 term_T *term;
3243 term_T *next_term;
3244
3245 for (term = first_term; term != NULL; term = next_term)
3246 {
3247 next_term = term->tl_next;
3248 if (term->tl_channel_recently_closed)
3249 {
3250 term->tl_channel_recently_closed = FALSE;
3251 if (term_after_channel_closed(term))
3252 // start over, the list may have changed
3253 next_term = first_term;
3254 }
3255 }
3256}
3257
3258/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003259 * Fill one screen line from a line of the terminal.
3260 * Advances "pos" to past the last column.
3261 */
3262 static void
3263term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3264{
3265 int off = screen_get_current_line_off();
3266
3267 for (pos->col = 0; pos->col < max_col; )
3268 {
3269 VTermScreenCell cell;
3270 int c;
3271
3272 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3273 vim_memset(&cell, 0, sizeof(cell));
3274
3275 c = cell.chars[0];
3276 if (c == NUL)
3277 {
3278 ScreenLines[off] = ' ';
3279 if (enc_utf8)
3280 ScreenLinesUC[off] = NUL;
3281 }
3282 else
3283 {
3284 if (enc_utf8)
3285 {
3286 int i;
3287
3288 /* composing chars */
3289 for (i = 0; i < Screen_mco
3290 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3291 {
3292 ScreenLinesC[i][off] = cell.chars[i + 1];
3293 if (cell.chars[i + 1] == 0)
3294 break;
3295 }
3296 if (c >= 0x80 || (Screen_mco > 0
3297 && ScreenLinesC[0][off] != 0))
3298 {
3299 ScreenLines[off] = ' ';
3300 ScreenLinesUC[off] = c;
3301 }
3302 else
3303 {
3304 ScreenLines[off] = c;
3305 ScreenLinesUC[off] = NUL;
3306 }
3307 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003308#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003309 else if (has_mbyte && c >= 0x80)
3310 {
3311 char_u mb[MB_MAXBYTES+1];
3312 WCHAR wc = c;
3313
3314 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3315 (char*)mb, 2, 0, 0) > 1)
3316 {
3317 ScreenLines[off] = mb[0];
3318 ScreenLines[off + 1] = mb[1];
3319 cell.width = mb_ptr2cells(mb);
3320 }
3321 else
3322 ScreenLines[off] = c;
3323 }
3324#endif
3325 else
3326 ScreenLines[off] = c;
3327 }
3328 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3329
3330 ++pos->col;
3331 ++off;
3332 if (cell.width == 2)
3333 {
3334 if (enc_utf8)
3335 ScreenLinesUC[off] = NUL;
3336
3337 /* don't set the second byte to NUL for a DBCS encoding, it
3338 * has been set above */
3339 if (enc_utf8 || !has_mbyte)
3340 ScreenLines[off] = NUL;
3341
3342 ++pos->col;
3343 ++off;
3344 }
3345 }
3346}
3347
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003348#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003349 static void
3350update_system_term(term_T *term)
3351{
3352 VTermPos pos;
3353 VTermScreen *screen;
3354
3355 if (term->tl_vterm == NULL)
3356 return;
3357 screen = vterm_obtain_screen(term->tl_vterm);
3358
3359 /* Scroll up to make more room for terminal lines if needed. */
3360 while (term->tl_toprow > 0
3361 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3362 {
3363 int save_p_more = p_more;
3364
3365 p_more = FALSE;
3366 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003367 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003368 p_more = save_p_more;
3369 --term->tl_toprow;
3370 }
3371
3372 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3373 && pos.row < Rows; ++pos.row)
3374 {
3375 if (pos.row < term->tl_rows)
3376 {
3377 int max_col = MIN(Columns, term->tl_cols);
3378
3379 term_line2screenline(screen, &pos, max_col);
3380 }
3381 else
3382 pos.col = 0;
3383
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003384 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003385 }
3386
3387 term->tl_dirty_row_start = MAX_ROW;
3388 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003389}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003390#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003391
3392/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003393 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3394 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003395 * Terminal-Normal mode.
3396 */
3397 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003398term_do_update_window(win_T *wp)
3399{
3400 term_T *term = wp->w_buffer->b_term;
3401
3402 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3403}
3404
3405/*
3406 * Called to update a window that contains an active terminal.
3407 */
3408 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003409term_update_window(win_T *wp)
3410{
3411 term_T *term = wp->w_buffer->b_term;
3412 VTerm *vterm;
3413 VTermScreen *screen;
3414 VTermState *state;
3415 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003416 int rows, cols;
3417 int newrows, newcols;
3418 int minsize;
3419 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003421 vterm = term->tl_vterm;
3422 screen = vterm_obtain_screen(vterm);
3423 state = vterm_obtain_state(vterm);
3424
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003425 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3426 * SOME_VALID only redraw what was marked dirty. */
3427 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003428 {
3429 term->tl_dirty_row_start = 0;
3430 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003431
3432 if (term->tl_postponed_scroll > 0
3433 && term->tl_postponed_scroll < term->tl_rows / 3)
3434 /* Scrolling is usually faster than redrawing, when there are only
3435 * a few lines to scroll. */
3436 term_scroll_up(term, 0, term->tl_postponed_scroll);
3437 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003438 }
3439
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003440 /*
3441 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003442 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003443 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003444 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003445
Bram Moolenaar498c2562018-04-15 23:45:15 +02003446 newrows = 99999;
3447 newcols = 99999;
3448 FOR_ALL_WINDOWS(twp)
3449 {
3450 /* When more than one window shows the same terminal, use the
3451 * smallest size. */
3452 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003453 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003454 newrows = MIN(newrows, twp->w_height);
3455 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003456 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003457 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003458 if (newrows == 99999 || newcols == 99999)
3459 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003460 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3461 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3462
3463 if (term->tl_rows != newrows || term->tl_cols != newcols)
3464 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003465 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003466 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003467 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003468 newrows);
3469 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003470
3471 // Updating the terminal size will cause the snapshot to be cleared.
3472 // When not in terminal_loop() we need to restore it.
3473 if (term != in_terminal_loop)
3474 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003475 }
3476
3477 /* The cursor may have been moved when resizing. */
3478 vterm_state_get_cursorpos(state, &pos);
3479 position_cursor(wp, &pos);
3480
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003481 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3482 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003483 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003484 if (pos.row < term->tl_rows)
3485 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003486 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003487
Bram Moolenaar13568252018-03-16 20:46:58 +01003488 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003489 }
3490 else
3491 pos.col = 0;
3492
Bram Moolenaarf118d482018-03-13 13:14:00 +01003493 screen_line(wp->w_winrow + pos.row
3494#ifdef FEAT_MENU
3495 + winbar_height(wp)
3496#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003497 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003498 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003499 term->tl_dirty_row_start = MAX_ROW;
3500 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003501}
3502
3503/*
3504 * Return TRUE if "wp" is a terminal window where the job has finished.
3505 */
3506 int
3507term_is_finished(buf_T *buf)
3508{
3509 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3510}
3511
3512/*
3513 * Return TRUE if "wp" is a terminal window where the job has finished or we
3514 * are in Terminal-Normal mode, thus we show the buffer contents.
3515 */
3516 int
3517term_show_buffer(buf_T *buf)
3518{
3519 term_T *term = buf->b_term;
3520
3521 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3522}
3523
3524/*
3525 * The current buffer is going to be changed. If there is terminal
3526 * highlighting remove it now.
3527 */
3528 void
3529term_change_in_curbuf(void)
3530{
3531 term_T *term = curbuf->b_term;
3532
3533 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3534 {
3535 free_scrollback(term);
3536 redraw_buf_later(term->tl_buffer, NOT_VALID);
3537
3538 /* The buffer is now like a normal buffer, it cannot be easily
3539 * abandoned when changed. */
3540 set_string_option_direct((char_u *)"buftype", -1,
3541 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3542 }
3543}
3544
3545/*
3546 * Get the screen attribute for a position in the buffer.
3547 * Use a negative "col" to get the filler background color.
3548 */
3549 int
3550term_get_attr(buf_T *buf, linenr_T lnum, int col)
3551{
3552 term_T *term = buf->b_term;
3553 sb_line_T *line;
3554 cellattr_T *cellattr;
3555
3556 if (lnum > term->tl_scrollback.ga_len)
3557 cellattr = &term->tl_default_color;
3558 else
3559 {
3560 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3561 if (col < 0 || col >= line->sb_cols)
3562 cellattr = &line->sb_fill_attr;
3563 else
3564 cellattr = line->sb_cells + col;
3565 }
3566 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3567}
3568
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003569/*
3570 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003571 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003572 */
3573 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003574cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003575{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003576 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003577}
3578
3579/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003580 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003581 */
3582 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003583init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003584{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003585 VTermColor *fg, *bg;
3586 int fgval, bgval;
3587 int id;
3588
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003589 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3590 term->tl_default_color.width = 1;
3591 fg = &term->tl_default_color.fg;
3592 bg = &term->tl_default_color.bg;
3593
3594 /* Vterm uses a default black background. Set it to white when
3595 * 'background' is "light". */
3596 if (*p_bg == 'l')
3597 {
3598 fgval = 0;
3599 bgval = 255;
3600 }
3601 else
3602 {
3603 fgval = 255;
3604 bgval = 0;
3605 }
3606 fg->red = fg->green = fg->blue = fgval;
3607 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003608 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003609
3610 /* The "Terminal" highlight group overrules the defaults. */
3611 id = syn_name2id((char_u *)"Terminal");
3612
Bram Moolenaar46359e12017-11-29 22:33:38 +01003613 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003614#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3615 if (0
3616# ifdef FEAT_GUI
3617 || gui.in_use
3618# endif
3619# ifdef FEAT_TERMGUICOLORS
3620 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003621# ifdef FEAT_VTP
3622 /* Finally get INVALCOLOR on this execution path */
3623 || (!p_tgc && t_colors >= 256)
3624# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003625# endif
3626 )
3627 {
3628 guicolor_T fg_rgb = INVALCOLOR;
3629 guicolor_T bg_rgb = INVALCOLOR;
3630
3631 if (id != 0)
3632 syn_id2colors(id, &fg_rgb, &bg_rgb);
3633
3634# ifdef FEAT_GUI
3635 if (gui.in_use)
3636 {
3637 if (fg_rgb == INVALCOLOR)
3638 fg_rgb = gui.norm_pixel;
3639 if (bg_rgb == INVALCOLOR)
3640 bg_rgb = gui.back_pixel;
3641 }
3642# ifdef FEAT_TERMGUICOLORS
3643 else
3644# endif
3645# endif
3646# ifdef FEAT_TERMGUICOLORS
3647 {
3648 if (fg_rgb == INVALCOLOR)
3649 fg_rgb = cterm_normal_fg_gui_color;
3650 if (bg_rgb == INVALCOLOR)
3651 bg_rgb = cterm_normal_bg_gui_color;
3652 }
3653# endif
3654 if (fg_rgb != INVALCOLOR)
3655 {
3656 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3657
3658 fg->red = (unsigned)(rgb >> 16);
3659 fg->green = (unsigned)(rgb >> 8) & 255;
3660 fg->blue = (unsigned)rgb & 255;
3661 }
3662 if (bg_rgb != INVALCOLOR)
3663 {
3664 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3665
3666 bg->red = (unsigned)(rgb >> 16);
3667 bg->green = (unsigned)(rgb >> 8) & 255;
3668 bg->blue = (unsigned)rgb & 255;
3669 }
3670 }
3671 else
3672#endif
3673 if (id != 0 && t_colors >= 16)
3674 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003675 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003676 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003677 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003678 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003679 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003680 else
3681 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003682#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003683 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003684#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003685
3686 /* In an MS-Windows console we know the normal colors. */
3687 if (cterm_normal_fg_color > 0)
3688 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003689 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003690# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3691# ifdef VIMDLL
3692 if (!gui.in_use)
3693# endif
3694 {
3695 tmp = fg->red;
3696 fg->red = fg->blue;
3697 fg->blue = tmp;
3698 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003699# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003700 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003701# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003702 else
3703 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003704# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003705
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003706 if (cterm_normal_bg_color > 0)
3707 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003708 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003709# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3710# ifdef VIMDLL
3711 if (!gui.in_use)
3712# endif
3713 {
3714 tmp = fg->red;
3715 fg->red = fg->blue;
3716 fg->blue = tmp;
3717 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003718# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003719 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003720# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003721 else
3722 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003723# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003724 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003725}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003726
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003727#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3728/*
3729 * Set the 16 ANSI colors from array of RGB values
3730 */
3731 static void
3732set_vterm_palette(VTerm *vterm, long_u *rgb)
3733{
3734 int index = 0;
3735 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003736
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003737 for (; index < 16; index++)
3738 {
3739 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003740
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003741 color.red = (unsigned)(rgb[index] >> 16);
3742 color.green = (unsigned)(rgb[index] >> 8) & 255;
3743 color.blue = (unsigned)rgb[index] & 255;
3744 vterm_state_set_palette_color(state, index, &color);
3745 }
3746}
3747
3748/*
3749 * Set the ANSI color palette from a list of colors
3750 */
3751 static int
3752set_ansi_colors_list(VTerm *vterm, list_T *list)
3753{
3754 int n = 0;
3755 long_u rgb[16];
3756 listitem_T *li = list->lv_first;
3757
3758 for (; li != NULL && n < 16; li = li->li_next, n++)
3759 {
3760 char_u *color_name;
3761 guicolor_T guicolor;
3762
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003763 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003764 if (color_name == NULL)
3765 return FAIL;
3766
3767 guicolor = GUI_GET_COLOR(color_name);
3768 if (guicolor == INVALCOLOR)
3769 return FAIL;
3770
3771 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3772 }
3773
3774 if (n != 16 || li != NULL)
3775 return FAIL;
3776
3777 set_vterm_palette(vterm, rgb);
3778
3779 return OK;
3780}
3781
3782/*
3783 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3784 */
3785 static void
3786init_vterm_ansi_colors(VTerm *vterm)
3787{
3788 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3789
3790 if (var != NULL
3791 && (var->di_tv.v_type != VAR_LIST
3792 || var->di_tv.vval.v_list == NULL
3793 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003794 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003795}
3796#endif
3797
Bram Moolenaar52acb112018-03-18 19:20:22 +01003798/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003799 * Handles a "drop" command from the job in the terminal.
3800 * "item" is the file name, "item->li_next" may have options.
3801 */
3802 static void
3803handle_drop_command(listitem_T *item)
3804{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003805 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003806 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003807 int bufnr;
3808 win_T *wp;
3809 tabpage_T *tp;
3810 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003811 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003812
3813 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3814 FOR_ALL_TAB_WINDOWS(tp, wp)
3815 {
3816 if (wp->w_buffer->b_fnum == bufnr)
3817 {
3818 /* buffer is in a window already, go there */
3819 goto_tabpage_win(tp, wp);
3820 return;
3821 }
3822 }
3823
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003824 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003825
3826 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3827 && opt_item->li_tv.vval.v_dict != NULL)
3828 {
3829 dict_T *dict = opt_item->li_tv.vval.v_dict;
3830 char_u *p;
3831
Bram Moolenaar8f667172018-12-14 15:38:31 +01003832 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003833 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003834 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003835 if (p != NULL)
3836 {
3837 if (check_ff_value(p) == FAIL)
3838 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3839 else
3840 ea.force_ff = *p;
3841 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003842 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003843 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003844 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003845 if (p != NULL)
3846 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003847 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003848 if (ea.cmd != NULL)
3849 {
3850 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3851 ea.force_enc = 11;
3852 tofree = ea.cmd;
3853 }
3854 }
3855
Bram Moolenaar8f667172018-12-14 15:38:31 +01003856 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003857 if (p != NULL)
3858 get_bad_opt(p, &ea);
3859
3860 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3861 ea.force_bin = FORCE_BIN;
3862 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3863 ea.force_bin = FORCE_BIN;
3864 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3865 ea.force_bin = FORCE_NOBIN;
3866 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3867 ea.force_bin = FORCE_NOBIN;
3868 }
3869
3870 /* open in new window, like ":split fname" */
3871 if (ea.cmd == NULL)
3872 ea.cmd = (char_u *)"split";
3873 ea.arg = fname;
3874 ea.cmdidx = CMD_split;
3875 ex_splitview(&ea);
3876
3877 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003878}
3879
3880/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003881 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3882 */
3883 static int
3884is_permitted_term_api(char_u *func, char_u *pat)
3885{
3886 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3887}
3888
3889/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003890 * Handles a function call from the job running in a terminal.
3891 * "item" is the function name, "item->li_next" has the arguments.
3892 */
3893 static void
3894handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3895{
3896 char_u *func;
3897 typval_T argvars[2];
3898 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003899 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003900
3901 if (item->li_next == NULL)
3902 {
3903 ch_log(channel, "Missing function arguments for call");
3904 return;
3905 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003906 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003907
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003908 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003909 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003910 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003911 return;
3912 }
3913
3914 argvars[0].v_type = VAR_NUMBER;
3915 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3916 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003917 vim_memset(&funcexe, 0, sizeof(funcexe));
3918 funcexe.firstline = 1L;
3919 funcexe.lastline = 1L;
3920 funcexe.evaluate = TRUE;
3921 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003922 {
3923 clear_tv(&rettv);
3924 ch_log(channel, "Function %s called", func);
3925 }
3926 else
3927 ch_log(channel, "Calling function %s failed", func);
3928}
3929
3930/*
3931 * Called by libvterm when it cannot recognize an OSC sequence.
3932 * We recognize a terminal API command.
3933 */
3934 static int
3935parse_osc(const char *command, size_t cmdlen, void *user)
3936{
3937 term_T *term = (term_T *)user;
3938 js_read_T reader;
3939 typval_T tv;
3940 channel_T *channel = term->tl_job == NULL ? NULL
3941 : term->tl_job->jv_channel;
3942
3943 /* We recognize only OSC 5 1 ; {command} */
3944 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3945 return 0; /* not handled */
3946
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003947 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003948 if (reader.js_buf == NULL)
3949 return 1;
3950 reader.js_fill = NULL;
3951 reader.js_used = 0;
3952 if (json_decode(&reader, &tv, 0) == OK
3953 && tv.v_type == VAR_LIST
3954 && tv.vval.v_list != NULL)
3955 {
3956 listitem_T *item = tv.vval.v_list->lv_first;
3957
3958 if (item == NULL)
3959 ch_log(channel, "Missing command");
3960 else
3961 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003962 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003963
Bram Moolenaara997b452018-04-17 23:24:06 +02003964 /* Make sure an invoked command doesn't delete the buffer (and the
3965 * terminal) under our fingers. */
3966 ++term->tl_buffer->b_locked;
3967
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003968 item = item->li_next;
3969 if (item == NULL)
3970 ch_log(channel, "Missing argument for %s", cmd);
3971 else if (STRCMP(cmd, "drop") == 0)
3972 handle_drop_command(item);
3973 else if (STRCMP(cmd, "call") == 0)
3974 handle_call_command(term, channel, item);
3975 else
3976 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003977 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003978 }
3979 }
3980 else
3981 ch_log(channel, "Invalid JSON received");
3982
3983 vim_free(reader.js_buf);
3984 clear_tv(&tv);
3985 return 1;
3986}
3987
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003988/*
3989 * Called by libvterm when it cannot recognize a CSI sequence.
3990 * We recognize the window position report.
3991 */
3992 static int
3993parse_csi(
3994 const char *leader UNUSED,
3995 const long args[],
3996 int argcount,
3997 const char *intermed UNUSED,
3998 char command,
3999 void *user)
4000{
4001 term_T *term = (term_T *)user;
4002 char buf[100];
4003 int len;
4004 int x = 0;
4005 int y = 0;
4006 win_T *wp;
4007
4008 // We recognize only CSI 13 t
4009 if (command != 't' || argcount != 1 || args[0] != 13)
4010 return 0; // not handled
4011
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004012 // When getting the window position is not possible or it fails it results
4013 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004014#if defined(FEAT_GUI) \
4015 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4016 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004017 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004018#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004019
4020 FOR_ALL_WINDOWS(wp)
4021 if (wp->w_buffer == term->tl_buffer)
4022 break;
4023 if (wp != NULL)
4024 {
4025#ifdef FEAT_GUI
4026 if (gui.in_use)
4027 {
4028 x += wp->w_wincol * gui.char_width;
4029 y += W_WINROW(wp) * gui.char_height;
4030 }
4031 else
4032#endif
4033 {
4034 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004035 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004036 x += wp->w_wincol * 7;
4037 y += W_WINROW(wp) * 10;
4038 }
4039 }
4040
4041 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4042 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4043 (char_u *)buf, len, NULL);
4044 return 1;
4045}
4046
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004047static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004048 NULL, // text
4049 NULL, // control
4050 NULL, // escape
4051 parse_csi, // csi
4052 parse_osc, // osc
4053 NULL, // dcs
4054 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004055};
4056
4057/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004058 * Use Vim's allocation functions for vterm so profiling works.
4059 */
4060 static void *
4061vterm_malloc(size_t size, void *data UNUSED)
4062{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004063 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004064}
4065
4066 static void
4067vterm_memfree(void *ptr, void *data UNUSED)
4068{
4069 vim_free(ptr);
4070}
4071
4072static VTermAllocatorFunctions vterm_allocator = {
4073 &vterm_malloc,
4074 &vterm_memfree
4075};
4076
4077/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004078 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004079 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004080 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004081 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004082create_vterm(term_T *term, int rows, int cols)
4083{
4084 VTerm *vterm;
4085 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004086 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004087 VTermValue value;
4088
Bram Moolenaar756ef112018-04-10 12:04:27 +02004089 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004090 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004091 if (vterm == NULL)
4092 return FAIL;
4093
4094 // Allocate screen and state here, so we can bail out if that fails.
4095 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004096 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004097 if (state == NULL || screen == NULL)
4098 {
4099 vterm_free(vterm);
4100 return FAIL;
4101 }
4102
Bram Moolenaar52acb112018-03-18 19:20:22 +01004103 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4104 /* TODO: depends on 'encoding'. */
4105 vterm_set_utf8(vterm, 1);
4106
4107 init_default_colors(term);
4108
4109 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004110 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004111 &term->tl_default_color.fg,
4112 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004113
Bram Moolenaar9e587872019-05-13 20:27:23 +02004114 if (t_colors < 16)
4115 // Less than 16 colors: assume that bold means using a bright color for
4116 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004117 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4118
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004119 /* Required to initialize most things. */
4120 vterm_screen_reset(screen, 1 /* hard */);
4121
4122 /* Allow using alternate screen. */
4123 vterm_screen_enable_altscreen(screen, 1);
4124
4125 /* For unix do not use a blinking cursor. In an xterm this causes the
4126 * cursor to blink if it's blinking in the xterm.
4127 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004128#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004129 if (GetCaretBlinkTime() == INFINITE)
4130 value.boolean = 0;
4131 else
4132 value.boolean = 1;
4133#else
4134 value.boolean = 0;
4135#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004136 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4137 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004138
4139 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004140}
4141
4142/*
4143 * Return the text to show for the buffer name and status.
4144 */
4145 char_u *
4146term_get_status_text(term_T *term)
4147{
4148 if (term->tl_status_text == NULL)
4149 {
4150 char_u *txt;
4151 size_t len;
4152
4153 if (term->tl_normal_mode)
4154 {
4155 if (term_job_running(term))
4156 txt = (char_u *)_("Terminal");
4157 else
4158 txt = (char_u *)_("Terminal-finished");
4159 }
4160 else if (term->tl_title != NULL)
4161 txt = term->tl_title;
4162 else if (term_none_open(term))
4163 txt = (char_u *)_("active");
4164 else if (term_job_running(term))
4165 txt = (char_u *)_("running");
4166 else
4167 txt = (char_u *)_("finished");
4168 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004169 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004170 if (term->tl_status_text != NULL)
4171 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4172 term->tl_buffer->b_fname, txt);
4173 }
4174 return term->tl_status_text;
4175}
4176
4177/*
4178 * Mark references in jobs of terminals.
4179 */
4180 int
4181set_ref_in_term(int copyID)
4182{
4183 int abort = FALSE;
4184 term_T *term;
4185 typval_T tv;
4186
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004187 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188 if (term->tl_job != NULL)
4189 {
4190 tv.v_type = VAR_JOB;
4191 tv.vval.v_job = term->tl_job;
4192 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4193 }
4194 return abort;
4195}
4196
4197/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004198 * Cache "Terminal" highlight group colors.
4199 */
4200 void
4201set_terminal_default_colors(int cterm_fg, int cterm_bg)
4202{
4203 term_default_cterm_fg = cterm_fg - 1;
4204 term_default_cterm_bg = cterm_bg - 1;
4205}
4206
4207/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004208 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004209 * Returns NULL when the buffer is not for a terminal window and logs a message
4210 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004211 */
4212 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004213term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004214{
4215 buf_T *buf;
4216
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004217 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004218 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004219 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004220 --emsg_off;
4221 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004222 {
4223 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004224 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004225 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004226 return buf;
4227}
4228
Bram Moolenaard96ff162018-02-18 22:13:29 +01004229 static int
4230same_color(VTermColor *a, VTermColor *b)
4231{
4232 return a->red == b->red
4233 && a->green == b->green
4234 && a->blue == b->blue
4235 && a->ansi_index == b->ansi_index;
4236}
4237
4238 static void
4239dump_term_color(FILE *fd, VTermColor *color)
4240{
4241 fprintf(fd, "%02x%02x%02x%d",
4242 (int)color->red, (int)color->green, (int)color->blue,
4243 (int)color->ansi_index);
4244}
4245
4246/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004247 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004248 *
4249 * Each screen cell in full is:
4250 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4251 * {characters} is a space for an empty cell
4252 * For a double-width character "+" is changed to "*" and the next cell is
4253 * skipped.
4254 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4255 * when "&" use the same as the previous cell.
4256 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4257 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4258 * {color-idx} is a number from 0 to 255
4259 *
4260 * Screen cell with same width, attributes and color as the previous one:
4261 * |{characters}
4262 *
4263 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4264 *
4265 * Repeating the previous screen cell:
4266 * @{count}
4267 */
4268 void
4269f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4270{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004271 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004272 term_T *term;
4273 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004274 int max_height = 0;
4275 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004276 stat_T st;
4277 FILE *fd;
4278 VTermPos pos;
4279 VTermScreen *screen;
4280 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004281 VTermState *state;
4282 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004283
4284 if (check_restricted() || check_secure())
4285 return;
4286 if (buf == NULL)
4287 return;
4288 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004289 if (term->tl_vterm == NULL)
4290 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004291 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004292 return;
4293 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004294
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004295 if (argvars[2].v_type != VAR_UNKNOWN)
4296 {
4297 dict_T *d;
4298
4299 if (argvars[2].v_type != VAR_DICT)
4300 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004301 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004302 return;
4303 }
4304 d = argvars[2].vval.v_dict;
4305 if (d != NULL)
4306 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004307 max_height = dict_get_number(d, (char_u *)"rows");
4308 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004309 }
4310 }
4311
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004312 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004313 if (fname == NULL)
4314 return;
4315 if (mch_stat((char *)fname, &st) >= 0)
4316 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004317 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004318 return;
4319 }
4320
Bram Moolenaard96ff162018-02-18 22:13:29 +01004321 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4322 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004323 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004324 return;
4325 }
4326
4327 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4328
4329 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004330 state = vterm_obtain_state(term->tl_vterm);
4331 vterm_state_get_cursorpos(state, &cursor_pos);
4332
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004333 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4334 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004335 {
4336 int repeat = 0;
4337
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004338 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4339 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004340 {
4341 VTermScreenCell cell;
4342 int same_attr;
4343 int same_chars = TRUE;
4344 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004345 int is_cursor_pos = (pos.col == cursor_pos.col
4346 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004347
4348 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4349 vim_memset(&cell, 0, sizeof(cell));
4350
4351 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4352 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004353 int c = cell.chars[i];
4354 int pc = prev_cell.chars[i];
4355
4356 /* For the first character NUL is the same as space. */
4357 if (i == 0)
4358 {
4359 c = (c == NUL) ? ' ' : c;
4360 pc = (pc == NUL) ? ' ' : pc;
4361 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004362 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004363 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004364 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004365 break;
4366 }
4367 same_attr = vtermAttr2hl(cell.attrs)
4368 == vtermAttr2hl(prev_cell.attrs)
4369 && same_color(&cell.fg, &prev_cell.fg)
4370 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004371 if (same_chars && cell.width == prev_cell.width && same_attr
4372 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373 {
4374 ++repeat;
4375 }
4376 else
4377 {
4378 if (repeat > 0)
4379 {
4380 fprintf(fd, "@%d", repeat);
4381 repeat = 0;
4382 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004383 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004384
4385 if (cell.chars[0] == NUL)
4386 fputs(" ", fd);
4387 else
4388 {
4389 char_u charbuf[10];
4390 int len;
4391
4392 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4393 && cell.chars[i] != NUL; ++i)
4394 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004395 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004396 fwrite(charbuf, len, 1, fd);
4397 }
4398 }
4399
4400 /* When only the characters differ we don't write anything, the
4401 * following "|", "@" or NL will indicate using the same
4402 * attributes. */
4403 if (cell.width != prev_cell.width || !same_attr)
4404 {
4405 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004406 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004407 else
4408 fputs("+", fd);
4409
4410 if (same_attr)
4411 {
4412 fputs("&", fd);
4413 }
4414 else
4415 {
4416 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4417 if (same_color(&cell.fg, &prev_cell.fg))
4418 fputs("&", fd);
4419 else
4420 {
4421 fputs("#", fd);
4422 dump_term_color(fd, &cell.fg);
4423 }
4424 if (same_color(&cell.bg, &prev_cell.bg))
4425 fputs("&", fd);
4426 else
4427 {
4428 fputs("#", fd);
4429 dump_term_color(fd, &cell.bg);
4430 }
4431 }
4432 }
4433
4434 prev_cell = cell;
4435 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004436
4437 if (cell.width == 2)
4438 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004439 }
4440 if (repeat > 0)
4441 fprintf(fd, "@%d", repeat);
4442 fputs("\n", fd);
4443 }
4444
4445 fclose(fd);
4446}
4447
4448/*
4449 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4450 */
4451 static void
4452dump_is_corrupt(garray_T *gap)
4453{
4454 ga_concat(gap, (char_u *)"CORRUPT");
4455}
4456
4457 static void
4458append_cell(garray_T *gap, cellattr_T *cell)
4459{
4460 if (ga_grow(gap, 1) == OK)
4461 {
4462 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4463 ++gap->ga_len;
4464 }
4465}
4466
4467/*
4468 * Read the dump file from "fd" and append lines to the current buffer.
4469 * Return the cell width of the longest line.
4470 */
4471 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004472read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004473{
4474 int c;
4475 garray_T ga_text;
4476 garray_T ga_cell;
4477 char_u *prev_char = NULL;
4478 int attr = 0;
4479 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004480 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004481 term_T *term = curbuf->b_term;
4482 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004483 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004484
4485 ga_init2(&ga_text, 1, 90);
4486 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4487 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004488 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004489 cursor_pos->row = -1;
4490 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004491
4492 c = fgetc(fd);
4493 for (;;)
4494 {
4495 if (c == EOF)
4496 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004497 if (c == '\r')
4498 {
4499 // DOS line endings? Ignore.
4500 c = fgetc(fd);
4501 }
4502 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004503 {
4504 /* End of a line: append it to the buffer. */
4505 if (ga_text.ga_data == NULL)
4506 dump_is_corrupt(&ga_text);
4507 if (ga_grow(&term->tl_scrollback, 1) == OK)
4508 {
4509 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4510 + term->tl_scrollback.ga_len;
4511
4512 if (max_cells < ga_cell.ga_len)
4513 max_cells = ga_cell.ga_len;
4514 line->sb_cols = ga_cell.ga_len;
4515 line->sb_cells = ga_cell.ga_data;
4516 line->sb_fill_attr = term->tl_default_color;
4517 ++term->tl_scrollback.ga_len;
4518 ga_init(&ga_cell);
4519
4520 ga_append(&ga_text, NUL);
4521 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4522 ga_text.ga_len, FALSE);
4523 }
4524 else
4525 ga_clear(&ga_cell);
4526 ga_text.ga_len = 0;
4527
4528 c = fgetc(fd);
4529 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004530 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004531 {
4532 int prev_len = ga_text.ga_len;
4533
Bram Moolenaar9271d052018-02-25 21:39:46 +01004534 if (c == '>')
4535 {
4536 if (cursor_pos->row != -1)
4537 dump_is_corrupt(&ga_text); /* duplicate cursor */
4538 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4539 cursor_pos->col = ga_cell.ga_len;
4540 }
4541
Bram Moolenaard96ff162018-02-18 22:13:29 +01004542 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4543 c = fgetc(fd);
4544 if (c != EOF)
4545 ga_append(&ga_text, c);
4546 for (;;)
4547 {
4548 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004549 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004550 || c == EOF || c == '\n')
4551 break;
4552 ga_append(&ga_text, c);
4553 }
4554
4555 /* save the character for repeating it */
4556 vim_free(prev_char);
4557 if (ga_text.ga_data != NULL)
4558 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4559 ga_text.ga_len - prev_len);
4560
Bram Moolenaar9271d052018-02-25 21:39:46 +01004561 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004562 {
4563 /* use all attributes from previous cell */
4564 }
4565 else if (c == '+' || c == '*')
4566 {
4567 int is_bg;
4568
4569 cell.width = c == '+' ? 1 : 2;
4570
4571 c = fgetc(fd);
4572 if (c == '&')
4573 {
4574 /* use same attr as previous cell */
4575 c = fgetc(fd);
4576 }
4577 else if (isdigit(c))
4578 {
4579 /* get the decimal attribute */
4580 attr = 0;
4581 while (isdigit(c))
4582 {
4583 attr = attr * 10 + (c - '0');
4584 c = fgetc(fd);
4585 }
4586 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004587
4588 /* is_bg == 0: fg, is_bg == 1: bg */
4589 for (is_bg = 0; is_bg <= 1; ++is_bg)
4590 {
4591 if (c == '&')
4592 {
4593 /* use same color as previous cell */
4594 c = fgetc(fd);
4595 }
4596 else if (c == '#')
4597 {
4598 int red, green, blue, index = 0;
4599
4600 c = fgetc(fd);
4601 red = hex2nr(c);
4602 c = fgetc(fd);
4603 red = (red << 4) + hex2nr(c);
4604 c = fgetc(fd);
4605 green = hex2nr(c);
4606 c = fgetc(fd);
4607 green = (green << 4) + hex2nr(c);
4608 c = fgetc(fd);
4609 blue = hex2nr(c);
4610 c = fgetc(fd);
4611 blue = (blue << 4) + hex2nr(c);
4612 c = fgetc(fd);
4613 if (!isdigit(c))
4614 dump_is_corrupt(&ga_text);
4615 while (isdigit(c))
4616 {
4617 index = index * 10 + (c - '0');
4618 c = fgetc(fd);
4619 }
4620
4621 if (is_bg)
4622 {
4623 cell.bg.red = red;
4624 cell.bg.green = green;
4625 cell.bg.blue = blue;
4626 cell.bg.ansi_index = index;
4627 }
4628 else
4629 {
4630 cell.fg.red = red;
4631 cell.fg.green = green;
4632 cell.fg.blue = blue;
4633 cell.fg.ansi_index = index;
4634 }
4635 }
4636 else
4637 dump_is_corrupt(&ga_text);
4638 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004639 }
4640 else
4641 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004642 }
4643 else
4644 dump_is_corrupt(&ga_text);
4645
4646 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004647 if (cell.width == 2)
4648 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004649 }
4650 else if (c == '@')
4651 {
4652 if (prev_char == NULL)
4653 dump_is_corrupt(&ga_text);
4654 else
4655 {
4656 int count = 0;
4657
4658 /* repeat previous character, get the count */
4659 for (;;)
4660 {
4661 c = fgetc(fd);
4662 if (!isdigit(c))
4663 break;
4664 count = count * 10 + (c - '0');
4665 }
4666
4667 while (count-- > 0)
4668 {
4669 ga_concat(&ga_text, prev_char);
4670 append_cell(&ga_cell, &cell);
4671 }
4672 }
4673 }
4674 else
4675 {
4676 dump_is_corrupt(&ga_text);
4677 c = fgetc(fd);
4678 }
4679 }
4680
4681 if (ga_text.ga_len > 0)
4682 {
4683 /* trailing characters after last NL */
4684 dump_is_corrupt(&ga_text);
4685 ga_append(&ga_text, NUL);
4686 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4687 ga_text.ga_len, FALSE);
4688 }
4689
4690 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004691 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004692 vim_free(prev_char);
4693
4694 return max_cells;
4695}
4696
4697/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004698 * Return an allocated string with at least "text_width" "=" characters and
4699 * "fname" inserted in the middle.
4700 */
4701 static char_u *
4702get_separator(int text_width, char_u *fname)
4703{
4704 int width = MAX(text_width, curwin->w_width);
4705 char_u *textline;
4706 int fname_size;
4707 char_u *p = fname;
4708 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004709 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004710
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004711 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004712 if (textline == NULL)
4713 return NULL;
4714
4715 fname_size = vim_strsize(fname);
4716 if (fname_size < width - 8)
4717 {
4718 /* enough room, don't use the full window width */
4719 width = MAX(text_width, fname_size + 8);
4720 }
4721 else if (fname_size > width - 8)
4722 {
4723 /* full name doesn't fit, use only the tail */
4724 p = gettail(fname);
4725 fname_size = vim_strsize(p);
4726 }
4727 /* skip characters until the name fits */
4728 while (fname_size > width - 8)
4729 {
4730 p += (*mb_ptr2len)(p);
4731 fname_size = vim_strsize(p);
4732 }
4733
4734 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4735 textline[i] = '=';
4736 textline[i++] = ' ';
4737
4738 STRCPY(textline + i, p);
4739 off = STRLEN(textline);
4740 textline[off] = ' ';
4741 for (i = 1; i < (width - fname_size) / 2; ++i)
4742 textline[off + i] = '=';
4743 textline[off + i] = NUL;
4744
4745 return textline;
4746}
4747
4748/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004749 * Common for "term_dumpdiff()" and "term_dumpload()".
4750 */
4751 static void
4752term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4753{
4754 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004755 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004756 char_u buf1[NUMBUFLEN];
4757 char_u buf2[NUMBUFLEN];
4758 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004759 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004760 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004761 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004762 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004763 char_u *textline = NULL;
4764
4765 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004766 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004767 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004768 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004769 if (fname1 == NULL || (do_diff && fname2 == NULL))
4770 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004771 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004772 return;
4773 }
4774 fd1 = mch_fopen((char *)fname1, READBIN);
4775 if (fd1 == NULL)
4776 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004777 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004778 return;
4779 }
4780 if (do_diff)
4781 {
4782 fd2 = mch_fopen((char *)fname2, READBIN);
4783 if (fd2 == NULL)
4784 {
4785 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004786 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004787 return;
4788 }
4789 }
4790
4791 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004792 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4793 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4794 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4795 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4796 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004797
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004798 if (opt.jo_term_name == NULL)
4799 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004800 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004801
Bram Moolenaar51e14382019-05-25 20:21:28 +02004802 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004803 if (fname_tofree != NULL)
4804 {
4805 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4806 opt.jo_term_name = fname_tofree;
4807 }
4808 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004809
Bram Moolenaar87abab92019-06-03 21:14:59 +02004810 if (opt.jo_bufnr_buf != NULL)
4811 {
4812 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4813
4814 // With "bufnr" argument: enter the window with this buffer and make it
4815 // empty.
4816 if (wp == NULL)
4817 semsg(_(e_invarg2), "bufnr");
4818 else
4819 {
4820 buf = curbuf;
4821 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4822 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004823 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004824 redraw_later(NOT_VALID);
4825 }
4826 }
4827 else
4828 // Create a new terminal window.
4829 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4830
Bram Moolenaard96ff162018-02-18 22:13:29 +01004831 if (buf != NULL && buf->b_term != NULL)
4832 {
4833 int i;
4834 linenr_T bot_lnum;
4835 linenr_T lnum;
4836 term_T *term = buf->b_term;
4837 int width;
4838 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004839 VTermPos cursor_pos1;
4840 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004841
Bram Moolenaar52acb112018-03-18 19:20:22 +01004842 init_default_colors(term);
4843
Bram Moolenaard96ff162018-02-18 22:13:29 +01004844 rettv->vval.v_number = buf->b_fnum;
4845
4846 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004847 width = read_dump_file(fd1, &cursor_pos1);
4848
4849 /* position the cursor */
4850 if (cursor_pos1.row >= 0)
4851 {
4852 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4853 coladvance(cursor_pos1.col);
4854 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004855
4856 /* Delete the empty line that was in the empty buffer. */
4857 ml_delete(1, FALSE);
4858
4859 /* For term_dumpload() we are done here. */
4860 if (!do_diff)
4861 goto theend;
4862
4863 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4864
Bram Moolenaar4a696342018-04-05 18:45:26 +02004865 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004866 if (textline == NULL)
4867 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004868 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4869 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4870 vim_free(textline);
4871
4872 textline = get_separator(width, fname2);
4873 if (textline == NULL)
4874 goto theend;
4875 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4876 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004877 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004878
4879 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004880 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004881 if (width2 > width)
4882 {
4883 vim_free(textline);
4884 textline = alloc(width2 + 1);
4885 if (textline == NULL)
4886 goto theend;
4887 width = width2;
4888 textline[width] = NUL;
4889 }
4890 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4891
4892 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4893 {
4894 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4895 {
4896 /* bottom part has fewer rows, fill with "-" */
4897 for (i = 0; i < width; ++i)
4898 textline[i] = '-';
4899 }
4900 else
4901 {
4902 char_u *line1;
4903 char_u *line2;
4904 char_u *p1;
4905 char_u *p2;
4906 int col;
4907 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4908 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4909 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4910 ->sb_cells;
4911
4912 /* Make a copy, getting the second line will invalidate it. */
4913 line1 = vim_strsave(ml_get(lnum));
4914 if (line1 == NULL)
4915 break;
4916 p1 = line1;
4917
4918 line2 = ml_get(lnum + bot_lnum);
4919 p2 = line2;
4920 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4921 {
4922 int len1 = utfc_ptr2len(p1);
4923 int len2 = utfc_ptr2len(p2);
4924
4925 textline[col] = ' ';
4926 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004927 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004928 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004929 else if (lnum == cursor_pos1.row + 1
4930 && col == cursor_pos1.col
4931 && (cursor_pos1.row != cursor_pos2.row
4932 || cursor_pos1.col != cursor_pos2.col))
4933 /* cursor in first but not in second */
4934 textline[col] = '>';
4935 else if (lnum == cursor_pos2.row + 1
4936 && col == cursor_pos2.col
4937 && (cursor_pos1.row != cursor_pos2.row
4938 || cursor_pos1.col != cursor_pos2.col))
4939 /* cursor in second but not in first */
4940 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004941 else if (cellattr1 != NULL && cellattr2 != NULL)
4942 {
4943 if ((cellattr1 + col)->width
4944 != (cellattr2 + col)->width)
4945 textline[col] = 'w';
4946 else if (!same_color(&(cellattr1 + col)->fg,
4947 &(cellattr2 + col)->fg))
4948 textline[col] = 'f';
4949 else if (!same_color(&(cellattr1 + col)->bg,
4950 &(cellattr2 + col)->bg))
4951 textline[col] = 'b';
4952 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4953 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4954 textline[col] = 'a';
4955 }
4956 p1 += len1;
4957 p2 += len2;
4958 /* TODO: handle different width */
4959 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004960
4961 while (col < width)
4962 {
4963 if (*p1 == NUL && *p2 == NUL)
4964 textline[col] = '?';
4965 else if (*p1 == NUL)
4966 {
4967 textline[col] = '+';
4968 p2 += utfc_ptr2len(p2);
4969 }
4970 else
4971 {
4972 textline[col] = '-';
4973 p1 += utfc_ptr2len(p1);
4974 }
4975 ++col;
4976 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004977
4978 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004979 }
4980 if (add_empty_scrollback(term, &term->tl_default_color,
4981 term->tl_top_diff_rows) == OK)
4982 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4983 ++bot_lnum;
4984 }
4985
4986 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4987 {
4988 /* bottom part has more rows, fill with "+" */
4989 for (i = 0; i < width; ++i)
4990 textline[i] = '+';
4991 if (add_empty_scrollback(term, &term->tl_default_color,
4992 term->tl_top_diff_rows) == OK)
4993 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4994 ++lnum;
4995 ++bot_lnum;
4996 }
4997
4998 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004999
5000 /* looks better without wrapping */
5001 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005002 }
5003
5004theend:
5005 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005006 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005007 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005008 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005009 fclose(fd2);
5010}
5011
5012/*
5013 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5014 * bottom files.
5015 * Return FAIL when this is not possible.
5016 */
5017 int
5018term_swap_diff()
5019{
5020 term_T *term = curbuf->b_term;
5021 linenr_T line_count;
5022 linenr_T top_rows;
5023 linenr_T bot_rows;
5024 linenr_T bot_start;
5025 linenr_T lnum;
5026 char_u *p;
5027 sb_line_T *sb_line;
5028
5029 if (term == NULL
5030 || !term_is_finished(curbuf)
5031 || term->tl_top_diff_rows == 0
5032 || term->tl_scrollback.ga_len == 0)
5033 return FAIL;
5034
5035 line_count = curbuf->b_ml.ml_line_count;
5036 top_rows = term->tl_top_diff_rows;
5037 bot_rows = term->tl_bot_diff_rows;
5038 bot_start = line_count - bot_rows;
5039 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5040
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005041 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005042 for (lnum = 1; lnum <= top_rows; ++lnum)
5043 {
5044 p = vim_strsave(ml_get(1));
5045 if (p == NULL)
5046 return OK;
5047 ml_append(bot_start, p, 0, FALSE);
5048 ml_delete(1, FALSE);
5049 vim_free(p);
5050 }
5051
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005052 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005053 for (lnum = 1; lnum <= bot_rows; ++lnum)
5054 {
5055 p = vim_strsave(ml_get(bot_start + lnum));
5056 if (p == NULL)
5057 return OK;
5058 ml_delete(bot_start + lnum, FALSE);
5059 ml_append(lnum - 1, p, 0, FALSE);
5060 vim_free(p);
5061 }
5062
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005063 // move top title to bottom
5064 p = vim_strsave(ml_get(bot_rows + 1));
5065 if (p == NULL)
5066 return OK;
5067 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5068 ml_delete(bot_rows + 1, FALSE);
5069 vim_free(p);
5070
5071 // move bottom title to top
5072 p = vim_strsave(ml_get(line_count - top_rows));
5073 if (p == NULL)
5074 return OK;
5075 ml_delete(line_count - top_rows, FALSE);
5076 ml_append(bot_rows, p, 0, FALSE);
5077 vim_free(p);
5078
Bram Moolenaard96ff162018-02-18 22:13:29 +01005079 if (top_rows == bot_rows)
5080 {
5081 /* rows counts are equal, can swap cell properties */
5082 for (lnum = 0; lnum < top_rows; ++lnum)
5083 {
5084 sb_line_T temp;
5085
5086 temp = *(sb_line + lnum);
5087 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5088 *(sb_line + bot_start + lnum) = temp;
5089 }
5090 }
5091 else
5092 {
5093 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005094 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005095
5096 /* need to copy cell properties into temp memory */
5097 if (temp != NULL)
5098 {
5099 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5100 mch_memmove(term->tl_scrollback.ga_data,
5101 temp + bot_start,
5102 sizeof(sb_line_T) * bot_rows);
5103 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5104 temp + top_rows,
5105 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5106 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5107 + line_count - top_rows,
5108 temp,
5109 sizeof(sb_line_T) * top_rows);
5110 vim_free(temp);
5111 }
5112 }
5113
5114 term->tl_top_diff_rows = bot_rows;
5115 term->tl_bot_diff_rows = top_rows;
5116
5117 update_screen(NOT_VALID);
5118 return OK;
5119}
5120
5121/*
5122 * "term_dumpdiff(filename, filename, options)" function
5123 */
5124 void
5125f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5126{
5127 term_load_dump(argvars, rettv, TRUE);
5128}
5129
5130/*
5131 * "term_dumpload(filename, options)" function
5132 */
5133 void
5134f_term_dumpload(typval_T *argvars, typval_T *rettv)
5135{
5136 term_load_dump(argvars, rettv, FALSE);
5137}
5138
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005139/*
5140 * "term_getaltscreen(buf)" function
5141 */
5142 void
5143f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5144{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005145 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005146
5147 if (buf == NULL)
5148 return;
5149 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5150}
5151
5152/*
5153 * "term_getattr(attr, name)" function
5154 */
5155 void
5156f_term_getattr(typval_T *argvars, typval_T *rettv)
5157{
5158 int attr;
5159 size_t i;
5160 char_u *name;
5161
5162 static struct {
5163 char *name;
5164 int attr;
5165 } attrs[] = {
5166 {"bold", HL_BOLD},
5167 {"italic", HL_ITALIC},
5168 {"underline", HL_UNDERLINE},
5169 {"strike", HL_STRIKETHROUGH},
5170 {"reverse", HL_INVERSE},
5171 };
5172
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005173 attr = tv_get_number(&argvars[0]);
5174 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005175 if (name == NULL)
5176 return;
5177
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005178 if (attr > HL_ALL)
5179 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005180 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5181 if (STRCMP(name, attrs[i].name) == 0)
5182 {
5183 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5184 break;
5185 }
5186}
5187
5188/*
5189 * "term_getcursor(buf)" function
5190 */
5191 void
5192f_term_getcursor(typval_T *argvars, typval_T *rettv)
5193{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005194 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005195 term_T *term;
5196 list_T *l;
5197 dict_T *d;
5198
5199 if (rettv_list_alloc(rettv) == FAIL)
5200 return;
5201 if (buf == NULL)
5202 return;
5203 term = buf->b_term;
5204
5205 l = rettv->vval.v_list;
5206 list_append_number(l, term->tl_cursor_pos.row + 1);
5207 list_append_number(l, term->tl_cursor_pos.col + 1);
5208
5209 d = dict_alloc();
5210 if (d != NULL)
5211 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005212 dict_add_number(d, "visible", term->tl_cursor_visible);
5213 dict_add_number(d, "blink", blink_state_is_inverted()
5214 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5215 dict_add_number(d, "shape", term->tl_cursor_shape);
5216 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005217 list_append_dict(l, d);
5218 }
5219}
5220
5221/*
5222 * "term_getjob(buf)" function
5223 */
5224 void
5225f_term_getjob(typval_T *argvars, typval_T *rettv)
5226{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005227 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005228
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005229 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005230 {
5231 rettv->v_type = VAR_SPECIAL;
5232 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005233 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005234 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005235
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005236 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005237 rettv->vval.v_job = buf->b_term->tl_job;
5238 if (rettv->vval.v_job != NULL)
5239 ++rettv->vval.v_job->jv_refcount;
5240}
5241
5242 static int
5243get_row_number(typval_T *tv, term_T *term)
5244{
5245 if (tv->v_type == VAR_STRING
5246 && tv->vval.v_string != NULL
5247 && STRCMP(tv->vval.v_string, ".") == 0)
5248 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005249 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005250}
5251
5252/*
5253 * "term_getline(buf, row)" function
5254 */
5255 void
5256f_term_getline(typval_T *argvars, typval_T *rettv)
5257{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005258 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005259 term_T *term;
5260 int row;
5261
5262 rettv->v_type = VAR_STRING;
5263 if (buf == NULL)
5264 return;
5265 term = buf->b_term;
5266 row = get_row_number(&argvars[1], term);
5267
5268 if (term->tl_vterm == NULL)
5269 {
5270 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5271
5272 /* vterm is finished, get the text from the buffer */
5273 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5274 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5275 }
5276 else
5277 {
5278 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5279 VTermRect rect;
5280 int len;
5281 char_u *p;
5282
5283 if (row < 0 || row >= term->tl_rows)
5284 return;
5285 len = term->tl_cols * MB_MAXBYTES + 1;
5286 p = alloc(len);
5287 if (p == NULL)
5288 return;
5289 rettv->vval.v_string = p;
5290
5291 rect.start_col = 0;
5292 rect.end_col = term->tl_cols;
5293 rect.start_row = row;
5294 rect.end_row = row + 1;
5295 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5296 }
5297}
5298
5299/*
5300 * "term_getscrolled(buf)" function
5301 */
5302 void
5303f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5304{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005305 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005306
5307 if (buf == NULL)
5308 return;
5309 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5310}
5311
5312/*
5313 * "term_getsize(buf)" function
5314 */
5315 void
5316f_term_getsize(typval_T *argvars, typval_T *rettv)
5317{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005318 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005319 list_T *l;
5320
5321 if (rettv_list_alloc(rettv) == FAIL)
5322 return;
5323 if (buf == NULL)
5324 return;
5325
5326 l = rettv->vval.v_list;
5327 list_append_number(l, buf->b_term->tl_rows);
5328 list_append_number(l, buf->b_term->tl_cols);
5329}
5330
5331/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005332 * "term_setsize(buf, rows, cols)" function
5333 */
5334 void
5335f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5336{
5337 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5338 term_T *term;
5339 varnumber_T rows, cols;
5340
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005341 if (buf == NULL)
5342 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005343 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005344 return;
5345 }
5346 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005347 return;
5348 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005349 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005350 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005351 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005352 cols = cols <= 0 ? term->tl_cols : cols;
5353 vterm_set_size(term->tl_vterm, rows, cols);
5354 /* handle_resize() will resize the windows */
5355
5356 /* Get and remember the size we ended up with. Update the pty. */
5357 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5358 term_report_winsize(term, term->tl_rows, term->tl_cols);
5359}
5360
5361/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005362 * "term_getstatus(buf)" function
5363 */
5364 void
5365f_term_getstatus(typval_T *argvars, typval_T *rettv)
5366{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005367 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005368 term_T *term;
5369 char_u val[100];
5370
5371 rettv->v_type = VAR_STRING;
5372 if (buf == NULL)
5373 return;
5374 term = buf->b_term;
5375
5376 if (term_job_running(term))
5377 STRCPY(val, "running");
5378 else
5379 STRCPY(val, "finished");
5380 if (term->tl_normal_mode)
5381 STRCAT(val, ",normal");
5382 rettv->vval.v_string = vim_strsave(val);
5383}
5384
5385/*
5386 * "term_gettitle(buf)" function
5387 */
5388 void
5389f_term_gettitle(typval_T *argvars, typval_T *rettv)
5390{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005391 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005392
5393 rettv->v_type = VAR_STRING;
5394 if (buf == NULL)
5395 return;
5396
5397 if (buf->b_term->tl_title != NULL)
5398 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5399}
5400
5401/*
5402 * "term_gettty(buf)" function
5403 */
5404 void
5405f_term_gettty(typval_T *argvars, typval_T *rettv)
5406{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005407 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005408 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005409 int num = 0;
5410
5411 rettv->v_type = VAR_STRING;
5412 if (buf == NULL)
5413 return;
5414 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005415 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005416
5417 switch (num)
5418 {
5419 case 0:
5420 if (buf->b_term->tl_job != NULL)
5421 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005422 break;
5423 case 1:
5424 if (buf->b_term->tl_job != NULL)
5425 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005426 break;
5427 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005428 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005429 return;
5430 }
5431 if (p != NULL)
5432 rettv->vval.v_string = vim_strsave(p);
5433}
5434
5435/*
5436 * "term_list()" function
5437 */
5438 void
5439f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5440{
5441 term_T *tp;
5442 list_T *l;
5443
5444 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5445 return;
5446
5447 l = rettv->vval.v_list;
5448 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5449 if (tp != NULL && tp->tl_buffer != NULL)
5450 if (list_append_number(l,
5451 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5452 return;
5453}
5454
5455/*
5456 * "term_scrape(buf, row)" function
5457 */
5458 void
5459f_term_scrape(typval_T *argvars, typval_T *rettv)
5460{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005461 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005462 VTermScreen *screen = NULL;
5463 VTermPos pos;
5464 list_T *l;
5465 term_T *term;
5466 char_u *p;
5467 sb_line_T *line;
5468
5469 if (rettv_list_alloc(rettv) == FAIL)
5470 return;
5471 if (buf == NULL)
5472 return;
5473 term = buf->b_term;
5474
5475 l = rettv->vval.v_list;
5476 pos.row = get_row_number(&argvars[1], term);
5477
5478 if (term->tl_vterm != NULL)
5479 {
5480 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005481 if (screen == NULL) // can't really happen
5482 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005483 p = NULL;
5484 line = NULL;
5485 }
5486 else
5487 {
5488 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5489
5490 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5491 return;
5492 p = ml_get_buf(buf, lnum + 1, FALSE);
5493 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5494 }
5495
5496 for (pos.col = 0; pos.col < term->tl_cols; )
5497 {
5498 dict_T *dcell;
5499 int width;
5500 VTermScreenCellAttrs attrs;
5501 VTermColor fg, bg;
5502 char_u rgb[8];
5503 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5504 int off = 0;
5505 int i;
5506
5507 if (screen == NULL)
5508 {
5509 cellattr_T *cellattr;
5510 int len;
5511
5512 /* vterm has finished, get the cell from scrollback */
5513 if (pos.col >= line->sb_cols)
5514 break;
5515 cellattr = line->sb_cells + pos.col;
5516 width = cellattr->width;
5517 attrs = cellattr->attrs;
5518 fg = cellattr->fg;
5519 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005520 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005521 mch_memmove(mbs, p, len);
5522 mbs[len] = NUL;
5523 p += len;
5524 }
5525 else
5526 {
5527 VTermScreenCell cell;
5528 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5529 break;
5530 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5531 {
5532 if (cell.chars[i] == 0)
5533 break;
5534 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5535 }
5536 mbs[off] = NUL;
5537 width = cell.width;
5538 attrs = cell.attrs;
5539 fg = cell.fg;
5540 bg = cell.bg;
5541 }
5542 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005543 if (dcell == NULL)
5544 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005545 list_append_dict(l, dcell);
5546
Bram Moolenaare0be1672018-07-08 16:50:37 +02005547 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005548
5549 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5550 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005551 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005552 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5553 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005554 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005555
Bram Moolenaare0be1672018-07-08 16:50:37 +02005556 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5557 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005558
5559 ++pos.col;
5560 if (width == 2)
5561 ++pos.col;
5562 }
5563}
5564
5565/*
5566 * "term_sendkeys(buf, keys)" function
5567 */
5568 void
5569f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5570{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005571 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005572 char_u *msg;
5573 term_T *term;
5574
5575 rettv->v_type = VAR_UNKNOWN;
5576 if (buf == NULL)
5577 return;
5578
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005579 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005580 if (msg == NULL)
5581 return;
5582 term = buf->b_term;
5583 if (term->tl_vterm == NULL)
5584 return;
5585
5586 while (*msg != NUL)
5587 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005588 int c;
5589
5590 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5591 {
5592 c = TO_SPECIAL(msg[1], msg[2]);
5593 msg += 3;
5594 }
5595 else
5596 {
5597 c = PTR2CHAR(msg);
5598 msg += MB_CPTR2LEN(msg);
5599 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005600 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005601 }
5602}
5603
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005604#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5605/*
5606 * "term_getansicolors(buf)" function
5607 */
5608 void
5609f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5610{
5611 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5612 term_T *term;
5613 VTermState *state;
5614 VTermColor color;
5615 char_u hexbuf[10];
5616 int index;
5617 list_T *list;
5618
5619 if (rettv_list_alloc(rettv) == FAIL)
5620 return;
5621
5622 if (buf == NULL)
5623 return;
5624 term = buf->b_term;
5625 if (term->tl_vterm == NULL)
5626 return;
5627
5628 list = rettv->vval.v_list;
5629 state = vterm_obtain_state(term->tl_vterm);
5630 for (index = 0; index < 16; index++)
5631 {
5632 vterm_state_get_palette_color(state, index, &color);
5633 sprintf((char *)hexbuf, "#%02x%02x%02x",
5634 color.red, color.green, color.blue);
5635 if (list_append_string(list, hexbuf, 7) == FAIL)
5636 return;
5637 }
5638}
5639
5640/*
5641 * "term_setansicolors(buf, list)" function
5642 */
5643 void
5644f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5645{
5646 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5647 term_T *term;
5648
5649 if (buf == NULL)
5650 return;
5651 term = buf->b_term;
5652 if (term->tl_vterm == NULL)
5653 return;
5654
5655 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5656 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005657 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005658 return;
5659 }
5660
5661 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005662 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005663}
5664#endif
5665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005666/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005667 * "term_setapi(buf, api)" function
5668 */
5669 void
5670f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5671{
5672 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5673 term_T *term;
5674 char_u *api;
5675
5676 if (buf == NULL)
5677 return;
5678 term = buf->b_term;
5679 vim_free(term->tl_api);
5680 api = tv_get_string_chk(&argvars[1]);
5681 if (api != NULL)
5682 term->tl_api = vim_strsave(api);
5683 else
5684 term->tl_api = NULL;
5685}
5686
5687/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005688 * "term_setrestore(buf, command)" function
5689 */
5690 void
5691f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5692{
5693#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005694 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005695 term_T *term;
5696 char_u *cmd;
5697
5698 if (buf == NULL)
5699 return;
5700 term = buf->b_term;
5701 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005702 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005703 if (cmd != NULL)
5704 term->tl_command = vim_strsave(cmd);
5705 else
5706 term->tl_command = NULL;
5707#endif
5708}
5709
5710/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005711 * "term_setkill(buf, how)" function
5712 */
5713 void
5714f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5715{
5716 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5717 term_T *term;
5718 char_u *how;
5719
5720 if (buf == NULL)
5721 return;
5722 term = buf->b_term;
5723 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005724 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005725 if (how != NULL)
5726 term->tl_kill = vim_strsave(how);
5727 else
5728 term->tl_kill = NULL;
5729}
5730
5731/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005732 * "term_start(command, options)" function
5733 */
5734 void
5735f_term_start(typval_T *argvars, typval_T *rettv)
5736{
5737 jobopt_T opt;
5738 buf_T *buf;
5739
5740 init_job_options(&opt);
5741 if (argvars[1].v_type != VAR_UNKNOWN
5742 && get_job_options(&argvars[1], &opt,
5743 JO_TIMEOUT_ALL + JO_STOPONEXIT
5744 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5745 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5746 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5747 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005748 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005749 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005750 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005751 return;
5752
Bram Moolenaar13568252018-03-16 20:46:58 +01005753 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005754
5755 if (buf != NULL && buf->b_term != NULL)
5756 rettv->vval.v_number = buf->b_fnum;
5757}
5758
5759/*
5760 * "term_wait" function
5761 */
5762 void
5763f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5764{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005765 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005766
5767 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005768 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005769 if (buf->b_term->tl_job == NULL)
5770 {
5771 ch_log(NULL, "term_wait(): no job to wait for");
5772 return;
5773 }
5774 if (buf->b_term->tl_job->jv_channel == NULL)
5775 /* channel is closed, nothing to do */
5776 return;
5777
5778 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005779 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005780 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5781 {
5782 /* The job is dead, keep reading channel I/O until the channel is
5783 * closed. buf->b_term may become NULL if the terminal was closed while
5784 * waiting. */
5785 ch_log(NULL, "term_wait(): waiting for channel to close");
5786 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5787 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005788 term_flush_messages();
5789
Bram Moolenaard45aa552018-05-21 22:50:29 +02005790 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005791 if (!buf_valid(buf))
5792 /* If the terminal is closed when the channel is closed the
5793 * buffer disappears. */
5794 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005795 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005796
5797 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005798 }
5799 else
5800 {
5801 long wait = 10L;
5802
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005803 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005804
5805 /* Wait for some time for any channel I/O. */
5806 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005807 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005808 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005809
5810 /* Flushing messages on channels is hopefully sufficient.
5811 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005812 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005813 }
5814}
5815
5816/*
5817 * Called when a channel has sent all the lines to a terminal.
5818 * Send a CTRL-D to mark the end of the text.
5819 */
5820 void
5821term_send_eof(channel_T *ch)
5822{
5823 term_T *term;
5824
5825 for (term = first_term; term != NULL; term = term->tl_next)
5826 if (term->tl_job == ch->ch_job)
5827 {
5828 if (term->tl_eof_chars != NULL)
5829 {
5830 channel_send(ch, PART_IN, term->tl_eof_chars,
5831 (int)STRLEN(term->tl_eof_chars), NULL);
5832 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5833 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005834# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005835 else
5836 /* Default: CTRL-D */
5837 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5838# endif
5839 }
5840}
5841
Bram Moolenaar113e1072019-01-20 15:30:40 +01005842#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005843 job_T *
5844term_getjob(term_T *term)
5845{
5846 return term != NULL ? term->tl_job : NULL;
5847}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005848#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005849
Bram Moolenaar4f974752019-02-17 17:44:42 +01005850# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005851
5852/**************************************
5853 * 2. MS-Windows implementation.
5854 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005855#ifdef PROTO
5856typedef int COORD;
5857typedef int DWORD;
5858typedef int HANDLE;
5859typedef int *DWORD_PTR;
5860typedef int HPCON;
5861typedef int HRESULT;
5862typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005863typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005864typedef int PSIZE_T;
5865typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005866typedef int BOOL;
5867# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005868#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005869
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005870HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5871HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5872HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005873BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5874BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5875void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005876
5877 static int
5878dyn_conpty_init(int verbose)
5879{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005880 static HMODULE hKerneldll = NULL;
5881 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005882 static struct
5883 {
5884 char *name;
5885 FARPROC *ptr;
5886 } conpty_entry[] =
5887 {
5888 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5889 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5890 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5891 {"InitializeProcThreadAttributeList",
5892 (FARPROC*)&pInitializeProcThreadAttributeList},
5893 {"UpdateProcThreadAttribute",
5894 (FARPROC*)&pUpdateProcThreadAttribute},
5895 {"DeleteProcThreadAttributeList",
5896 (FARPROC*)&pDeleteProcThreadAttributeList},
5897 {NULL, NULL}
5898 };
5899
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005900 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005901 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005902 if (verbose)
5903 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005904 return FAIL;
5905 }
5906
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005907 // No need to initialize twice.
5908 if (hKerneldll)
5909 return OK;
5910
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005911 hKerneldll = vimLoadLib("kernel32.dll");
5912 for (i = 0; conpty_entry[i].name != NULL
5913 && conpty_entry[i].ptr != NULL; ++i)
5914 {
5915 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5916 conpty_entry[i].name)) == NULL)
5917 {
5918 if (verbose)
5919 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005920 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005921 return FAIL;
5922 }
5923 }
5924
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005925 return OK;
5926}
5927
5928 static int
5929conpty_term_and_job_init(
5930 term_T *term,
5931 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005932 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005933 jobopt_T *opt,
5934 jobopt_T *orig_opt)
5935{
5936 WCHAR *cmd_wchar = NULL;
5937 WCHAR *cmd_wchar_copy = NULL;
5938 WCHAR *cwd_wchar = NULL;
5939 WCHAR *env_wchar = NULL;
5940 channel_T *channel = NULL;
5941 job_T *job = NULL;
5942 HANDLE jo = NULL;
5943 garray_T ga_cmd, ga_env;
5944 char_u *cmd = NULL;
5945 HRESULT hr;
5946 COORD consize;
5947 SIZE_T breq;
5948 PROCESS_INFORMATION proc_info;
5949 HANDLE i_theirs = NULL;
5950 HANDLE o_theirs = NULL;
5951 HANDLE i_ours = NULL;
5952 HANDLE o_ours = NULL;
5953
5954 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5955 ga_init2(&ga_env, (int)sizeof(char*), 20);
5956
5957 if (argvar->v_type == VAR_STRING)
5958 {
5959 cmd = argvar->vval.v_string;
5960 }
5961 else if (argvar->v_type == VAR_LIST)
5962 {
5963 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5964 goto failed;
5965 cmd = ga_cmd.ga_data;
5966 }
5967 if (cmd == NULL || *cmd == NUL)
5968 {
5969 emsg(_(e_invarg));
5970 goto failed;
5971 }
5972
5973 term->tl_arg0_cmd = vim_strsave(cmd);
5974
5975 cmd_wchar = enc_to_utf16(cmd, NULL);
5976
5977 if (cmd_wchar != NULL)
5978 {
5979 /* Request by CreateProcessW */
5980 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005981 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005982 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5983 }
5984
5985 ga_clear(&ga_cmd);
5986 if (cmd_wchar == NULL)
5987 goto failed;
5988 if (opt->jo_cwd != NULL)
5989 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5990
5991 win32_build_env(opt->jo_env, &ga_env, TRUE);
5992 env_wchar = ga_env.ga_data;
5993
5994 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5995 goto failed;
5996 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5997 goto failed;
5998
5999 consize.X = term->tl_cols;
6000 consize.Y = term->tl_rows;
6001 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6002 &term->tl_conpty);
6003 if (FAILED(hr))
6004 goto failed;
6005
6006 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6007
6008 /* Set up pipe inheritance safely: Vista or later. */
6009 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006010 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006011 if (!term->tl_siex.lpAttributeList)
6012 goto failed;
6013 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6014 0, &breq))
6015 goto failed;
6016 if (!pUpdateProcThreadAttribute(
6017 term->tl_siex.lpAttributeList, 0,
6018 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6019 sizeof(HPCON), NULL, NULL))
6020 goto failed;
6021
6022 channel = add_channel();
6023 if (channel == NULL)
6024 goto failed;
6025
6026 job = job_alloc();
6027 if (job == NULL)
6028 goto failed;
6029 if (argvar->v_type == VAR_STRING)
6030 {
6031 int argc;
6032
6033 build_argv_from_string(cmd, &job->jv_argv, &argc);
6034 }
6035 else
6036 {
6037 int argc;
6038
6039 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6040 }
6041
6042 if (opt->jo_set & JO_IN_BUF)
6043 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6044
6045 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6046 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6047 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6048 | CREATE_DEFAULT_ERROR_MODE,
6049 env_wchar, cwd_wchar,
6050 &term->tl_siex.StartupInfo, &proc_info))
6051 goto failed;
6052
6053 CloseHandle(i_theirs);
6054 CloseHandle(o_theirs);
6055
6056 channel_set_pipes(channel,
6057 (sock_T)i_ours,
6058 (sock_T)o_ours,
6059 (sock_T)o_ours);
6060
6061 /* Write lines with CR instead of NL. */
6062 channel->ch_write_text_mode = TRUE;
6063
6064 /* Use to explicitly delete anonymous pipe handle. */
6065 channel->ch_anonymous_pipe = TRUE;
6066
6067 jo = CreateJobObject(NULL, NULL);
6068 if (jo == NULL)
6069 goto failed;
6070
6071 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6072 {
6073 /* Failed, switch the way to terminate process with TerminateProcess. */
6074 CloseHandle(jo);
6075 jo = NULL;
6076 }
6077
6078 ResumeThread(proc_info.hThread);
6079 CloseHandle(proc_info.hThread);
6080
6081 vim_free(cmd_wchar);
6082 vim_free(cmd_wchar_copy);
6083 vim_free(cwd_wchar);
6084 vim_free(env_wchar);
6085
6086 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6087 goto failed;
6088
6089#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6090 if (opt->jo_set2 & JO2_ANSI_COLORS)
6091 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6092 else
6093 init_vterm_ansi_colors(term->tl_vterm);
6094#endif
6095
6096 channel_set_job(channel, job, opt);
6097 job_set_options(job, opt);
6098
6099 job->jv_channel = channel;
6100 job->jv_proc_info = proc_info;
6101 job->jv_job_object = jo;
6102 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006103 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006104 ++job->jv_refcount;
6105 term->tl_job = job;
6106
6107 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6108 * open the file here and handle it in. opt->jo_io was changed in
6109 * setup_job_options(), use the original flags here. */
6110 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6111 {
6112 char_u *fname = opt->jo_io_name[PART_OUT];
6113
6114 ch_log(channel, "Opening output file %s", fname);
6115 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6116 if (term->tl_out_fd == NULL)
6117 semsg(_(e_notopen), fname);
6118 }
6119
6120 return OK;
6121
6122failed:
6123 ga_clear(&ga_cmd);
6124 ga_clear(&ga_env);
6125 vim_free(cmd_wchar);
6126 vim_free(cmd_wchar_copy);
6127 vim_free(cwd_wchar);
6128 if (channel != NULL)
6129 channel_clear(channel);
6130 if (job != NULL)
6131 {
6132 job->jv_channel = NULL;
6133 job_cleanup(job);
6134 }
6135 term->tl_job = NULL;
6136 if (jo != NULL)
6137 CloseHandle(jo);
6138
6139 if (term->tl_siex.lpAttributeList != NULL)
6140 {
6141 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6142 vim_free(term->tl_siex.lpAttributeList);
6143 }
6144 term->tl_siex.lpAttributeList = NULL;
6145 if (o_theirs != NULL)
6146 CloseHandle(o_theirs);
6147 if (o_ours != NULL)
6148 CloseHandle(o_ours);
6149 if (i_ours != NULL)
6150 CloseHandle(i_ours);
6151 if (i_theirs != NULL)
6152 CloseHandle(i_theirs);
6153 if (term->tl_conpty != NULL)
6154 pClosePseudoConsole(term->tl_conpty);
6155 term->tl_conpty = NULL;
6156 return FAIL;
6157}
6158
6159 static void
6160conpty_term_report_winsize(term_T *term, int rows, int cols)
6161{
6162 COORD consize;
6163
6164 consize.X = cols;
6165 consize.Y = rows;
6166 pResizePseudoConsole(term->tl_conpty, consize);
6167}
6168
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006169 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006170term_free_conpty(term_T *term)
6171{
6172 if (term->tl_siex.lpAttributeList != NULL)
6173 {
6174 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6175 vim_free(term->tl_siex.lpAttributeList);
6176 }
6177 term->tl_siex.lpAttributeList = NULL;
6178 if (term->tl_conpty != NULL)
6179 pClosePseudoConsole(term->tl_conpty);
6180 term->tl_conpty = NULL;
6181}
6182
6183 int
6184use_conpty(void)
6185{
6186 return has_conpty;
6187}
6188
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006189# ifndef PROTO
6190
6191#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6192#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006193#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006194
6195void* (*winpty_config_new)(UINT64, void*);
6196void* (*winpty_open)(void*, void*);
6197void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6198BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6199void (*winpty_config_set_mouse_mode)(void*, int);
6200void (*winpty_config_set_initial_size)(void*, int, int);
6201LPCWSTR (*winpty_conin_name)(void*);
6202LPCWSTR (*winpty_conout_name)(void*);
6203LPCWSTR (*winpty_conerr_name)(void*);
6204void (*winpty_free)(void*);
6205void (*winpty_config_free)(void*);
6206void (*winpty_spawn_config_free)(void*);
6207void (*winpty_error_free)(void*);
6208LPCWSTR (*winpty_error_msg)(void*);
6209BOOL (*winpty_set_size)(void*, int, int, void*);
6210HANDLE (*winpty_agent_process)(void*);
6211
6212#define WINPTY_DLL "winpty.dll"
6213
6214static HINSTANCE hWinPtyDLL = NULL;
6215# endif
6216
6217 static int
6218dyn_winpty_init(int verbose)
6219{
6220 int i;
6221 static struct
6222 {
6223 char *name;
6224 FARPROC *ptr;
6225 } winpty_entry[] =
6226 {
6227 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6228 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6229 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6230 {"winpty_config_set_mouse_mode",
6231 (FARPROC*)&winpty_config_set_mouse_mode},
6232 {"winpty_config_set_initial_size",
6233 (FARPROC*)&winpty_config_set_initial_size},
6234 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6235 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6236 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6237 {"winpty_free", (FARPROC*)&winpty_free},
6238 {"winpty_open", (FARPROC*)&winpty_open},
6239 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6240 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6241 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6242 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6243 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6244 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6245 {NULL, NULL}
6246 };
6247
6248 /* No need to initialize twice. */
6249 if (hWinPtyDLL)
6250 return OK;
6251 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6252 * winpty.dll. */
6253 if (*p_winptydll != NUL)
6254 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6255 if (!hWinPtyDLL)
6256 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6257 if (!hWinPtyDLL)
6258 {
6259 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006260 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006261 : (char_u *)WINPTY_DLL);
6262 return FAIL;
6263 }
6264 for (i = 0; winpty_entry[i].name != NULL
6265 && winpty_entry[i].ptr != NULL; ++i)
6266 {
6267 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6268 winpty_entry[i].name)) == NULL)
6269 {
6270 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006271 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006272 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006273 return FAIL;
6274 }
6275 }
6276
6277 return OK;
6278}
6279
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006280 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006281winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006282 term_T *term,
6283 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006284 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006285 jobopt_T *opt,
6286 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006287{
6288 WCHAR *cmd_wchar = NULL;
6289 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006290 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006291 channel_T *channel = NULL;
6292 job_T *job = NULL;
6293 DWORD error;
6294 HANDLE jo = NULL;
6295 HANDLE child_process_handle;
6296 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006297 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006298 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006299 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006300 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006301
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006302 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6303 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006304
6305 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006306 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006307 cmd = argvar->vval.v_string;
6308 }
6309 else if (argvar->v_type == VAR_LIST)
6310 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006311 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006312 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006313 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006314 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006315 if (cmd == NULL || *cmd == NUL)
6316 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006317 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006318 goto failed;
6319 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006320
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006321 term->tl_arg0_cmd = vim_strsave(cmd);
6322
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006323 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006324 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006325 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006326 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006327 if (opt->jo_cwd != NULL)
6328 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006329
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006330 win32_build_env(opt->jo_env, &ga_env, TRUE);
6331 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006332
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006333 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6334 if (term->tl_winpty_config == NULL)
6335 goto failed;
6336
6337 winpty_config_set_mouse_mode(term->tl_winpty_config,
6338 WINPTY_MOUSE_MODE_FORCE);
6339 winpty_config_set_initial_size(term->tl_winpty_config,
6340 term->tl_cols, term->tl_rows);
6341 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6342 if (term->tl_winpty == NULL)
6343 goto failed;
6344
6345 spawn_config = winpty_spawn_config_new(
6346 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6347 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6348 NULL,
6349 cmd_wchar,
6350 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006351 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006352 &winpty_err);
6353 if (spawn_config == NULL)
6354 goto failed;
6355
6356 channel = add_channel();
6357 if (channel == NULL)
6358 goto failed;
6359
6360 job = job_alloc();
6361 if (job == NULL)
6362 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006363 if (argvar->v_type == VAR_STRING)
6364 {
6365 int argc;
6366
6367 build_argv_from_string(cmd, &job->jv_argv, &argc);
6368 }
6369 else
6370 {
6371 int argc;
6372
6373 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6374 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006375
6376 if (opt->jo_set & JO_IN_BUF)
6377 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6378
6379 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6380 &child_thread_handle, &error, &winpty_err))
6381 goto failed;
6382
6383 channel_set_pipes(channel,
6384 (sock_T)CreateFileW(
6385 winpty_conin_name(term->tl_winpty),
6386 GENERIC_WRITE, 0, NULL,
6387 OPEN_EXISTING, 0, NULL),
6388 (sock_T)CreateFileW(
6389 winpty_conout_name(term->tl_winpty),
6390 GENERIC_READ, 0, NULL,
6391 OPEN_EXISTING, 0, NULL),
6392 (sock_T)CreateFileW(
6393 winpty_conerr_name(term->tl_winpty),
6394 GENERIC_READ, 0, NULL,
6395 OPEN_EXISTING, 0, NULL));
6396
6397 /* Write lines with CR instead of NL. */
6398 channel->ch_write_text_mode = TRUE;
6399
6400 jo = CreateJobObject(NULL, NULL);
6401 if (jo == NULL)
6402 goto failed;
6403
6404 if (!AssignProcessToJobObject(jo, child_process_handle))
6405 {
6406 /* Failed, switch the way to terminate process with TerminateProcess. */
6407 CloseHandle(jo);
6408 jo = NULL;
6409 }
6410
6411 winpty_spawn_config_free(spawn_config);
6412 vim_free(cmd_wchar);
6413 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006414 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006415
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006416 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6417 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006418
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006419#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6420 if (opt->jo_set2 & JO2_ANSI_COLORS)
6421 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6422 else
6423 init_vterm_ansi_colors(term->tl_vterm);
6424#endif
6425
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006426 channel_set_job(channel, job, opt);
6427 job_set_options(job, opt);
6428
6429 job->jv_channel = channel;
6430 job->jv_proc_info.hProcess = child_process_handle;
6431 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6432 job->jv_job_object = jo;
6433 job->jv_status = JOB_STARTED;
6434 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006435 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006436 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006437 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006438 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006439 ++job->jv_refcount;
6440 term->tl_job = job;
6441
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006442 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6443 * open the file here and handle it in. opt->jo_io was changed in
6444 * setup_job_options(), use the original flags here. */
6445 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6446 {
6447 char_u *fname = opt->jo_io_name[PART_OUT];
6448
6449 ch_log(channel, "Opening output file %s", fname);
6450 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6451 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006452 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006453 }
6454
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006455 return OK;
6456
6457failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006458 ga_clear(&ga_cmd);
6459 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006460 vim_free(cmd_wchar);
6461 vim_free(cwd_wchar);
6462 if (spawn_config != NULL)
6463 winpty_spawn_config_free(spawn_config);
6464 if (channel != NULL)
6465 channel_clear(channel);
6466 if (job != NULL)
6467 {
6468 job->jv_channel = NULL;
6469 job_cleanup(job);
6470 }
6471 term->tl_job = NULL;
6472 if (jo != NULL)
6473 CloseHandle(jo);
6474 if (term->tl_winpty != NULL)
6475 winpty_free(term->tl_winpty);
6476 term->tl_winpty = NULL;
6477 if (term->tl_winpty_config != NULL)
6478 winpty_config_free(term->tl_winpty_config);
6479 term->tl_winpty_config = NULL;
6480 if (winpty_err != NULL)
6481 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006482 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006483 (short_u *)winpty_error_msg(winpty_err), NULL);
6484
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006485 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006486 winpty_error_free(winpty_err);
6487 }
6488 return FAIL;
6489}
6490
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006491/*
6492 * Create a new terminal of "rows" by "cols" cells.
6493 * Store a reference in "term".
6494 * Return OK or FAIL.
6495 */
6496 static int
6497term_and_job_init(
6498 term_T *term,
6499 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006500 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006501 jobopt_T *opt,
6502 jobopt_T *orig_opt)
6503{
6504 int use_winpty = FALSE;
6505 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006506 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006507
6508 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6509 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6510
6511 if (!has_winpty && !has_conpty)
6512 // If neither is available give the errors for winpty, since when
6513 // conpty is not available it can't be installed either.
6514 return dyn_winpty_init(TRUE);
6515
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006516 if (opt->jo_tty_type != NUL)
6517 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006518
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006519 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006520 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006521 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006522 use_conpty = TRUE;
6523 else if (has_winpty)
6524 use_winpty = TRUE;
6525 // else: error
6526 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006527 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006528 {
6529 if (has_winpty)
6530 use_winpty = TRUE;
6531 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006532 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006533 {
6534 if (has_conpty)
6535 use_conpty = TRUE;
6536 else
6537 return dyn_conpty_init(TRUE);
6538 }
6539
6540 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006541 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006542
6543 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006544 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006545
6546 // error
6547 return dyn_winpty_init(TRUE);
6548}
6549
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006550 static int
6551create_pty_only(term_T *term, jobopt_T *options)
6552{
6553 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6554 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6555 char in_name[80], out_name[80];
6556 channel_T *channel = NULL;
6557
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006558 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6559 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006560
6561 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6562 GetCurrentProcessId(),
6563 curbuf->b_fnum);
6564 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6565 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6566 PIPE_UNLIMITED_INSTANCES,
6567 0, 0, NMPWAIT_NOWAIT, NULL);
6568 if (hPipeIn == INVALID_HANDLE_VALUE)
6569 goto failed;
6570
6571 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6572 GetCurrentProcessId(),
6573 curbuf->b_fnum);
6574 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6575 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6576 PIPE_UNLIMITED_INSTANCES,
6577 0, 0, 0, NULL);
6578 if (hPipeOut == INVALID_HANDLE_VALUE)
6579 goto failed;
6580
6581 ConnectNamedPipe(hPipeIn, NULL);
6582 ConnectNamedPipe(hPipeOut, NULL);
6583
6584 term->tl_job = job_alloc();
6585 if (term->tl_job == NULL)
6586 goto failed;
6587 ++term->tl_job->jv_refcount;
6588
6589 /* behave like the job is already finished */
6590 term->tl_job->jv_status = JOB_FINISHED;
6591
6592 channel = add_channel();
6593 if (channel == NULL)
6594 goto failed;
6595 term->tl_job->jv_channel = channel;
6596 channel->ch_keep_open = TRUE;
6597 channel->ch_named_pipe = TRUE;
6598
6599 channel_set_pipes(channel,
6600 (sock_T)hPipeIn,
6601 (sock_T)hPipeOut,
6602 (sock_T)hPipeOut);
6603 channel_set_job(channel, term->tl_job, options);
6604 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6605 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6606
6607 return OK;
6608
6609failed:
6610 if (hPipeIn != NULL)
6611 CloseHandle(hPipeIn);
6612 if (hPipeOut != NULL)
6613 CloseHandle(hPipeOut);
6614 return FAIL;
6615}
6616
6617/*
6618 * Free the terminal emulator part of "term".
6619 */
6620 static void
6621term_free_vterm(term_T *term)
6622{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006623 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006624 if (term->tl_winpty != NULL)
6625 winpty_free(term->tl_winpty);
6626 term->tl_winpty = NULL;
6627 if (term->tl_winpty_config != NULL)
6628 winpty_config_free(term->tl_winpty_config);
6629 term->tl_winpty_config = NULL;
6630 if (term->tl_vterm != NULL)
6631 vterm_free(term->tl_vterm);
6632 term->tl_vterm = NULL;
6633}
6634
6635/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006636 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006637 */
6638 static void
6639term_report_winsize(term_T *term, int rows, int cols)
6640{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006641 if (term->tl_conpty)
6642 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006643 if (term->tl_winpty)
6644 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6645}
6646
6647 int
6648terminal_enabled(void)
6649{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006650 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006651}
6652
6653# else
6654
6655/**************************************
6656 * 3. Unix-like implementation.
6657 */
6658
6659/*
6660 * Create a new terminal of "rows" by "cols" cells.
6661 * Start job for "cmd".
6662 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006663 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006664 * Return OK or FAIL.
6665 */
6666 static int
6667term_and_job_init(
6668 term_T *term,
6669 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006670 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006671 jobopt_T *opt,
6672 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006673{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006674 term->tl_arg0_cmd = NULL;
6675
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006676 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6677 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006678
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006679#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6680 if (opt->jo_set2 & JO2_ANSI_COLORS)
6681 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6682 else
6683 init_vterm_ansi_colors(term->tl_vterm);
6684#endif
6685
Bram Moolenaar13568252018-03-16 20:46:58 +01006686 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006687 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006688 if (term->tl_job != NULL)
6689 ++term->tl_job->jv_refcount;
6690
6691 return term->tl_job != NULL
6692 && term->tl_job->jv_channel != NULL
6693 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6694}
6695
6696 static int
6697create_pty_only(term_T *term, jobopt_T *opt)
6698{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006699 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6700 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006701
6702 term->tl_job = job_alloc();
6703 if (term->tl_job == NULL)
6704 return FAIL;
6705 ++term->tl_job->jv_refcount;
6706
6707 /* behave like the job is already finished */
6708 term->tl_job->jv_status = JOB_FINISHED;
6709
6710 return mch_create_pty_channel(term->tl_job, opt);
6711}
6712
6713/*
6714 * Free the terminal emulator part of "term".
6715 */
6716 static void
6717term_free_vterm(term_T *term)
6718{
6719 if (term->tl_vterm != NULL)
6720 vterm_free(term->tl_vterm);
6721 term->tl_vterm = NULL;
6722}
6723
6724/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006725 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006726 */
6727 static void
6728term_report_winsize(term_T *term, int rows, int cols)
6729{
6730 /* Use an ioctl() to report the new window size to the job. */
6731 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6732 {
6733 int fd = -1;
6734 int part;
6735
6736 for (part = PART_OUT; part < PART_COUNT; ++part)
6737 {
6738 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006739 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006740 break;
6741 }
6742 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6743 mch_signal_job(term->tl_job, (char_u *)"winch");
6744 }
6745}
6746
6747# endif
6748
6749#endif /* FEAT_TERMINAL */