blob: 10343fe20ec6f21f8ba177155ac7b04ab233635f [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;
706 char_u *cmd;
707 char_u *tofree = NULL;
708
709 init_job_options(&opt);
710
711 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100712 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200713 {
714 char_u *p, *ep;
715
716 cmd += 2;
717 p = skiptowhite(cmd);
718 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200719 if (ep != NULL)
720 {
721 if (ep < p)
722 p = ep;
723 else
724 ep = NULL;
725 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200726
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200727# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
728 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
729 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200730 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200731 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100732 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200733 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200734 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200735 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200736 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200737 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200738 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200739 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100740 opt.jo_term_norestore = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200741 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100742 {
743 opt.jo_set2 |= JO2_TERM_KILL;
744 opt.jo_term_kill = ep + 1;
745 p = skiptowhite(cmd);
746 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200747 else if (OPTARG_HAS("api"))
748 {
749 opt.jo_set2 |= JO2_TERM_API;
750 if (ep != NULL)
751 {
752 opt.jo_term_api = ep + 1;
753 p = skiptowhite(cmd);
754 }
755 else
756 opt.jo_term_api = NULL;
757 }
758 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200759 {
760 opt.jo_set2 |= JO2_TERM_ROWS;
761 opt.jo_term_rows = atoi((char *)ep + 1);
762 p = skiptowhite(cmd);
763 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200764 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200765 {
766 opt.jo_set2 |= JO2_TERM_COLS;
767 opt.jo_term_cols = atoi((char *)ep + 1);
768 p = skiptowhite(cmd);
769 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200770 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200771 {
772 char_u *buf = NULL;
773 char_u *keys;
774
775 p = skiptowhite(cmd);
776 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200777 keys = replace_termcodes(ep + 1, &buf,
778 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200779 opt.jo_set2 |= JO2_EOF_CHARS;
780 opt.jo_eof_chars = vim_strsave(keys);
781 vim_free(buf);
782 *p = ' ';
783 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100784#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100785 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
786 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100787 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100788 int tty_type = NUL;
789
790 p = skiptowhite(cmd);
791 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
792 tty_type = 'w';
793 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
794 tty_type = 'c';
795 else
796 {
797 semsg(e_invargval, "type");
798 goto theend;
799 }
800 opt.jo_set2 |= JO2_TTY_TYPE;
801 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100802 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100803#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 else
805 {
806 if (*p)
807 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100808 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100809 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200810 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200811# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200812 cmd = skipwhite(p);
813 }
814 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100815 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816 /* Make a copy of 'shell', an autocommand may change the option. */
817 tofree = cmd = vim_strsave(p_sh);
818
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100819 /* default to close when the shell exits */
820 if (opt.jo_term_finish == NUL)
821 opt.jo_term_finish = 'c';
822 }
823
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 if (eap->addr_count > 0)
825 {
826 /* Write lines from current buffer to the job. */
827 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
828 opt.jo_io[PART_IN] = JIO_BUFFER;
829 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
830 opt.jo_in_top = eap->line1;
831 opt.jo_in_bot = eap->line2;
832 }
833
834 argvar[0].v_type = VAR_STRING;
835 argvar[0].vval.v_string = cmd;
836 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100837 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200838 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100839
840theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 vim_free(opt.jo_eof_chars);
842}
843
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100844#if defined(FEAT_SESSION) || defined(PROTO)
845/*
846 * Write a :terminal command to the session file to restore the terminal in
847 * window "wp".
848 * Return FAIL if writing fails.
849 */
850 int
851term_write_session(FILE *fd, win_T *wp)
852{
853 term_T *term = wp->w_buffer->b_term;
854
855 /* Create the terminal and run the command. This is not without
856 * risk, but let's assume the user only creates a session when this
857 * will be OK. */
858 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
859 term->tl_cols, term->tl_rows) < 0)
860 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100861#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100862 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
863 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100864#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100865 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
866 return FAIL;
867
868 return put_eol(fd);
869}
870
871/*
872 * Return TRUE if "buf" has a terminal that should be restored.
873 */
874 int
875term_should_restore(buf_T *buf)
876{
877 term_T *term = buf->b_term;
878
879 return term != NULL && (term->tl_command == NULL
880 || STRCMP(term->tl_command, "NONE") != 0);
881}
882#endif
883
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884/*
885 * Free the scrollback buffer for "term".
886 */
887 static void
888free_scrollback(term_T *term)
889{
890 int i;
891
892 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
893 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
894 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100895 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
896 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
897 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898}
899
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100900
901// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200902static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100903
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200904/*
905 * Free a terminal and everything it refers to.
906 * Kills the job if there is one.
907 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100908 * The actual terminal structure is freed later in free_unused_terminals(),
909 * because callbacks may wipe out a buffer while the terminal is still
910 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200911 */
912 void
913free_terminal(buf_T *buf)
914{
915 term_T *term = buf->b_term;
916 term_T *tp;
917
918 if (term == NULL)
919 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100920
921 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200922 if (first_term == term)
923 first_term = term->tl_next;
924 else
925 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
926 if (tp->tl_next == term)
927 {
928 tp->tl_next = term->tl_next;
929 break;
930 }
931
932 if (term->tl_job != NULL)
933 {
934 if (term->tl_job->jv_status != JOB_ENDED
935 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100936 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200937 job_stop(term->tl_job, NULL, "kill");
938 job_unref(term->tl_job);
939 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100940 term->tl_next = terminals_to_free;
941 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200942
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200943 buf->b_term = NULL;
944 if (in_terminal_loop == term)
945 in_terminal_loop = NULL;
946}
947
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100948 void
949free_unused_terminals()
950{
951 while (terminals_to_free != NULL)
952 {
953 term_T *term = terminals_to_free;
954
955 terminals_to_free = term->tl_next;
956
957 free_scrollback(term);
958
959 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200960 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100961 vim_free(term->tl_title);
962#ifdef FEAT_SESSION
963 vim_free(term->tl_command);
964#endif
965 vim_free(term->tl_kill);
966 vim_free(term->tl_status_text);
967 vim_free(term->tl_opencmd);
968 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100969 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100970#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100971 if (term->tl_out_fd != NULL)
972 fclose(term->tl_out_fd);
973#endif
974 vim_free(term->tl_cursor_color);
975 vim_free(term);
976 }
977}
978
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200979/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100980 * Get the part that is connected to the tty. Normally this is PART_IN, but
981 * when writing buffer lines to the job it can be another. This makes it
982 * possible to do "1,5term vim -".
983 */
984 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200985get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100986{
987#ifdef UNIX
988 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
989 int i;
990
991 for (i = 0; i < 3; ++i)
992 {
993 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
994
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +0100995 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100996 return parts[i];
997 }
998#endif
999 return PART_IN;
1000}
1001
1002/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001003 * Write job output "msg[len]" to the vterm.
1004 */
1005 static void
1006term_write_job_output(term_T *term, char_u *msg, size_t len)
1007{
1008 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001009 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001010
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001011 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001012
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001013 /* flush vterm buffer when vterm responded to control sequence */
1014 if (prevlen != vterm_output_get_buffer_current(vterm))
1015 {
1016 char buf[KEY_BUF_LEN];
1017 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1018
1019 if (curlen > 0)
1020 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1021 (char_u *)buf, (int)curlen, NULL);
1022 }
1023
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001024 /* this invokes the damage callbacks */
1025 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1026}
1027
1028 static void
1029update_cursor(term_T *term, int redraw)
1030{
1031 if (term->tl_normal_mode)
1032 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001033#ifdef FEAT_GUI
1034 if (term->tl_system)
1035 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1036 term->tl_cursor_pos.col);
1037 else
1038#endif
1039 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001040 if (redraw)
1041 {
1042 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1043 cursor_on();
1044 out_flush();
1045#ifdef FEAT_GUI
1046 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001047 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001048 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001049 gui_mch_flush();
1050 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001051#endif
1052 }
1053}
1054
1055/*
1056 * Invoked when "msg" output from a job was received. Write it to the terminal
1057 * of "buffer".
1058 */
1059 void
1060write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1061{
1062 size_t len = STRLEN(msg);
1063 term_T *term = buffer->b_term;
1064
Bram Moolenaar4f974752019-02-17 17:44:42 +01001065#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001066 /* Win32: Cannot redirect output of the job, intercept it here and write to
1067 * the file. */
1068 if (term->tl_out_fd != NULL)
1069 {
1070 ch_log(channel, "Writing %d bytes to output file", (int)len);
1071 fwrite(msg, len, 1, term->tl_out_fd);
1072 return;
1073 }
1074#endif
1075
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001076 if (term->tl_vterm == NULL)
1077 {
1078 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1079 return;
1080 }
1081 ch_log(channel, "writing %d bytes to terminal", (int)len);
1082 term_write_job_output(term, msg, len);
1083
Bram Moolenaar13568252018-03-16 20:46:58 +01001084#ifdef FEAT_GUI
1085 if (term->tl_system)
1086 {
1087 /* show system output, scrolling up the screen as needed */
1088 update_system_term(term);
1089 update_cursor(term, TRUE);
1090 }
1091 else
1092#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001093 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
1094 * contents, thus no screen update is needed. */
1095 if (!term->tl_normal_mode)
1096 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001097 // Don't use update_screen() when editing the command line, it gets
1098 // cleared.
1099 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001100 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001101 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001102 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001103 update_screen(VALID_NO_UPDATE);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001104 /* update_screen() can be slow, check the terminal wasn't closed
1105 * already */
1106 if (buffer == curbuf && curbuf->b_term != NULL)
1107 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001108 }
1109 else
1110 redraw_after_callback(TRUE);
1111 }
1112}
1113
1114/*
1115 * Send a mouse position and click to the vterm
1116 */
1117 static int
1118term_send_mouse(VTerm *vterm, int button, int pressed)
1119{
1120 VTermModifier mod = VTERM_MOD_NONE;
1121
1122 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +02001123 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001124 if (button != 0)
1125 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001126 return TRUE;
1127}
1128
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001129static int enter_mouse_col = -1;
1130static int enter_mouse_row = -1;
1131
1132/*
1133 * Handle a mouse click, drag or release.
1134 * Return TRUE when a mouse event is sent to the terminal.
1135 */
1136 static int
1137term_mouse_click(VTerm *vterm, int key)
1138{
1139#if defined(FEAT_CLIPBOARD)
1140 /* For modeless selection mouse drag and release events are ignored, unless
1141 * they are preceded with a mouse down event */
1142 static int ignore_drag_release = TRUE;
1143 VTermMouseState mouse_state;
1144
1145 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1146 if (mouse_state.flags == 0)
1147 {
1148 /* Terminal is not using the mouse, use modeless selection. */
1149 switch (key)
1150 {
1151 case K_LEFTDRAG:
1152 case K_LEFTRELEASE:
1153 case K_RIGHTDRAG:
1154 case K_RIGHTRELEASE:
1155 /* Ignore drag and release events when the button-down wasn't
1156 * seen before. */
1157 if (ignore_drag_release)
1158 {
1159 int save_mouse_col, save_mouse_row;
1160
1161 if (enter_mouse_col < 0)
1162 break;
1163
1164 /* mouse click in the window gave us focus, handle that
1165 * click now */
1166 save_mouse_col = mouse_col;
1167 save_mouse_row = mouse_row;
1168 mouse_col = enter_mouse_col;
1169 mouse_row = enter_mouse_row;
1170 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1171 mouse_col = save_mouse_col;
1172 mouse_row = save_mouse_row;
1173 }
1174 /* FALLTHROUGH */
1175 case K_LEFTMOUSE:
1176 case K_RIGHTMOUSE:
1177 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1178 ignore_drag_release = TRUE;
1179 else
1180 ignore_drag_release = FALSE;
1181 /* Should we call mouse_has() here? */
1182 if (clip_star.available)
1183 {
1184 int button, is_click, is_drag;
1185
1186 button = get_mouse_button(KEY2TERMCAP1(key),
1187 &is_click, &is_drag);
1188 if (mouse_model_popup() && button == MOUSE_LEFT
1189 && (mod_mask & MOD_MASK_SHIFT))
1190 {
1191 /* Translate shift-left to right button. */
1192 button = MOUSE_RIGHT;
1193 mod_mask &= ~MOD_MASK_SHIFT;
1194 }
1195 clip_modeless(button, is_click, is_drag);
1196 }
1197 break;
1198
1199 case K_MIDDLEMOUSE:
1200 if (clip_star.available)
1201 insert_reg('*', TRUE);
1202 break;
1203 }
1204 enter_mouse_col = -1;
1205 return FALSE;
1206 }
1207#endif
1208 enter_mouse_col = -1;
1209
1210 switch (key)
1211 {
1212 case K_LEFTMOUSE:
1213 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1214 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1215 case K_LEFTRELEASE:
1216 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1217 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1218 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1219 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1220 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1221 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1222 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1223 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1224 }
1225 return TRUE;
1226}
1227
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001228/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001229 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1230 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001231 * Return the number of bytes in "buf".
1232 */
1233 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001234term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001235{
1236 VTerm *vterm = term->tl_vterm;
1237 VTermKey key = VTERM_KEY_NONE;
1238 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001239 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001240
1241 switch (c)
1242 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001243 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1244
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001245 /* don't use VTERM_KEY_BACKSPACE, it always
1246 * becomes 0x7f DEL */
1247 case K_BS: c = term_backspace_char; break;
1248
1249 case ESC: key = VTERM_KEY_ESCAPE; break;
1250 case K_DEL: key = VTERM_KEY_DEL; break;
1251 case K_DOWN: key = VTERM_KEY_DOWN; break;
1252 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1253 key = VTERM_KEY_DOWN; break;
1254 case K_END: key = VTERM_KEY_END; break;
1255 case K_S_END: mod = VTERM_MOD_SHIFT;
1256 key = VTERM_KEY_END; break;
1257 case K_C_END: mod = VTERM_MOD_CTRL;
1258 key = VTERM_KEY_END; break;
1259 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1260 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1261 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1262 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1263 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1264 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1265 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1266 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1267 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1268 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1269 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1270 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1271 case K_HOME: key = VTERM_KEY_HOME; break;
1272 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1273 key = VTERM_KEY_HOME; break;
1274 case K_C_HOME: mod = VTERM_MOD_CTRL;
1275 key = VTERM_KEY_HOME; break;
1276 case K_INS: key = VTERM_KEY_INS; break;
1277 case K_K0: key = VTERM_KEY_KP_0; break;
1278 case K_K1: key = VTERM_KEY_KP_1; break;
1279 case K_K2: key = VTERM_KEY_KP_2; break;
1280 case K_K3: key = VTERM_KEY_KP_3; break;
1281 case K_K4: key = VTERM_KEY_KP_4; break;
1282 case K_K5: key = VTERM_KEY_KP_5; break;
1283 case K_K6: key = VTERM_KEY_KP_6; break;
1284 case K_K7: key = VTERM_KEY_KP_7; break;
1285 case K_K8: key = VTERM_KEY_KP_8; break;
1286 case K_K9: key = VTERM_KEY_KP_9; break;
1287 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1288 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1289 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1290 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1291 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1292 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1293 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1294 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1295 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1296 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1297 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1298 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1299 case K_LEFT: key = VTERM_KEY_LEFT; break;
1300 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1301 key = VTERM_KEY_LEFT; break;
1302 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1303 key = VTERM_KEY_LEFT; break;
1304 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1305 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1306 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1307 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1308 key = VTERM_KEY_RIGHT; break;
1309 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1310 key = VTERM_KEY_RIGHT; break;
1311 case K_UP: key = VTERM_KEY_UP; break;
1312 case K_S_UP: mod = VTERM_MOD_SHIFT;
1313 key = VTERM_KEY_UP; break;
1314 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001315 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1316 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001317
Bram Moolenaara42ad572017-11-16 13:08:04 +01001318 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1319 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001320 case K_MOUSELEFT: /* TODO */ return 0;
1321 case K_MOUSERIGHT: /* TODO */ return 0;
1322
1323 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001324 case K_LEFTMOUSE_NM:
1325 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001326 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001327 case K_LEFTRELEASE_NM:
1328 case K_MOUSEMOVE:
1329 case K_MIDDLEMOUSE:
1330 case K_MIDDLEDRAG:
1331 case K_MIDDLERELEASE:
1332 case K_RIGHTMOUSE:
1333 case K_RIGHTDRAG:
1334 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1335 return 0;
1336 other = TRUE;
1337 break;
1338
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001339 case K_X1MOUSE: /* TODO */ return 0;
1340 case K_X1DRAG: /* TODO */ return 0;
1341 case K_X1RELEASE: /* TODO */ return 0;
1342 case K_X2MOUSE: /* TODO */ return 0;
1343 case K_X2DRAG: /* TODO */ return 0;
1344 case K_X2RELEASE: /* TODO */ return 0;
1345
1346 case K_IGNORE: return 0;
1347 case K_NOP: return 0;
1348 case K_UNDO: return 0;
1349 case K_HELP: return 0;
1350 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1351 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1352 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1353 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1354 case K_SELECT: return 0;
1355#ifdef FEAT_GUI
1356 case K_VER_SCROLLBAR: return 0;
1357 case K_HOR_SCROLLBAR: return 0;
1358#endif
1359#ifdef FEAT_GUI_TABLINE
1360 case K_TABLINE: return 0;
1361 case K_TABMENU: return 0;
1362#endif
1363#ifdef FEAT_NETBEANS_INTG
1364 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1365#endif
1366#ifdef FEAT_DND
1367 case K_DROP: return 0;
1368#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001369 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001370 case K_PS: vterm_keyboard_start_paste(vterm);
1371 other = TRUE;
1372 break;
1373 case K_PE: vterm_keyboard_end_paste(vterm);
1374 other = TRUE;
1375 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001376 }
1377
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001378 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001379 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001380 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001381 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001382 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001383 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001384 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001385
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001386 /*
1387 * Convert special keys to vterm keys:
1388 * - Write keys to vterm: vterm_keyboard_key()
1389 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001390 */
1391 if (key != VTERM_KEY_NONE)
1392 /* Special key, let vterm convert it. */
1393 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001394 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001395 /* Normal character, let vterm convert it. */
1396 vterm_keyboard_unichar(vterm, c, mod);
1397
1398 /* Read back the converted escape sequence. */
1399 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1400}
1401
1402/*
1403 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001404 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001405 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001406 */
1407 static int
1408term_job_running_check(term_T *term, int check_job_status)
1409{
1410 /* Also consider the job finished when the channel is closed, to avoid a
1411 * race condition when updating the title. */
1412 if (term != NULL
1413 && term->tl_job != NULL
1414 && channel_is_open(term->tl_job->jv_channel))
1415 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001416 job_T *job = term->tl_job;
1417
1418 // Careful: Checking the job status may invoked callbacks, which close
1419 // the buffer and terminate "term". However, "job" will not be freed
1420 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001421 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001422 job_status(job);
1423 return (job->jv_status == JOB_STARTED
1424 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001425 }
1426 return FALSE;
1427}
1428
1429/*
1430 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001431 */
1432 int
1433term_job_running(term_T *term)
1434{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001435 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001436}
1437
1438/*
1439 * Return TRUE if "term" has an active channel and used ":term NONE".
1440 */
1441 int
1442term_none_open(term_T *term)
1443{
1444 /* Also consider the job finished when the channel is closed, to avoid a
1445 * race condition when updating the title. */
1446 return term != NULL
1447 && term->tl_job != NULL
1448 && channel_is_open(term->tl_job->jv_channel)
1449 && term->tl_job->jv_channel->ch_keep_open;
1450}
1451
1452/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001453 * Used when exiting: kill the job in "buf" if so desired.
1454 * Return OK when the job finished.
1455 * Return FAIL when the job is still running.
1456 */
1457 int
1458term_try_stop_job(buf_T *buf)
1459{
1460 int count;
1461 char *how = (char *)buf->b_term->tl_kill;
1462
1463#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1464 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1465 {
1466 char_u buff[DIALOG_MSG_SIZE];
1467 int ret;
1468
1469 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1470 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1471 if (ret == VIM_YES)
1472 how = "kill";
1473 else if (ret == VIM_CANCEL)
1474 return FAIL;
1475 }
1476#endif
1477 if (how == NULL || *how == NUL)
1478 return FAIL;
1479
1480 job_stop(buf->b_term->tl_job, NULL, how);
1481
Bram Moolenaar9172d232019-01-29 23:06:54 +01001482 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001483 for (count = 0; count < 100; ++count)
1484 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001485 job_T *job;
1486
1487 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001488 if (!buf_valid(buf)
1489 || buf->b_term == NULL
1490 || buf->b_term->tl_job == NULL)
1491 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001492 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001493
Bram Moolenaar9172d232019-01-29 23:06:54 +01001494 // Call job_status() to update jv_status. It may cause the job to be
1495 // cleaned up but it won't be freed.
1496 job_status(job);
1497 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001498 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001499
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001500 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001501 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001502 }
1503 return FAIL;
1504}
1505
1506/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001507 * Add the last line of the scrollback buffer to the buffer in the window.
1508 */
1509 static void
1510add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1511{
1512 buf_T *buf = term->tl_buffer;
1513 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1514 linenr_T lnum = buf->b_ml.ml_line_count;
1515
Bram Moolenaar4f974752019-02-17 17:44:42 +01001516#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001517 if (!enc_utf8 && enc_codepage > 0)
1518 {
1519 WCHAR *ret = NULL;
1520 int length = 0;
1521
1522 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1523 &ret, &length);
1524 if (ret != NULL)
1525 {
1526 WideCharToMultiByte_alloc(enc_codepage, 0,
1527 ret, length, (char **)&text, &len, 0, 0);
1528 vim_free(ret);
1529 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1530 vim_free(text);
1531 }
1532 }
1533 else
1534#endif
1535 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1536 if (empty)
1537 {
1538 /* Delete the empty line that was in the empty buffer. */
1539 curbuf = buf;
1540 ml_delete(1, FALSE);
1541 curbuf = curwin->w_buffer;
1542 }
1543}
1544
1545 static void
1546cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1547{
1548 attr->width = cell->width;
1549 attr->attrs = cell->attrs;
1550 attr->fg = cell->fg;
1551 attr->bg = cell->bg;
1552}
1553
1554 static int
1555equal_celattr(cellattr_T *a, cellattr_T *b)
1556{
1557 /* Comparing the colors should be sufficient. */
1558 return a->fg.red == b->fg.red
1559 && a->fg.green == b->fg.green
1560 && a->fg.blue == b->fg.blue
1561 && a->bg.red == b->bg.red
1562 && a->bg.green == b->bg.green
1563 && a->bg.blue == b->bg.blue;
1564}
1565
Bram Moolenaard96ff162018-02-18 22:13:29 +01001566/*
1567 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1568 * line at this position. Otherwise at the end.
1569 */
1570 static int
1571add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1572{
1573 if (ga_grow(&term->tl_scrollback, 1) == OK)
1574 {
1575 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1576 + term->tl_scrollback.ga_len;
1577
1578 if (lnum > 0)
1579 {
1580 int i;
1581
1582 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1583 {
1584 *line = *(line - 1);
1585 --line;
1586 }
1587 }
1588 line->sb_cols = 0;
1589 line->sb_cells = NULL;
1590 line->sb_fill_attr = *fill_attr;
1591 ++term->tl_scrollback.ga_len;
1592 return OK;
1593 }
1594 return FALSE;
1595}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001596
1597/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001598 * Remove the terminal contents from the scrollback and the buffer.
1599 * Used before adding a new scrollback line or updating the buffer for lines
1600 * displayed in the terminal.
1601 */
1602 static void
1603cleanup_scrollback(term_T *term)
1604{
1605 sb_line_T *line;
1606 garray_T *gap;
1607
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001608 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001609 gap = &term->tl_scrollback;
1610 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1611 && gap->ga_len > 0)
1612 {
1613 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1614 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1615 vim_free(line->sb_cells);
1616 --gap->ga_len;
1617 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001618 curbuf = curwin->w_buffer;
1619 if (curbuf == term->tl_buffer)
1620 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001621}
1622
1623/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001625 */
1626 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001627update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001628{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001629 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630 int len;
1631 int lines_skipped = 0;
1632 VTermPos pos;
1633 VTermScreenCell cell;
1634 cellattr_T fill_attr, new_fill_attr;
1635 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001636
1637 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1638 "Adding terminal window snapshot to buffer");
1639
1640 /* First remove the lines that were appended before, they might be
1641 * outdated. */
1642 cleanup_scrollback(term);
1643
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644 screen = vterm_obtain_screen(term->tl_vterm);
1645 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001646 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1647 {
1648 len = 0;
1649 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1650 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1651 && cell.chars[0] != NUL)
1652 {
1653 len = pos.col + 1;
1654 new_fill_attr = term->tl_default_color;
1655 }
1656 else
1657 /* Assume the last attr is the filler attr. */
1658 cell2cellattr(&cell, &new_fill_attr);
1659
1660 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1661 ++lines_skipped;
1662 else
1663 {
1664 while (lines_skipped > 0)
1665 {
1666 /* Line was skipped, add an empty line. */
1667 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001668 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001669 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001670 }
1671
1672 if (len == 0)
1673 p = NULL;
1674 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001675 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 if ((p != NULL || len == 0)
1677 && ga_grow(&term->tl_scrollback, 1) == OK)
1678 {
1679 garray_T ga;
1680 int width;
1681 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1682 + term->tl_scrollback.ga_len;
1683
1684 ga_init2(&ga, 1, 100);
1685 for (pos.col = 0; pos.col < len; pos.col += width)
1686 {
1687 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1688 {
1689 width = 1;
1690 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1691 if (ga_grow(&ga, 1) == OK)
1692 ga.ga_len += utf_char2bytes(' ',
1693 (char_u *)ga.ga_data + ga.ga_len);
1694 }
1695 else
1696 {
1697 width = cell.width;
1698
1699 cell2cellattr(&cell, &p[pos.col]);
1700
Bram Moolenaara79fd562018-12-20 20:47:32 +01001701 // Each character can be up to 6 bytes.
1702 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001703 {
1704 int i;
1705 int c;
1706
1707 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1708 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1709 (char_u *)ga.ga_data + ga.ga_len);
1710 }
1711 }
1712 }
1713 line->sb_cols = len;
1714 line->sb_cells = p;
1715 line->sb_fill_attr = new_fill_attr;
1716 fill_attr = new_fill_attr;
1717 ++term->tl_scrollback.ga_len;
1718
1719 if (ga_grow(&ga, 1) == FAIL)
1720 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1721 else
1722 {
1723 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1724 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1725 }
1726 ga_clear(&ga);
1727 }
1728 else
1729 vim_free(p);
1730 }
1731 }
1732
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001733 // Add trailing empty lines.
1734 for (pos.row = term->tl_scrollback.ga_len;
1735 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1736 ++pos.row)
1737 {
1738 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1739 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1740 }
1741
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001742 term->tl_dirty_snapshot = FALSE;
1743#ifdef FEAT_TIMERS
1744 term->tl_timer_set = FALSE;
1745#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001746}
1747
1748/*
1749 * If needed, add the current lines of the terminal to scrollback and to the
1750 * buffer. Called after the job has ended and when switching to
1751 * Terminal-Normal mode.
1752 * When "redraw" is TRUE redraw the windows that show the terminal.
1753 */
1754 static void
1755may_move_terminal_to_buffer(term_T *term, int redraw)
1756{
1757 win_T *wp;
1758
1759 if (term->tl_vterm == NULL)
1760 return;
1761
1762 /* Update the snapshot only if something changes or the buffer does not
1763 * have all the lines. */
1764 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1765 <= term->tl_scrollback_scrolled)
1766 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001767
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001768 /* Obtain the current background color. */
1769 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1770 &term->tl_default_color.fg, &term->tl_default_color.bg);
1771
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001772 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001773 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001774 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001775 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001776 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001777 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1778 wp->w_cursor.col = 0;
1779 wp->w_valid = 0;
1780 if (wp->w_cursor.lnum >= wp->w_height)
1781 {
1782 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001783
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001784 if (wp->w_topline < min_topline)
1785 wp->w_topline = min_topline;
1786 }
1787 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001788 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001790}
1791
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001792#if defined(FEAT_TIMERS) || defined(PROTO)
1793/*
1794 * Check if any terminal timer expired. If so, copy text from the terminal to
1795 * the buffer.
1796 * Return the time until the next timer will expire.
1797 */
1798 int
1799term_check_timers(int next_due_arg, proftime_T *now)
1800{
1801 term_T *term;
1802 int next_due = next_due_arg;
1803
1804 for (term = first_term; term != NULL; term = term->tl_next)
1805 {
1806 if (term->tl_timer_set && !term->tl_normal_mode)
1807 {
1808 long this_due = proftime_time_left(&term->tl_timer_due, now);
1809
1810 if (this_due <= 1)
1811 {
1812 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001813 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001814 }
1815 else if (next_due == -1 || next_due > this_due)
1816 next_due = this_due;
1817 }
1818 }
1819
1820 return next_due;
1821}
1822#endif
1823
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001824/*
1825 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1826 * otherwise end it.
1827 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001828 static void
1829set_terminal_mode(term_T *term, int normal_mode)
1830{
1831 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001832 if (!normal_mode)
1833 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001834 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001835 if (term->tl_buffer == curbuf)
1836 maketitle();
1837}
1838
1839/*
1840 * Called after the job if finished and Terminal mode is not active:
1841 * Move the vterm contents into the scrollback buffer and free the vterm.
1842 */
1843 static void
1844cleanup_vterm(term_T *term)
1845{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001846 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001847 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001848 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001849 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850}
1851
1852/*
1853 * Switch from Terminal-Job mode to Terminal-Normal mode.
1854 * Suspends updating the terminal window.
1855 */
1856 static void
1857term_enter_normal_mode(void)
1858{
1859 term_T *term = curbuf->b_term;
1860
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001861 set_terminal_mode(term, TRUE);
1862
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001863 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001864 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 /* Move the window cursor to the position of the cursor in the
1867 * terminal. */
1868 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1869 + term->tl_cursor_pos.row + 1;
1870 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001871 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1872 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873
1874 /* Display the same lines as in the terminal. */
1875 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1876}
1877
1878/*
1879 * Returns TRUE if the current window contains a terminal and we are in
1880 * Terminal-Normal mode.
1881 */
1882 int
1883term_in_normal_mode(void)
1884{
1885 term_T *term = curbuf->b_term;
1886
1887 return term != NULL && term->tl_normal_mode;
1888}
1889
1890/*
1891 * Switch from Terminal-Normal mode to Terminal-Job mode.
1892 * Restores updating the terminal window.
1893 */
1894 void
1895term_enter_job_mode()
1896{
1897 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001898
1899 set_terminal_mode(term, FALSE);
1900
1901 if (term->tl_channel_closed)
1902 cleanup_vterm(term);
1903 redraw_buf_and_status_later(curbuf, NOT_VALID);
1904}
1905
1906/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001907 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001908 * Note: while waiting a terminal may be closed and freed if the channel is
1909 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001910 */
1911 static int
1912term_vgetc()
1913{
1914 int c;
1915 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001916 int modify_other_keys =
1917 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001918
1919 State = TERMINAL;
1920 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01001921#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001922 ctrl_break_was_pressed = FALSE;
1923#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001924 if (modify_other_keys)
1925 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001926 c = vgetc();
1927 got_int = FALSE;
1928 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001929 if (modify_other_keys)
1930 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001931 return c;
1932}
1933
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001934static int mouse_was_outside = FALSE;
1935
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001936/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001937 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938 * Return FAIL when the key needs to be handled in Normal mode.
1939 * Return OK when the key was dropped or sent to the terminal.
1940 */
1941 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001942send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001943{
1944 char msg[KEY_BUF_LEN];
1945 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001946 int dragging_outside = FALSE;
1947
1948 /* Catch keys that need to be handled as in Normal mode. */
1949 switch (c)
1950 {
1951 case NUL:
1952 case K_ZERO:
1953 if (typed)
1954 stuffcharReadbuff(c);
1955 return FAIL;
1956
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001957 case K_TABLINE:
1958 stuffcharReadbuff(c);
1959 return FAIL;
1960
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001962 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001963 return FAIL;
1964
1965 case K_LEFTDRAG:
1966 case K_MIDDLEDRAG:
1967 case K_RIGHTDRAG:
1968 case K_X1DRAG:
1969 case K_X2DRAG:
1970 dragging_outside = mouse_was_outside;
1971 /* FALLTHROUGH */
1972 case K_LEFTMOUSE:
1973 case K_LEFTMOUSE_NM:
1974 case K_LEFTRELEASE:
1975 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001976 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001977 case K_MIDDLEMOUSE:
1978 case K_MIDDLERELEASE:
1979 case K_RIGHTMOUSE:
1980 case K_RIGHTRELEASE:
1981 case K_X1MOUSE:
1982 case K_X1RELEASE:
1983 case K_X2MOUSE:
1984 case K_X2RELEASE:
1985
1986 case K_MOUSEUP:
1987 case K_MOUSEDOWN:
1988 case K_MOUSELEFT:
1989 case K_MOUSERIGHT:
1990 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001991 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001992 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001993 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001994 || dragging_outside)
1995 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001996 /* click or scroll outside the current window or on status line
1997 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001998 if (typed)
1999 {
2000 stuffcharReadbuff(c);
2001 mouse_was_outside = TRUE;
2002 }
2003 return FAIL;
2004 }
2005 }
2006 if (typed)
2007 mouse_was_outside = FALSE;
2008
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002009 // Convert the typed key to a sequence of bytes for the job.
2010 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002011 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002012 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002013 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2014 (char_u *)msg, (int)len, NULL);
2015
2016 return OK;
2017}
2018
2019 static void
2020position_cursor(win_T *wp, VTermPos *pos)
2021{
2022 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2023 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
2024 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2025}
2026
2027/*
2028 * Handle CTRL-W "": send register contents to the job.
2029 */
2030 static void
2031term_paste_register(int prev_c UNUSED)
2032{
2033 int c;
2034 list_T *l;
2035 listitem_T *item;
2036 long reglen = 0;
2037 int type;
2038
2039#ifdef FEAT_CMDL_INFO
2040 if (add_to_showcmd(prev_c))
2041 if (add_to_showcmd('"'))
2042 out_flush();
2043#endif
2044 c = term_vgetc();
2045#ifdef FEAT_CMDL_INFO
2046 clear_showcmd();
2047#endif
2048 if (!term_use_loop())
2049 /* job finished while waiting for a character */
2050 return;
2051
2052 /* CTRL-W "= prompt for expression to evaluate. */
2053 if (c == '=' && get_expr_register() != '=')
2054 return;
2055 if (!term_use_loop())
2056 /* job finished while waiting for a character */
2057 return;
2058
2059 l = (list_T *)get_reg_contents(c, GREG_LIST);
2060 if (l != NULL)
2061 {
2062 type = get_reg_type(c, &reglen);
2063 for (item = l->lv_first; item != NULL; item = item->li_next)
2064 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002065 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002066#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002067 char_u *tmp = s;
2068
2069 if (!enc_utf8 && enc_codepage > 0)
2070 {
2071 WCHAR *ret = NULL;
2072 int length = 0;
2073
2074 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2075 (int)STRLEN(s), &ret, &length);
2076 if (ret != NULL)
2077 {
2078 WideCharToMultiByte_alloc(CP_UTF8, 0,
2079 ret, length, (char **)&s, &length, 0, 0);
2080 vim_free(ret);
2081 }
2082 }
2083#endif
2084 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2085 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002086#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002087 if (tmp != s)
2088 vim_free(s);
2089#endif
2090
2091 if (item->li_next != NULL || type == MLINE)
2092 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2093 (char_u *)"\r", 1, NULL);
2094 }
2095 list_free(l);
2096 }
2097}
2098
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002099/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002100 * Return TRUE when waiting for a character in the terminal, the cursor of the
2101 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002102 */
2103 int
2104terminal_is_active()
2105{
2106 return in_terminal_loop != NULL;
2107}
2108
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002109#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002110 cursorentry_T *
2111term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2112{
2113 term_T *term = in_terminal_loop;
2114 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002115 int id;
2116 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117
2118 vim_memset(&entry, 0, sizeof(entry));
2119 entry.shape = entry.mshape =
2120 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2121 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2122 SHAPE_BLOCK;
2123 entry.percentage = 20;
2124 if (term->tl_cursor_blink)
2125 {
2126 entry.blinkwait = 700;
2127 entry.blinkon = 400;
2128 entry.blinkoff = 250;
2129 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002130
2131 /* The "Terminal" highlight group overrules the defaults. */
2132 id = syn_name2id((char_u *)"Terminal");
2133 if (id != 0)
2134 {
2135 syn_id2colors(id, &term_fg, &term_bg);
2136 *fg = term_bg;
2137 }
2138 else
2139 *fg = gui.back_pixel;
2140
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002142 {
2143 if (id != 0)
2144 *bg = term_fg;
2145 else
2146 *bg = gui.norm_pixel;
2147 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002148 else
2149 *bg = color_name2handle(term->tl_cursor_color);
2150 entry.name = "n";
2151 entry.used_for = SHAPE_CURSOR;
2152
2153 return &entry;
2154}
2155#endif
2156
Bram Moolenaard317b382018-02-08 22:33:31 +01002157 static void
2158may_output_cursor_props(void)
2159{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002160 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002161 || last_set_cursor_shape != desired_cursor_shape
2162 || last_set_cursor_blink != desired_cursor_blink)
2163 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002164 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002165 last_set_cursor_shape = desired_cursor_shape;
2166 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002167 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002168 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
2169 /* this will restore the initial cursor style, if possible */
2170 ui_cursor_shape_forced(TRUE);
2171 else
2172 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2173 }
2174}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002175
Bram Moolenaard317b382018-02-08 22:33:31 +01002176/*
2177 * Set the cursor color and shape, if not last set to these.
2178 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002179 static void
2180may_set_cursor_props(term_T *term)
2181{
2182#ifdef FEAT_GUI
2183 /* For the GUI the cursor properties are obtained with
2184 * term_get_cursor_shape(). */
2185 if (gui.in_use)
2186 return;
2187#endif
2188 if (in_terminal_loop == term)
2189 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002190 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002191 desired_cursor_shape = term->tl_cursor_shape;
2192 desired_cursor_blink = term->tl_cursor_blink;
2193 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002194 }
2195}
2196
Bram Moolenaard317b382018-02-08 22:33:31 +01002197/*
2198 * Reset the desired cursor properties and restore them when needed.
2199 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002200 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002201prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002202{
2203#ifdef FEAT_GUI
2204 if (gui.in_use)
2205 return;
2206#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002207 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002208 desired_cursor_shape = -1;
2209 desired_cursor_blink = -1;
2210 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002211}
2212
2213/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002214 * Returns TRUE if the current window contains a terminal and we are sending
2215 * keys to the job.
2216 * If "check_job_status" is TRUE update the job status.
2217 */
2218 static int
2219term_use_loop_check(int check_job_status)
2220{
2221 term_T *term = curbuf->b_term;
2222
2223 return term != NULL
2224 && !term->tl_normal_mode
2225 && term->tl_vterm != NULL
2226 && term_job_running_check(term, check_job_status);
2227}
2228
2229/*
2230 * Returns TRUE if the current window contains a terminal and we are sending
2231 * keys to the job.
2232 */
2233 int
2234term_use_loop(void)
2235{
2236 return term_use_loop_check(FALSE);
2237}
2238
2239/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002240 * Called when entering a window with the mouse. If this is a terminal window
2241 * we may want to change state.
2242 */
2243 void
2244term_win_entered()
2245{
2246 term_T *term = curbuf->b_term;
2247
2248 if (term != NULL)
2249 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002250 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002251 {
2252 reset_VIsual_and_resel();
2253 if (State & INSERT)
2254 stop_insert_mode = TRUE;
2255 }
2256 mouse_was_outside = FALSE;
2257 enter_mouse_col = mouse_col;
2258 enter_mouse_row = mouse_row;
2259 }
2260}
2261
2262/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002263 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2264 * Return the Ctrl-key value in that case.
2265 */
2266 static int
2267raw_c_to_ctrl(int c)
2268{
2269 if ((mod_mask & MOD_MASK_CTRL)
2270 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2271 return c & 0x1f;
2272 return c;
2273}
2274
2275/*
2276 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2277 * May set "mod_mask".
2278 */
2279 static int
2280ctrl_to_raw_c(int c)
2281{
2282 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2283 {
2284 mod_mask |= MOD_MASK_CTRL;
2285 return c + '@';
2286 }
2287 return c;
2288}
2289
2290/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002291 * Wait for input and send it to the job.
2292 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2293 * when there is no more typahead.
2294 * Return when the start of a CTRL-W command is typed or anything else that
2295 * should be handled as a Normal mode command.
2296 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2297 * the terminal was closed.
2298 */
2299 int
2300terminal_loop(int blocking)
2301{
2302 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002303 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002304 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002305 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002306#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002307 int tty_fd = curbuf->b_term->tl_job->jv_channel
2308 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002309#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002310 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002311
2312 /* Remember the terminal we are sending keys to. However, the terminal
2313 * might be closed while waiting for a character, e.g. typing "exit" in a
2314 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2315 * stored reference. */
2316 in_terminal_loop = curbuf->b_term;
2317
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002318 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002319 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002320 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002321 if (termwinkey == Ctrl_W)
2322 termwinkey = 0;
2323 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002324 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2325 may_set_cursor_props(curbuf->b_term);
2326
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002327 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002328 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002329#ifdef FEAT_GUI
2330 if (!curbuf->b_term->tl_system)
2331#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002332 // TODO: skip screen update when handling a sequence of keys.
2333 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002334 while (must_redraw != 0)
2335 if (update_screen(0) == FAIL)
2336 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002337 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002338 /* job finished while redrawing */
2339 break;
2340
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002341 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002342 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002343
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002344 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002345 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002346 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002347 /* Job finished while waiting for a character. Push back the
2348 * received character. */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002349 if (raw_c != K_IGNORE)
2350 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002352 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002353 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002355 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002356
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002357#ifdef UNIX
2358 /*
2359 * The shell or another program may change the tty settings. Getting
2360 * them for every typed character is a bit of overhead, but it's needed
2361 * for the first character typed, e.g. when Vim starts in a shell.
2362 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002363 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002364 {
2365 ttyinfo_T info;
2366
2367 /* Get the current backspace character of the pty. */
2368 if (get_tty_info(tty_fd, &info) == OK)
2369 term_backspace_char = info.backspace;
2370 }
2371#endif
2372
Bram Moolenaar4f974752019-02-17 17:44:42 +01002373#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002374 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2375 * Use CTRL-BREAK to kill the job. */
2376 if (ctrl_break_was_pressed)
2377 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2378#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002379 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002380 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002381 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002382#ifdef FEAT_GUI
2383 && !curbuf->b_term->tl_system
2384#endif
2385 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002386 {
2387 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002388 int prev_raw_c = raw_c;
2389 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390
2391#ifdef FEAT_CMDL_INFO
2392 if (add_to_showcmd(c))
2393 out_flush();
2394#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002395 raw_c = term_vgetc();
2396 c = raw_c_to_ctrl(raw_c);
2397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002398#ifdef FEAT_CMDL_INFO
2399 clear_showcmd();
2400#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002401 if (!term_use_loop_check(TRUE)
2402 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002403 /* job finished while waiting for a character */
2404 break;
2405
2406 if (prev_c == Ctrl_BSL)
2407 {
2408 if (c == Ctrl_N)
2409 {
2410 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2411 term_enter_normal_mode();
2412 ret = FAIL;
2413 goto theend;
2414 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002415 // Send both keys to the terminal, first one here, second one
2416 // below.
2417 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2418 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 }
2420 else if (c == Ctrl_C)
2421 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002422 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002423 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2424 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002425 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002426 {
2427 /* "CTRL-W .": send CTRL-W to the job */
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002428 /* "'termwinkey' .": send 'termwinkey' to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002429 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002430 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002431 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002432 {
2433 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002434 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002435 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002436 else if (c == 'N')
2437 {
2438 /* CTRL-W N : go to Terminal-Normal mode. */
2439 term_enter_normal_mode();
2440 ret = FAIL;
2441 goto theend;
2442 }
2443 else if (c == '"')
2444 {
2445 term_paste_register(prev_c);
2446 continue;
2447 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002448 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002449 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002450 char_u buf[MB_MAXBYTES + 2];
2451
2452 // Put the command into the typeahead buffer, when using the
2453 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2454 buf[0] = Ctrl_W;
2455 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2456 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002457 ret = OK;
2458 goto theend;
2459 }
2460 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002461# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002462 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002463 {
2464 WCHAR wc;
2465 char_u mb[3];
2466
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002467 mb[0] = (unsigned)raw_c >> 8;
2468 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002470 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471 }
2472# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002473 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002475 if (raw_c == K_MOUSEMOVE)
Bram Moolenaard317b382018-02-08 22:33:31 +01002476 /* We are sure to come back here, don't reset the cursor color
2477 * and shape to avoid flickering. */
2478 restore_cursor = FALSE;
2479
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002480 ret = OK;
2481 goto theend;
2482 }
2483 }
2484 ret = FAIL;
2485
2486theend:
2487 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002488 if (restore_cursor)
2489 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002490
2491 /* Move a snapshot of the screen contents to the buffer, so that completion
2492 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002493 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2494 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002495
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002496 return ret;
2497}
2498
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002499 static void
2500may_toggle_cursor(term_T *term)
2501{
2502 if (in_terminal_loop == term)
2503 {
2504 if (term->tl_cursor_visible)
2505 cursor_on();
2506 else
2507 cursor_off();
2508 }
2509}
2510
2511/*
2512 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002513 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 */
2515 static int
2516color2index(VTermColor *color, int fg, int *boldp)
2517{
2518 int red = color->red;
2519 int blue = color->blue;
2520 int green = color->green;
2521
Bram Moolenaar46359e12017-11-29 22:33:38 +01002522 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002523 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002524 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002525 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002527 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002528 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002529 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2530 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2531 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002532 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002533 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2534 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2535 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2536 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2537 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2538 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2539 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2540 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2541 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2542 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2543 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002544 }
2545 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002546
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 if (t_colors >= 256)
2548 {
2549 if (red == blue && red == green)
2550 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002551 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002553 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2554 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2555 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002556 int i;
2557
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002558 if (red < 5)
2559 return 17; /* 00/00/00 */
2560 if (red > 245) /* ff/ff/ff */
2561 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002562 for (i = 0; i < 23; ++i)
2563 if (red < cutoff[i])
2564 return i + 233;
2565 return 256;
2566 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002567 {
2568 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2569 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002571 /* 216-color cube */
2572 for (ri = 0; ri < 5; ++ri)
2573 if (red < cutoff[ri])
2574 break;
2575 for (gi = 0; gi < 5; ++gi)
2576 if (green < cutoff[gi])
2577 break;
2578 for (bi = 0; bi < 5; ++bi)
2579 if (blue < cutoff[bi])
2580 break;
2581 return 17 + ri * 36 + gi * 6 + bi;
2582 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002583 }
2584 return 0;
2585}
2586
2587/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002588 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 */
2590 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002591vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002592{
2593 int attr = 0;
2594
2595 if (cellattrs.bold)
2596 attr |= HL_BOLD;
2597 if (cellattrs.underline)
2598 attr |= HL_UNDERLINE;
2599 if (cellattrs.italic)
2600 attr |= HL_ITALIC;
2601 if (cellattrs.strike)
2602 attr |= HL_STRIKETHROUGH;
2603 if (cellattrs.reverse)
2604 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002605 return attr;
2606}
2607
2608/*
2609 * Store Vterm attributes in "cell" from highlight flags.
2610 */
2611 static void
2612hl2vtermAttr(int attr, cellattr_T *cell)
2613{
2614 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2615 if (attr & HL_BOLD)
2616 cell->attrs.bold = 1;
2617 if (attr & HL_UNDERLINE)
2618 cell->attrs.underline = 1;
2619 if (attr & HL_ITALIC)
2620 cell->attrs.italic = 1;
2621 if (attr & HL_STRIKETHROUGH)
2622 cell->attrs.strike = 1;
2623 if (attr & HL_INVERSE)
2624 cell->attrs.reverse = 1;
2625}
2626
2627/*
2628 * Convert the attributes of a vterm cell into an attribute index.
2629 */
2630 static int
2631cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2632{
2633 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002634
2635#ifdef FEAT_GUI
2636 if (gui.in_use)
2637 {
2638 guicolor_T fg, bg;
2639
2640 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2641 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2642 return get_gui_attr_idx(attr, fg, bg);
2643 }
2644 else
2645#endif
2646#ifdef FEAT_TERMGUICOLORS
2647 if (p_tgc)
2648 {
2649 guicolor_T fg, bg;
2650
2651 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2652 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2653
2654 return get_tgc_attr_idx(attr, fg, bg);
2655 }
2656 else
2657#endif
2658 {
2659 int bold = MAYBE;
2660 int fg = color2index(&cellfg, TRUE, &bold);
2661 int bg = color2index(&cellbg, FALSE, &bold);
2662
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002663 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002664 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002665 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002666 if (fg == 0 && term_default_cterm_fg >= 0)
2667 fg = term_default_cterm_fg + 1;
2668 if (bg == 0 && term_default_cterm_bg >= 0)
2669 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002670 }
2671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002672 /* with 8 colors set the bold attribute to get a bright foreground */
2673 if (bold == TRUE)
2674 attr |= HL_BOLD;
2675 return get_cterm_attr_idx(attr, fg, bg);
2676 }
2677 return 0;
2678}
2679
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002680 static void
2681set_dirty_snapshot(term_T *term)
2682{
2683 term->tl_dirty_snapshot = TRUE;
2684#ifdef FEAT_TIMERS
2685 if (!term->tl_normal_mode)
2686 {
2687 /* Update the snapshot after 100 msec of not getting updates. */
2688 profile_setlimit(100L, &term->tl_timer_due);
2689 term->tl_timer_set = TRUE;
2690 }
2691#endif
2692}
2693
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002694 static int
2695handle_damage(VTermRect rect, void *user)
2696{
2697 term_T *term = (term_T *)user;
2698
2699 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2700 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002701 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002702 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002703 return 1;
2704}
2705
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002706 static void
2707term_scroll_up(term_T *term, int start_row, int count)
2708{
2709 win_T *wp;
2710 VTermColor fg, bg;
2711 VTermScreenCellAttrs attr;
2712 int clear_attr;
2713
2714 /* Set the color to clear lines with. */
2715 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2716 &fg, &bg);
2717 vim_memset(&attr, 0, sizeof(attr));
2718 clear_attr = cell2attr(attr, fg, bg);
2719
2720 FOR_ALL_WINDOWS(wp)
2721 {
2722 if (wp->w_buffer == term->tl_buffer)
2723 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2724 }
2725}
2726
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002727 static int
2728handle_moverect(VTermRect dest, VTermRect src, void *user)
2729{
2730 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002731 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002732
2733 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002734 * redrawing the text. But avoid doing this multiple times, postpone until
2735 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002736 if (dest.start_col == src.start_col
2737 && dest.end_col == src.end_col
2738 && dest.start_row < src.start_row)
2739 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002740 if (dest.start_row == 0)
2741 term->tl_postponed_scroll += count;
2742 else
2743 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002744 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002745
2746 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2747 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002748 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002749
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002750 /* Note sure if the scrolling will work correctly, let's do a complete
2751 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002752 redraw_buf_later(term->tl_buffer, NOT_VALID);
2753 return 1;
2754}
2755
2756 static int
2757handle_movecursor(
2758 VTermPos pos,
2759 VTermPos oldpos UNUSED,
2760 int visible,
2761 void *user)
2762{
2763 term_T *term = (term_T *)user;
2764 win_T *wp;
2765
2766 term->tl_cursor_pos = pos;
2767 term->tl_cursor_visible = visible;
2768
2769 FOR_ALL_WINDOWS(wp)
2770 {
2771 if (wp->w_buffer == term->tl_buffer)
2772 position_cursor(wp, &pos);
2773 }
2774 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2775 {
2776 may_toggle_cursor(term);
2777 update_cursor(term, term->tl_cursor_visible);
2778 }
2779
2780 return 1;
2781}
2782
2783 static int
2784handle_settermprop(
2785 VTermProp prop,
2786 VTermValue *value,
2787 void *user)
2788{
2789 term_T *term = (term_T *)user;
2790
2791 switch (prop)
2792 {
2793 case VTERM_PROP_TITLE:
2794 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002795 // a blank title isn't useful, make it empty, so that "running" is
2796 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002797 if (*skipwhite((char_u *)value->string) == NUL)
2798 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002799 // Same as blank
2800 else if (term->tl_arg0_cmd != NULL
2801 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
2802 (int)STRLEN(term->tl_arg0_cmd)) == 0)
2803 term->tl_title = NULL;
2804 // Empty corrupted data of winpty
2805 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
2806 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002807#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002808 else if (!enc_utf8 && enc_codepage > 0)
2809 {
2810 WCHAR *ret = NULL;
2811 int length = 0;
2812
2813 MultiByteToWideChar_alloc(CP_UTF8, 0,
2814 (char*)value->string, (int)STRLEN(value->string),
2815 &ret, &length);
2816 if (ret != NULL)
2817 {
2818 WideCharToMultiByte_alloc(enc_codepage, 0,
2819 ret, length, (char**)&term->tl_title,
2820 &length, 0, 0);
2821 vim_free(ret);
2822 }
2823 }
2824#endif
2825 else
2826 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002827 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828 if (term == curbuf->b_term)
2829 maketitle();
2830 break;
2831
2832 case VTERM_PROP_CURSORVISIBLE:
2833 term->tl_cursor_visible = value->boolean;
2834 may_toggle_cursor(term);
2835 out_flush();
2836 break;
2837
2838 case VTERM_PROP_CURSORBLINK:
2839 term->tl_cursor_blink = value->boolean;
2840 may_set_cursor_props(term);
2841 break;
2842
2843 case VTERM_PROP_CURSORSHAPE:
2844 term->tl_cursor_shape = value->number;
2845 may_set_cursor_props(term);
2846 break;
2847
2848 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002849 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002850 may_set_cursor_props(term);
2851 break;
2852
2853 case VTERM_PROP_ALTSCREEN:
2854 /* TODO: do anything else? */
2855 term->tl_using_altscreen = value->boolean;
2856 break;
2857
2858 default:
2859 break;
2860 }
2861 /* Always return 1, otherwise vterm doesn't store the value internally. */
2862 return 1;
2863}
2864
2865/*
2866 * The job running in the terminal resized the terminal.
2867 */
2868 static int
2869handle_resize(int rows, int cols, void *user)
2870{
2871 term_T *term = (term_T *)user;
2872 win_T *wp;
2873
2874 term->tl_rows = rows;
2875 term->tl_cols = cols;
2876 if (term->tl_vterm_size_changed)
2877 /* Size was set by vterm_set_size(), don't set the window size. */
2878 term->tl_vterm_size_changed = FALSE;
2879 else
2880 {
2881 FOR_ALL_WINDOWS(wp)
2882 {
2883 if (wp->w_buffer == term->tl_buffer)
2884 {
2885 win_setheight_win(rows, wp);
2886 win_setwidth_win(cols, wp);
2887 }
2888 }
2889 redraw_buf_later(term->tl_buffer, NOT_VALID);
2890 }
2891 return 1;
2892}
2893
2894/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002895 * If the number of lines that are stored goes over 'termscrollback' then
2896 * delete the first 10%.
2897 * "gap" points to tl_scrollback or tl_scrollback_postponed.
2898 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002899 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002900 static void
2901limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002902{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002903 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002904 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002905 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002906 int i;
2907
2908 curbuf = term->tl_buffer;
2909 for (i = 0; i < todo; ++i)
2910 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002911 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
2912 if (update_buffer)
2913 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002914 }
2915 curbuf = curwin->w_buffer;
2916
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002917 gap->ga_len -= todo;
2918 mch_memmove(gap->ga_data,
2919 (sb_line_T *)gap->ga_data + todo,
2920 sizeof(sb_line_T) * gap->ga_len);
2921 if (update_buffer)
2922 term->tl_scrollback_scrolled -= todo;
2923 }
2924}
2925
2926/*
2927 * Handle a line that is pushed off the top of the screen.
2928 */
2929 static int
2930handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2931{
2932 term_T *term = (term_T *)user;
2933 garray_T *gap;
2934 int update_buffer;
2935
2936 if (term->tl_normal_mode)
2937 {
2938 // In Terminal-Normal mode the user interacts with the buffer, thus we
2939 // must not change it. Postpone adding the scrollback lines.
2940 gap = &term->tl_scrollback_postponed;
2941 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002942 }
2943 else
2944 {
2945 // First remove the lines that were appended before, the pushed line
2946 // goes above it.
2947 cleanup_scrollback(term);
2948 gap = &term->tl_scrollback;
2949 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002950 }
2951
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002952 limit_scrollback(term, gap, update_buffer);
2953
2954 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002955 {
2956 cellattr_T *p = NULL;
2957 int len = 0;
2958 int i;
2959 int c;
2960 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002961 int text_len;
2962 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002963 sb_line_T *line;
2964 garray_T ga;
2965 cellattr_T fill_attr = term->tl_default_color;
2966
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002967 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002968 for (i = 0; i < cols; ++i)
2969 if (cells[i].chars[0] != 0)
2970 len = i + 1;
2971 else
2972 cell2cellattr(&cells[i], &fill_attr);
2973
2974 ga_init2(&ga, 1, 100);
2975 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002976 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002977 if (p != NULL)
2978 {
2979 for (col = 0; col < len; col += cells[col].width)
2980 {
2981 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2982 {
2983 ga.ga_len = 0;
2984 break;
2985 }
2986 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2987 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2988 (char_u *)ga.ga_data + ga.ga_len);
2989 cell2cellattr(&cells[col], &p[col]);
2990 }
2991 }
2992 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01002993 {
2994 if (update_buffer)
2995 text = (char_u *)"";
2996 else
2997 text = vim_strsave((char_u *)"");
2998 text_len = 0;
2999 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003000 else
3001 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003002 text = ga.ga_data;
3003 text_len = ga.ga_len;
3004 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003005 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003006 if (update_buffer)
3007 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003008
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003009 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003010 line->sb_cols = len;
3011 line->sb_cells = p;
3012 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003013 if (update_buffer)
3014 {
3015 line->sb_text = NULL;
3016 ++term->tl_scrollback_scrolled;
3017 ga_clear(&ga); // free the text
3018 }
3019 else
3020 {
3021 line->sb_text = text;
3022 ga_init(&ga); // text is kept in tl_scrollback_postponed
3023 }
3024 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003025 }
3026 return 0; /* ignored */
3027}
3028
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003029/*
3030 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3031 * received and stored in tl_scrollback_postponed.
3032 */
3033 static void
3034handle_postponed_scrollback(term_T *term)
3035{
3036 int i;
3037
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003038 if (term->tl_scrollback_postponed.ga_len == 0)
3039 return;
3040 ch_log(NULL, "Moving postponed scrollback to scrollback");
3041
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003042 // First remove the lines that were appended before, the pushed lines go
3043 // above it.
3044 cleanup_scrollback(term);
3045
3046 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3047 {
3048 char_u *text;
3049 sb_line_T *pp_line;
3050 sb_line_T *line;
3051
3052 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3053 break;
3054 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3055
3056 text = pp_line->sb_text;
3057 if (text == NULL)
3058 text = (char_u *)"";
3059 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3060 vim_free(pp_line->sb_text);
3061
3062 line = (sb_line_T *)term->tl_scrollback.ga_data
3063 + term->tl_scrollback.ga_len;
3064 line->sb_cols = pp_line->sb_cols;
3065 line->sb_cells = pp_line->sb_cells;
3066 line->sb_fill_attr = pp_line->sb_fill_attr;
3067 line->sb_text = NULL;
3068 ++term->tl_scrollback_scrolled;
3069 ++term->tl_scrollback.ga_len;
3070 }
3071
3072 ga_clear(&term->tl_scrollback_postponed);
3073 limit_scrollback(term, &term->tl_scrollback, TRUE);
3074}
3075
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003076static VTermScreenCallbacks screen_callbacks = {
3077 handle_damage, /* damage */
3078 handle_moverect, /* moverect */
3079 handle_movecursor, /* movecursor */
3080 handle_settermprop, /* settermprop */
3081 NULL, /* bell */
3082 handle_resize, /* resize */
3083 handle_pushline, /* sb_pushline */
3084 NULL /* sb_popline */
3085};
3086
3087/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003088 * Do the work after the channel of a terminal was closed.
3089 * Must be called only when updating_screen is FALSE.
3090 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3091 */
3092 static int
3093term_after_channel_closed(term_T *term)
3094{
3095 /* Unless in Terminal-Normal mode: clear the vterm. */
3096 if (!term->tl_normal_mode)
3097 {
3098 int fnum = term->tl_buffer->b_fnum;
3099
3100 cleanup_vterm(term);
3101
3102 if (term->tl_finish == TL_FINISH_CLOSE)
3103 {
3104 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003105 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003106
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003107 // If this is the last normal window: exit Vim.
3108 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3109 {
3110 exarg_T ea;
3111
3112 vim_memset(&ea, 0, sizeof(ea));
3113 ex_quit(&ea);
3114 return TRUE;
3115 }
3116
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003117 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003118 ch_log(NULL, "terminal job finished, closing window");
3119 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003120 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003121 if (curwin == aucmd_win)
3122 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003123 if (do_set_w_closing)
3124 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003125 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003126 if (do_set_w_closing)
3127 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003128 aucmd_restbuf(&aco);
3129 return TRUE;
3130 }
3131 if (term->tl_finish == TL_FINISH_OPEN
3132 && term->tl_buffer->b_nwindows == 0)
3133 {
3134 char buf[50];
3135
3136 /* TODO: use term_opencmd */
3137 ch_log(NULL, "terminal job finished, opening window");
3138 vim_snprintf(buf, sizeof(buf),
3139 term->tl_opencmd == NULL
3140 ? "botright sbuf %d"
3141 : (char *)term->tl_opencmd, fnum);
3142 do_cmdline_cmd((char_u *)buf);
3143 }
3144 else
3145 ch_log(NULL, "terminal job finished");
3146 }
3147
3148 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3149 return FALSE;
3150}
3151
3152/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 * Called when a channel has been closed.
3154 * If this was a channel for a terminal window then finish it up.
3155 */
3156 void
3157term_channel_closed(channel_T *ch)
3158{
3159 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003160 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003161 int did_one = FALSE;
3162
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003163 for (term = first_term; term != NULL; term = next_term)
3164 {
3165 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003166 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003167 {
3168 term->tl_channel_closed = TRUE;
3169 did_one = TRUE;
3170
Bram Moolenaard23a8232018-02-10 18:45:26 +01003171 VIM_CLEAR(term->tl_title);
3172 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003173#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003174 if (term->tl_out_fd != NULL)
3175 {
3176 fclose(term->tl_out_fd);
3177 term->tl_out_fd = NULL;
3178 }
3179#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003180
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003181 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003182 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003183 /* Cannot open or close windows now. Can happen when
3184 * 'lazyredraw' is set. */
3185 term->tl_channel_recently_closed = TRUE;
3186 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003187 }
3188
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003189 if (term_after_channel_closed(term))
3190 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003191 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003192 }
3193
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003194 if (did_one)
3195 {
3196 redraw_statuslines();
3197
3198 /* Need to break out of vgetc(). */
3199 ins_char_typebuf(K_IGNORE);
3200 typebuf_was_filled = TRUE;
3201
3202 term = curbuf->b_term;
3203 if (term != NULL)
3204 {
3205 if (term->tl_job == ch->ch_job)
3206 maketitle();
3207 update_cursor(term, term->tl_cursor_visible);
3208 }
3209 }
3210}
3211
3212/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003213 * To be called after resetting updating_screen: handle any terminal where the
3214 * channel was closed.
3215 */
3216 void
3217term_check_channel_closed_recently()
3218{
3219 term_T *term;
3220 term_T *next_term;
3221
3222 for (term = first_term; term != NULL; term = next_term)
3223 {
3224 next_term = term->tl_next;
3225 if (term->tl_channel_recently_closed)
3226 {
3227 term->tl_channel_recently_closed = FALSE;
3228 if (term_after_channel_closed(term))
3229 // start over, the list may have changed
3230 next_term = first_term;
3231 }
3232 }
3233}
3234
3235/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003236 * Fill one screen line from a line of the terminal.
3237 * Advances "pos" to past the last column.
3238 */
3239 static void
3240term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
3241{
3242 int off = screen_get_current_line_off();
3243
3244 for (pos->col = 0; pos->col < max_col; )
3245 {
3246 VTermScreenCell cell;
3247 int c;
3248
3249 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
3250 vim_memset(&cell, 0, sizeof(cell));
3251
3252 c = cell.chars[0];
3253 if (c == NUL)
3254 {
3255 ScreenLines[off] = ' ';
3256 if (enc_utf8)
3257 ScreenLinesUC[off] = NUL;
3258 }
3259 else
3260 {
3261 if (enc_utf8)
3262 {
3263 int i;
3264
3265 /* composing chars */
3266 for (i = 0; i < Screen_mco
3267 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3268 {
3269 ScreenLinesC[i][off] = cell.chars[i + 1];
3270 if (cell.chars[i + 1] == 0)
3271 break;
3272 }
3273 if (c >= 0x80 || (Screen_mco > 0
3274 && ScreenLinesC[0][off] != 0))
3275 {
3276 ScreenLines[off] = ' ';
3277 ScreenLinesUC[off] = c;
3278 }
3279 else
3280 {
3281 ScreenLines[off] = c;
3282 ScreenLinesUC[off] = NUL;
3283 }
3284 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003285#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003286 else if (has_mbyte && c >= 0x80)
3287 {
3288 char_u mb[MB_MAXBYTES+1];
3289 WCHAR wc = c;
3290
3291 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3292 (char*)mb, 2, 0, 0) > 1)
3293 {
3294 ScreenLines[off] = mb[0];
3295 ScreenLines[off + 1] = mb[1];
3296 cell.width = mb_ptr2cells(mb);
3297 }
3298 else
3299 ScreenLines[off] = c;
3300 }
3301#endif
3302 else
3303 ScreenLines[off] = c;
3304 }
3305 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3306
3307 ++pos->col;
3308 ++off;
3309 if (cell.width == 2)
3310 {
3311 if (enc_utf8)
3312 ScreenLinesUC[off] = NUL;
3313
3314 /* don't set the second byte to NUL for a DBCS encoding, it
3315 * has been set above */
3316 if (enc_utf8 || !has_mbyte)
3317 ScreenLines[off] = NUL;
3318
3319 ++pos->col;
3320 ++off;
3321 }
3322 }
3323}
3324
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003325#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003326 static void
3327update_system_term(term_T *term)
3328{
3329 VTermPos pos;
3330 VTermScreen *screen;
3331
3332 if (term->tl_vterm == NULL)
3333 return;
3334 screen = vterm_obtain_screen(term->tl_vterm);
3335
3336 /* Scroll up to make more room for terminal lines if needed. */
3337 while (term->tl_toprow > 0
3338 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3339 {
3340 int save_p_more = p_more;
3341
3342 p_more = FALSE;
3343 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003344 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003345 p_more = save_p_more;
3346 --term->tl_toprow;
3347 }
3348
3349 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3350 && pos.row < Rows; ++pos.row)
3351 {
3352 if (pos.row < term->tl_rows)
3353 {
3354 int max_col = MIN(Columns, term->tl_cols);
3355
3356 term_line2screenline(screen, &pos, max_col);
3357 }
3358 else
3359 pos.col = 0;
3360
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003361 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003362 }
3363
3364 term->tl_dirty_row_start = MAX_ROW;
3365 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003366}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003367#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003368
3369/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003370 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3371 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372 * Terminal-Normal mode.
3373 */
3374 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003375term_do_update_window(win_T *wp)
3376{
3377 term_T *term = wp->w_buffer->b_term;
3378
3379 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3380}
3381
3382/*
3383 * Called to update a window that contains an active terminal.
3384 */
3385 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003386term_update_window(win_T *wp)
3387{
3388 term_T *term = wp->w_buffer->b_term;
3389 VTerm *vterm;
3390 VTermScreen *screen;
3391 VTermState *state;
3392 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003393 int rows, cols;
3394 int newrows, newcols;
3395 int minsize;
3396 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003397
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003398 vterm = term->tl_vterm;
3399 screen = vterm_obtain_screen(vterm);
3400 state = vterm_obtain_state(vterm);
3401
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003402 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3403 * SOME_VALID only redraw what was marked dirty. */
3404 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003405 {
3406 term->tl_dirty_row_start = 0;
3407 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003408
3409 if (term->tl_postponed_scroll > 0
3410 && term->tl_postponed_scroll < term->tl_rows / 3)
3411 /* Scrolling is usually faster than redrawing, when there are only
3412 * a few lines to scroll. */
3413 term_scroll_up(term, 0, term->tl_postponed_scroll);
3414 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003415 }
3416
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003417 /*
3418 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003419 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003420 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003421 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003422
Bram Moolenaar498c2562018-04-15 23:45:15 +02003423 newrows = 99999;
3424 newcols = 99999;
3425 FOR_ALL_WINDOWS(twp)
3426 {
3427 /* When more than one window shows the same terminal, use the
3428 * smallest size. */
3429 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003430 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003431 newrows = MIN(newrows, twp->w_height);
3432 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003433 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003434 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003435 if (newrows == 99999 || newcols == 99999)
3436 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003437 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3438 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3439
3440 if (term->tl_rows != newrows || term->tl_cols != newcols)
3441 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003442 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003443 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003444 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003445 newrows);
3446 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003447
3448 // Updating the terminal size will cause the snapshot to be cleared.
3449 // When not in terminal_loop() we need to restore it.
3450 if (term != in_terminal_loop)
3451 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003452 }
3453
3454 /* The cursor may have been moved when resizing. */
3455 vterm_state_get_cursorpos(state, &pos);
3456 position_cursor(wp, &pos);
3457
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003458 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3459 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003460 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003461 if (pos.row < term->tl_rows)
3462 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003463 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003464
Bram Moolenaar13568252018-03-16 20:46:58 +01003465 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003466 }
3467 else
3468 pos.col = 0;
3469
Bram Moolenaarf118d482018-03-13 13:14:00 +01003470 screen_line(wp->w_winrow + pos.row
3471#ifdef FEAT_MENU
3472 + winbar_height(wp)
3473#endif
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003474 , wp->w_wincol, pos.col, wp->w_width, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003475 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003476 term->tl_dirty_row_start = MAX_ROW;
3477 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003478}
3479
3480/*
3481 * Return TRUE if "wp" is a terminal window where the job has finished.
3482 */
3483 int
3484term_is_finished(buf_T *buf)
3485{
3486 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3487}
3488
3489/*
3490 * Return TRUE if "wp" is a terminal window where the job has finished or we
3491 * are in Terminal-Normal mode, thus we show the buffer contents.
3492 */
3493 int
3494term_show_buffer(buf_T *buf)
3495{
3496 term_T *term = buf->b_term;
3497
3498 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3499}
3500
3501/*
3502 * The current buffer is going to be changed. If there is terminal
3503 * highlighting remove it now.
3504 */
3505 void
3506term_change_in_curbuf(void)
3507{
3508 term_T *term = curbuf->b_term;
3509
3510 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3511 {
3512 free_scrollback(term);
3513 redraw_buf_later(term->tl_buffer, NOT_VALID);
3514
3515 /* The buffer is now like a normal buffer, it cannot be easily
3516 * abandoned when changed. */
3517 set_string_option_direct((char_u *)"buftype", -1,
3518 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3519 }
3520}
3521
3522/*
3523 * Get the screen attribute for a position in the buffer.
3524 * Use a negative "col" to get the filler background color.
3525 */
3526 int
3527term_get_attr(buf_T *buf, linenr_T lnum, int col)
3528{
3529 term_T *term = buf->b_term;
3530 sb_line_T *line;
3531 cellattr_T *cellattr;
3532
3533 if (lnum > term->tl_scrollback.ga_len)
3534 cellattr = &term->tl_default_color;
3535 else
3536 {
3537 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3538 if (col < 0 || col >= line->sb_cols)
3539 cellattr = &line->sb_fill_attr;
3540 else
3541 cellattr = line->sb_cells + col;
3542 }
3543 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3544}
3545
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003546/*
3547 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003548 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003549 */
3550 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003551cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003552{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003553 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003554}
3555
3556/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003557 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003558 */
3559 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003560init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003561{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003562 VTermColor *fg, *bg;
3563 int fgval, bgval;
3564 int id;
3565
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003566 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3567 term->tl_default_color.width = 1;
3568 fg = &term->tl_default_color.fg;
3569 bg = &term->tl_default_color.bg;
3570
3571 /* Vterm uses a default black background. Set it to white when
3572 * 'background' is "light". */
3573 if (*p_bg == 'l')
3574 {
3575 fgval = 0;
3576 bgval = 255;
3577 }
3578 else
3579 {
3580 fgval = 255;
3581 bgval = 0;
3582 }
3583 fg->red = fg->green = fg->blue = fgval;
3584 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003585 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003586
3587 /* The "Terminal" highlight group overrules the defaults. */
3588 id = syn_name2id((char_u *)"Terminal");
3589
Bram Moolenaar46359e12017-11-29 22:33:38 +01003590 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003591#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3592 if (0
3593# ifdef FEAT_GUI
3594 || gui.in_use
3595# endif
3596# ifdef FEAT_TERMGUICOLORS
3597 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003598# ifdef FEAT_VTP
3599 /* Finally get INVALCOLOR on this execution path */
3600 || (!p_tgc && t_colors >= 256)
3601# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003602# endif
3603 )
3604 {
3605 guicolor_T fg_rgb = INVALCOLOR;
3606 guicolor_T bg_rgb = INVALCOLOR;
3607
3608 if (id != 0)
3609 syn_id2colors(id, &fg_rgb, &bg_rgb);
3610
3611# ifdef FEAT_GUI
3612 if (gui.in_use)
3613 {
3614 if (fg_rgb == INVALCOLOR)
3615 fg_rgb = gui.norm_pixel;
3616 if (bg_rgb == INVALCOLOR)
3617 bg_rgb = gui.back_pixel;
3618 }
3619# ifdef FEAT_TERMGUICOLORS
3620 else
3621# endif
3622# endif
3623# ifdef FEAT_TERMGUICOLORS
3624 {
3625 if (fg_rgb == INVALCOLOR)
3626 fg_rgb = cterm_normal_fg_gui_color;
3627 if (bg_rgb == INVALCOLOR)
3628 bg_rgb = cterm_normal_bg_gui_color;
3629 }
3630# endif
3631 if (fg_rgb != INVALCOLOR)
3632 {
3633 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3634
3635 fg->red = (unsigned)(rgb >> 16);
3636 fg->green = (unsigned)(rgb >> 8) & 255;
3637 fg->blue = (unsigned)rgb & 255;
3638 }
3639 if (bg_rgb != INVALCOLOR)
3640 {
3641 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3642
3643 bg->red = (unsigned)(rgb >> 16);
3644 bg->green = (unsigned)(rgb >> 8) & 255;
3645 bg->blue = (unsigned)rgb & 255;
3646 }
3647 }
3648 else
3649#endif
3650 if (id != 0 && t_colors >= 16)
3651 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003652 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003653 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003654 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003655 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003656 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003657 else
3658 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003659#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003660 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003661#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003662
3663 /* In an MS-Windows console we know the normal colors. */
3664 if (cterm_normal_fg_color > 0)
3665 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003666 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003667# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3668# ifdef VIMDLL
3669 if (!gui.in_use)
3670# endif
3671 {
3672 tmp = fg->red;
3673 fg->red = fg->blue;
3674 fg->blue = tmp;
3675 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003676# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003678# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003679 else
3680 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003681# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003682
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003683 if (cterm_normal_bg_color > 0)
3684 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003685 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003686# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3687# ifdef VIMDLL
3688 if (!gui.in_use)
3689# endif
3690 {
3691 tmp = fg->red;
3692 fg->red = fg->blue;
3693 fg->blue = tmp;
3694 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003695# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003696 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003697# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003698 else
3699 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003700# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003701 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003702}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003703
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003704#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3705/*
3706 * Set the 16 ANSI colors from array of RGB values
3707 */
3708 static void
3709set_vterm_palette(VTerm *vterm, long_u *rgb)
3710{
3711 int index = 0;
3712 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003713
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003714 for (; index < 16; index++)
3715 {
3716 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003717
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003718 color.red = (unsigned)(rgb[index] >> 16);
3719 color.green = (unsigned)(rgb[index] >> 8) & 255;
3720 color.blue = (unsigned)rgb[index] & 255;
3721 vterm_state_set_palette_color(state, index, &color);
3722 }
3723}
3724
3725/*
3726 * Set the ANSI color palette from a list of colors
3727 */
3728 static int
3729set_ansi_colors_list(VTerm *vterm, list_T *list)
3730{
3731 int n = 0;
3732 long_u rgb[16];
3733 listitem_T *li = list->lv_first;
3734
3735 for (; li != NULL && n < 16; li = li->li_next, n++)
3736 {
3737 char_u *color_name;
3738 guicolor_T guicolor;
3739
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003740 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003741 if (color_name == NULL)
3742 return FAIL;
3743
3744 guicolor = GUI_GET_COLOR(color_name);
3745 if (guicolor == INVALCOLOR)
3746 return FAIL;
3747
3748 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3749 }
3750
3751 if (n != 16 || li != NULL)
3752 return FAIL;
3753
3754 set_vterm_palette(vterm, rgb);
3755
3756 return OK;
3757}
3758
3759/*
3760 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3761 */
3762 static void
3763init_vterm_ansi_colors(VTerm *vterm)
3764{
3765 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3766
3767 if (var != NULL
3768 && (var->di_tv.v_type != VAR_LIST
3769 || var->di_tv.vval.v_list == NULL
3770 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003771 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003772}
3773#endif
3774
Bram Moolenaar52acb112018-03-18 19:20:22 +01003775/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003776 * Handles a "drop" command from the job in the terminal.
3777 * "item" is the file name, "item->li_next" may have options.
3778 */
3779 static void
3780handle_drop_command(listitem_T *item)
3781{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003782 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003783 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003784 int bufnr;
3785 win_T *wp;
3786 tabpage_T *tp;
3787 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003788 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003789
3790 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3791 FOR_ALL_TAB_WINDOWS(tp, wp)
3792 {
3793 if (wp->w_buffer->b_fnum == bufnr)
3794 {
3795 /* buffer is in a window already, go there */
3796 goto_tabpage_win(tp, wp);
3797 return;
3798 }
3799 }
3800
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003801 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003802
3803 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3804 && opt_item->li_tv.vval.v_dict != NULL)
3805 {
3806 dict_T *dict = opt_item->li_tv.vval.v_dict;
3807 char_u *p;
3808
Bram Moolenaar8f667172018-12-14 15:38:31 +01003809 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003810 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003811 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003812 if (p != NULL)
3813 {
3814 if (check_ff_value(p) == FAIL)
3815 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3816 else
3817 ea.force_ff = *p;
3818 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01003819 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003820 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01003821 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003822 if (p != NULL)
3823 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02003824 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003825 if (ea.cmd != NULL)
3826 {
3827 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3828 ea.force_enc = 11;
3829 tofree = ea.cmd;
3830 }
3831 }
3832
Bram Moolenaar8f667172018-12-14 15:38:31 +01003833 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003834 if (p != NULL)
3835 get_bad_opt(p, &ea);
3836
3837 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3838 ea.force_bin = FORCE_BIN;
3839 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3840 ea.force_bin = FORCE_BIN;
3841 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3842 ea.force_bin = FORCE_NOBIN;
3843 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3844 ea.force_bin = FORCE_NOBIN;
3845 }
3846
3847 /* open in new window, like ":split fname" */
3848 if (ea.cmd == NULL)
3849 ea.cmd = (char_u *)"split";
3850 ea.arg = fname;
3851 ea.cmdidx = CMD_split;
3852 ex_splitview(&ea);
3853
3854 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003855}
3856
3857/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003858 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
3859 */
3860 static int
3861is_permitted_term_api(char_u *func, char_u *pat)
3862{
3863 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
3864}
3865
3866/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003867 * Handles a function call from the job running in a terminal.
3868 * "item" is the function name, "item->li_next" has the arguments.
3869 */
3870 static void
3871handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3872{
3873 char_u *func;
3874 typval_T argvars[2];
3875 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003876 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003877
3878 if (item->li_next == NULL)
3879 {
3880 ch_log(channel, "Missing function arguments for call");
3881 return;
3882 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003883 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003884
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003885 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003886 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02003887 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003888 return;
3889 }
3890
3891 argvars[0].v_type = VAR_NUMBER;
3892 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3893 argvars[1] = item->li_next->li_tv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02003894 vim_memset(&funcexe, 0, sizeof(funcexe));
3895 funcexe.firstline = 1L;
3896 funcexe.lastline = 1L;
3897 funcexe.evaluate = TRUE;
3898 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003899 {
3900 clear_tv(&rettv);
3901 ch_log(channel, "Function %s called", func);
3902 }
3903 else
3904 ch_log(channel, "Calling function %s failed", func);
3905}
3906
3907/*
3908 * Called by libvterm when it cannot recognize an OSC sequence.
3909 * We recognize a terminal API command.
3910 */
3911 static int
3912parse_osc(const char *command, size_t cmdlen, void *user)
3913{
3914 term_T *term = (term_T *)user;
3915 js_read_T reader;
3916 typval_T tv;
3917 channel_T *channel = term->tl_job == NULL ? NULL
3918 : term->tl_job->jv_channel;
3919
3920 /* We recognize only OSC 5 1 ; {command} */
3921 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3922 return 0; /* not handled */
3923
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003924 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003925 if (reader.js_buf == NULL)
3926 return 1;
3927 reader.js_fill = NULL;
3928 reader.js_used = 0;
3929 if (json_decode(&reader, &tv, 0) == OK
3930 && tv.v_type == VAR_LIST
3931 && tv.vval.v_list != NULL)
3932 {
3933 listitem_T *item = tv.vval.v_list->lv_first;
3934
3935 if (item == NULL)
3936 ch_log(channel, "Missing command");
3937 else
3938 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01003939 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003940
Bram Moolenaara997b452018-04-17 23:24:06 +02003941 /* Make sure an invoked command doesn't delete the buffer (and the
3942 * terminal) under our fingers. */
3943 ++term->tl_buffer->b_locked;
3944
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003945 item = item->li_next;
3946 if (item == NULL)
3947 ch_log(channel, "Missing argument for %s", cmd);
3948 else if (STRCMP(cmd, "drop") == 0)
3949 handle_drop_command(item);
3950 else if (STRCMP(cmd, "call") == 0)
3951 handle_call_command(term, channel, item);
3952 else
3953 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003954 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003955 }
3956 }
3957 else
3958 ch_log(channel, "Invalid JSON received");
3959
3960 vim_free(reader.js_buf);
3961 clear_tv(&tv);
3962 return 1;
3963}
3964
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003965/*
3966 * Called by libvterm when it cannot recognize a CSI sequence.
3967 * We recognize the window position report.
3968 */
3969 static int
3970parse_csi(
3971 const char *leader UNUSED,
3972 const long args[],
3973 int argcount,
3974 const char *intermed UNUSED,
3975 char command,
3976 void *user)
3977{
3978 term_T *term = (term_T *)user;
3979 char buf[100];
3980 int len;
3981 int x = 0;
3982 int y = 0;
3983 win_T *wp;
3984
3985 // We recognize only CSI 13 t
3986 if (command != 't' || argcount != 1 || args[0] != 13)
3987 return 0; // not handled
3988
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003989 // When getting the window position is not possible or it fails it results
3990 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02003991#if defined(FEAT_GUI) \
3992 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
3993 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003994 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02003995#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02003996
3997 FOR_ALL_WINDOWS(wp)
3998 if (wp->w_buffer == term->tl_buffer)
3999 break;
4000 if (wp != NULL)
4001 {
4002#ifdef FEAT_GUI
4003 if (gui.in_use)
4004 {
4005 x += wp->w_wincol * gui.char_width;
4006 y += W_WINROW(wp) * gui.char_height;
4007 }
4008 else
4009#endif
4010 {
4011 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004012 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004013 x += wp->w_wincol * 7;
4014 y += W_WINROW(wp) * 10;
4015 }
4016 }
4017
4018 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4019 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4020 (char_u *)buf, len, NULL);
4021 return 1;
4022}
4023
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004024static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004025 NULL, // text
4026 NULL, // control
4027 NULL, // escape
4028 parse_csi, // csi
4029 parse_osc, // osc
4030 NULL, // dcs
4031 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004032};
4033
4034/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004035 * Use Vim's allocation functions for vterm so profiling works.
4036 */
4037 static void *
4038vterm_malloc(size_t size, void *data UNUSED)
4039{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004040 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004041}
4042
4043 static void
4044vterm_memfree(void *ptr, void *data UNUSED)
4045{
4046 vim_free(ptr);
4047}
4048
4049static VTermAllocatorFunctions vterm_allocator = {
4050 &vterm_malloc,
4051 &vterm_memfree
4052};
4053
4054/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004055 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004056 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004057 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004058 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004059create_vterm(term_T *term, int rows, int cols)
4060{
4061 VTerm *vterm;
4062 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004063 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004064 VTermValue value;
4065
Bram Moolenaar756ef112018-04-10 12:04:27 +02004066 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004067 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004068 if (vterm == NULL)
4069 return FAIL;
4070
4071 // Allocate screen and state here, so we can bail out if that fails.
4072 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004073 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004074 if (state == NULL || screen == NULL)
4075 {
4076 vterm_free(vterm);
4077 return FAIL;
4078 }
4079
Bram Moolenaar52acb112018-03-18 19:20:22 +01004080 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
4081 /* TODO: depends on 'encoding'. */
4082 vterm_set_utf8(vterm, 1);
4083
4084 init_default_colors(term);
4085
4086 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004087 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004088 &term->tl_default_color.fg,
4089 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004090
Bram Moolenaar9e587872019-05-13 20:27:23 +02004091 if (t_colors < 16)
4092 // Less than 16 colors: assume that bold means using a bright color for
4093 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004094 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4095
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004096 /* Required to initialize most things. */
4097 vterm_screen_reset(screen, 1 /* hard */);
4098
4099 /* Allow using alternate screen. */
4100 vterm_screen_enable_altscreen(screen, 1);
4101
4102 /* For unix do not use a blinking cursor. In an xterm this causes the
4103 * cursor to blink if it's blinking in the xterm.
4104 * For Windows we respect the system wide setting. */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004105#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106 if (GetCaretBlinkTime() == INFINITE)
4107 value.boolean = 0;
4108 else
4109 value.boolean = 1;
4110#else
4111 value.boolean = 0;
4112#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004113 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4114 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004115
4116 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004117}
4118
4119/*
4120 * Return the text to show for the buffer name and status.
4121 */
4122 char_u *
4123term_get_status_text(term_T *term)
4124{
4125 if (term->tl_status_text == NULL)
4126 {
4127 char_u *txt;
4128 size_t len;
4129
4130 if (term->tl_normal_mode)
4131 {
4132 if (term_job_running(term))
4133 txt = (char_u *)_("Terminal");
4134 else
4135 txt = (char_u *)_("Terminal-finished");
4136 }
4137 else if (term->tl_title != NULL)
4138 txt = term->tl_title;
4139 else if (term_none_open(term))
4140 txt = (char_u *)_("active");
4141 else if (term_job_running(term))
4142 txt = (char_u *)_("running");
4143 else
4144 txt = (char_u *)_("finished");
4145 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004146 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004147 if (term->tl_status_text != NULL)
4148 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4149 term->tl_buffer->b_fname, txt);
4150 }
4151 return term->tl_status_text;
4152}
4153
4154/*
4155 * Mark references in jobs of terminals.
4156 */
4157 int
4158set_ref_in_term(int copyID)
4159{
4160 int abort = FALSE;
4161 term_T *term;
4162 typval_T tv;
4163
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004164 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004165 if (term->tl_job != NULL)
4166 {
4167 tv.v_type = VAR_JOB;
4168 tv.vval.v_job = term->tl_job;
4169 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4170 }
4171 return abort;
4172}
4173
4174/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01004175 * Cache "Terminal" highlight group colors.
4176 */
4177 void
4178set_terminal_default_colors(int cterm_fg, int cterm_bg)
4179{
4180 term_default_cterm_fg = cterm_fg - 1;
4181 term_default_cterm_bg = cterm_bg - 1;
4182}
4183
4184/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004185 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004186 * Returns NULL when the buffer is not for a terminal window and logs a message
4187 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004188 */
4189 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004190term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004191{
4192 buf_T *buf;
4193
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004194 (void)tv_get_number(&argvars[0]); /* issue errmsg if type error */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004195 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004196 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004197 --emsg_off;
4198 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004199 {
4200 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004201 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004202 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004203 return buf;
4204}
4205
Bram Moolenaard96ff162018-02-18 22:13:29 +01004206 static int
4207same_color(VTermColor *a, VTermColor *b)
4208{
4209 return a->red == b->red
4210 && a->green == b->green
4211 && a->blue == b->blue
4212 && a->ansi_index == b->ansi_index;
4213}
4214
4215 static void
4216dump_term_color(FILE *fd, VTermColor *color)
4217{
4218 fprintf(fd, "%02x%02x%02x%d",
4219 (int)color->red, (int)color->green, (int)color->blue,
4220 (int)color->ansi_index);
4221}
4222
4223/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004224 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004225 *
4226 * Each screen cell in full is:
4227 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4228 * {characters} is a space for an empty cell
4229 * For a double-width character "+" is changed to "*" and the next cell is
4230 * skipped.
4231 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4232 * when "&" use the same as the previous cell.
4233 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4234 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4235 * {color-idx} is a number from 0 to 255
4236 *
4237 * Screen cell with same width, attributes and color as the previous one:
4238 * |{characters}
4239 *
4240 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4241 *
4242 * Repeating the previous screen cell:
4243 * @{count}
4244 */
4245 void
4246f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4247{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004248 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004249 term_T *term;
4250 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004251 int max_height = 0;
4252 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004253 stat_T st;
4254 FILE *fd;
4255 VTermPos pos;
4256 VTermScreen *screen;
4257 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004258 VTermState *state;
4259 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004260
4261 if (check_restricted() || check_secure())
4262 return;
4263 if (buf == NULL)
4264 return;
4265 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004266 if (term->tl_vterm == NULL)
4267 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004268 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004269 return;
4270 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004271
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004272 if (argvars[2].v_type != VAR_UNKNOWN)
4273 {
4274 dict_T *d;
4275
4276 if (argvars[2].v_type != VAR_DICT)
4277 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004278 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004279 return;
4280 }
4281 d = argvars[2].vval.v_dict;
4282 if (d != NULL)
4283 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004284 max_height = dict_get_number(d, (char_u *)"rows");
4285 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004286 }
4287 }
4288
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004289 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004290 if (fname == NULL)
4291 return;
4292 if (mch_stat((char *)fname, &st) >= 0)
4293 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004294 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004295 return;
4296 }
4297
Bram Moolenaard96ff162018-02-18 22:13:29 +01004298 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4299 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004300 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004301 return;
4302 }
4303
4304 vim_memset(&prev_cell, 0, sizeof(prev_cell));
4305
4306 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004307 state = vterm_obtain_state(term->tl_vterm);
4308 vterm_state_get_cursorpos(state, &cursor_pos);
4309
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004310 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4311 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004312 {
4313 int repeat = 0;
4314
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004315 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4316 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004317 {
4318 VTermScreenCell cell;
4319 int same_attr;
4320 int same_chars = TRUE;
4321 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004322 int is_cursor_pos = (pos.col == cursor_pos.col
4323 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004324
4325 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4326 vim_memset(&cell, 0, sizeof(cell));
4327
4328 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4329 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004330 int c = cell.chars[i];
4331 int pc = prev_cell.chars[i];
4332
4333 /* For the first character NUL is the same as space. */
4334 if (i == 0)
4335 {
4336 c = (c == NUL) ? ' ' : c;
4337 pc = (pc == NUL) ? ' ' : pc;
4338 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004339 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004340 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004341 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004342 break;
4343 }
4344 same_attr = vtermAttr2hl(cell.attrs)
4345 == vtermAttr2hl(prev_cell.attrs)
4346 && same_color(&cell.fg, &prev_cell.fg)
4347 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004348 if (same_chars && cell.width == prev_cell.width && same_attr
4349 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004350 {
4351 ++repeat;
4352 }
4353 else
4354 {
4355 if (repeat > 0)
4356 {
4357 fprintf(fd, "@%d", repeat);
4358 repeat = 0;
4359 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004360 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004361
4362 if (cell.chars[0] == NUL)
4363 fputs(" ", fd);
4364 else
4365 {
4366 char_u charbuf[10];
4367 int len;
4368
4369 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4370 && cell.chars[i] != NUL; ++i)
4371 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004372 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004373 fwrite(charbuf, len, 1, fd);
4374 }
4375 }
4376
4377 /* When only the characters differ we don't write anything, the
4378 * following "|", "@" or NL will indicate using the same
4379 * attributes. */
4380 if (cell.width != prev_cell.width || !same_attr)
4381 {
4382 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004383 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004384 else
4385 fputs("+", fd);
4386
4387 if (same_attr)
4388 {
4389 fputs("&", fd);
4390 }
4391 else
4392 {
4393 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4394 if (same_color(&cell.fg, &prev_cell.fg))
4395 fputs("&", fd);
4396 else
4397 {
4398 fputs("#", fd);
4399 dump_term_color(fd, &cell.fg);
4400 }
4401 if (same_color(&cell.bg, &prev_cell.bg))
4402 fputs("&", fd);
4403 else
4404 {
4405 fputs("#", fd);
4406 dump_term_color(fd, &cell.bg);
4407 }
4408 }
4409 }
4410
4411 prev_cell = cell;
4412 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004413
4414 if (cell.width == 2)
4415 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004416 }
4417 if (repeat > 0)
4418 fprintf(fd, "@%d", repeat);
4419 fputs("\n", fd);
4420 }
4421
4422 fclose(fd);
4423}
4424
4425/*
4426 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4427 */
4428 static void
4429dump_is_corrupt(garray_T *gap)
4430{
4431 ga_concat(gap, (char_u *)"CORRUPT");
4432}
4433
4434 static void
4435append_cell(garray_T *gap, cellattr_T *cell)
4436{
4437 if (ga_grow(gap, 1) == OK)
4438 {
4439 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4440 ++gap->ga_len;
4441 }
4442}
4443
4444/*
4445 * Read the dump file from "fd" and append lines to the current buffer.
4446 * Return the cell width of the longest line.
4447 */
4448 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004449read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004450{
4451 int c;
4452 garray_T ga_text;
4453 garray_T ga_cell;
4454 char_u *prev_char = NULL;
4455 int attr = 0;
4456 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004457 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004458 term_T *term = curbuf->b_term;
4459 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004460 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004461
4462 ga_init2(&ga_text, 1, 90);
4463 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4464 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004465 vim_memset(&empty_cell, 0, sizeof(empty_cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004466 cursor_pos->row = -1;
4467 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004468
4469 c = fgetc(fd);
4470 for (;;)
4471 {
4472 if (c == EOF)
4473 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004474 if (c == '\r')
4475 {
4476 // DOS line endings? Ignore.
4477 c = fgetc(fd);
4478 }
4479 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004480 {
4481 /* End of a line: append it to the buffer. */
4482 if (ga_text.ga_data == NULL)
4483 dump_is_corrupt(&ga_text);
4484 if (ga_grow(&term->tl_scrollback, 1) == OK)
4485 {
4486 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4487 + term->tl_scrollback.ga_len;
4488
4489 if (max_cells < ga_cell.ga_len)
4490 max_cells = ga_cell.ga_len;
4491 line->sb_cols = ga_cell.ga_len;
4492 line->sb_cells = ga_cell.ga_data;
4493 line->sb_fill_attr = term->tl_default_color;
4494 ++term->tl_scrollback.ga_len;
4495 ga_init(&ga_cell);
4496
4497 ga_append(&ga_text, NUL);
4498 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4499 ga_text.ga_len, FALSE);
4500 }
4501 else
4502 ga_clear(&ga_cell);
4503 ga_text.ga_len = 0;
4504
4505 c = fgetc(fd);
4506 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004507 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004508 {
4509 int prev_len = ga_text.ga_len;
4510
Bram Moolenaar9271d052018-02-25 21:39:46 +01004511 if (c == '>')
4512 {
4513 if (cursor_pos->row != -1)
4514 dump_is_corrupt(&ga_text); /* duplicate cursor */
4515 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4516 cursor_pos->col = ga_cell.ga_len;
4517 }
4518
Bram Moolenaard96ff162018-02-18 22:13:29 +01004519 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4520 c = fgetc(fd);
4521 if (c != EOF)
4522 ga_append(&ga_text, c);
4523 for (;;)
4524 {
4525 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004526 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004527 || c == EOF || c == '\n')
4528 break;
4529 ga_append(&ga_text, c);
4530 }
4531
4532 /* save the character for repeating it */
4533 vim_free(prev_char);
4534 if (ga_text.ga_data != NULL)
4535 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4536 ga_text.ga_len - prev_len);
4537
Bram Moolenaar9271d052018-02-25 21:39:46 +01004538 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004539 {
4540 /* use all attributes from previous cell */
4541 }
4542 else if (c == '+' || c == '*')
4543 {
4544 int is_bg;
4545
4546 cell.width = c == '+' ? 1 : 2;
4547
4548 c = fgetc(fd);
4549 if (c == '&')
4550 {
4551 /* use same attr as previous cell */
4552 c = fgetc(fd);
4553 }
4554 else if (isdigit(c))
4555 {
4556 /* get the decimal attribute */
4557 attr = 0;
4558 while (isdigit(c))
4559 {
4560 attr = attr * 10 + (c - '0');
4561 c = fgetc(fd);
4562 }
4563 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004564
4565 /* is_bg == 0: fg, is_bg == 1: bg */
4566 for (is_bg = 0; is_bg <= 1; ++is_bg)
4567 {
4568 if (c == '&')
4569 {
4570 /* use same color as previous cell */
4571 c = fgetc(fd);
4572 }
4573 else if (c == '#')
4574 {
4575 int red, green, blue, index = 0;
4576
4577 c = fgetc(fd);
4578 red = hex2nr(c);
4579 c = fgetc(fd);
4580 red = (red << 4) + hex2nr(c);
4581 c = fgetc(fd);
4582 green = hex2nr(c);
4583 c = fgetc(fd);
4584 green = (green << 4) + hex2nr(c);
4585 c = fgetc(fd);
4586 blue = hex2nr(c);
4587 c = fgetc(fd);
4588 blue = (blue << 4) + hex2nr(c);
4589 c = fgetc(fd);
4590 if (!isdigit(c))
4591 dump_is_corrupt(&ga_text);
4592 while (isdigit(c))
4593 {
4594 index = index * 10 + (c - '0');
4595 c = fgetc(fd);
4596 }
4597
4598 if (is_bg)
4599 {
4600 cell.bg.red = red;
4601 cell.bg.green = green;
4602 cell.bg.blue = blue;
4603 cell.bg.ansi_index = index;
4604 }
4605 else
4606 {
4607 cell.fg.red = red;
4608 cell.fg.green = green;
4609 cell.fg.blue = blue;
4610 cell.fg.ansi_index = index;
4611 }
4612 }
4613 else
4614 dump_is_corrupt(&ga_text);
4615 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004616 }
4617 else
4618 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004619 }
4620 else
4621 dump_is_corrupt(&ga_text);
4622
4623 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004624 if (cell.width == 2)
4625 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004626 }
4627 else if (c == '@')
4628 {
4629 if (prev_char == NULL)
4630 dump_is_corrupt(&ga_text);
4631 else
4632 {
4633 int count = 0;
4634
4635 /* repeat previous character, get the count */
4636 for (;;)
4637 {
4638 c = fgetc(fd);
4639 if (!isdigit(c))
4640 break;
4641 count = count * 10 + (c - '0');
4642 }
4643
4644 while (count-- > 0)
4645 {
4646 ga_concat(&ga_text, prev_char);
4647 append_cell(&ga_cell, &cell);
4648 }
4649 }
4650 }
4651 else
4652 {
4653 dump_is_corrupt(&ga_text);
4654 c = fgetc(fd);
4655 }
4656 }
4657
4658 if (ga_text.ga_len > 0)
4659 {
4660 /* trailing characters after last NL */
4661 dump_is_corrupt(&ga_text);
4662 ga_append(&ga_text, NUL);
4663 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4664 ga_text.ga_len, FALSE);
4665 }
4666
4667 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004668 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004669 vim_free(prev_char);
4670
4671 return max_cells;
4672}
4673
4674/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004675 * Return an allocated string with at least "text_width" "=" characters and
4676 * "fname" inserted in the middle.
4677 */
4678 static char_u *
4679get_separator(int text_width, char_u *fname)
4680{
4681 int width = MAX(text_width, curwin->w_width);
4682 char_u *textline;
4683 int fname_size;
4684 char_u *p = fname;
4685 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004686 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004687
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004688 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004689 if (textline == NULL)
4690 return NULL;
4691
4692 fname_size = vim_strsize(fname);
4693 if (fname_size < width - 8)
4694 {
4695 /* enough room, don't use the full window width */
4696 width = MAX(text_width, fname_size + 8);
4697 }
4698 else if (fname_size > width - 8)
4699 {
4700 /* full name doesn't fit, use only the tail */
4701 p = gettail(fname);
4702 fname_size = vim_strsize(p);
4703 }
4704 /* skip characters until the name fits */
4705 while (fname_size > width - 8)
4706 {
4707 p += (*mb_ptr2len)(p);
4708 fname_size = vim_strsize(p);
4709 }
4710
4711 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4712 textline[i] = '=';
4713 textline[i++] = ' ';
4714
4715 STRCPY(textline + i, p);
4716 off = STRLEN(textline);
4717 textline[off] = ' ';
4718 for (i = 1; i < (width - fname_size) / 2; ++i)
4719 textline[off + i] = '=';
4720 textline[off + i] = NUL;
4721
4722 return textline;
4723}
4724
4725/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004726 * Common for "term_dumpdiff()" and "term_dumpload()".
4727 */
4728 static void
4729term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4730{
4731 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02004732 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004733 char_u buf1[NUMBUFLEN];
4734 char_u buf2[NUMBUFLEN];
4735 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004736 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004737 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004738 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004739 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004740 char_u *textline = NULL;
4741
4742 /* First open the files. If this fails bail out. */
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004743 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004744 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004745 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004746 if (fname1 == NULL || (do_diff && fname2 == NULL))
4747 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004748 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01004749 return;
4750 }
4751 fd1 = mch_fopen((char *)fname1, READBIN);
4752 if (fd1 == NULL)
4753 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004754 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004755 return;
4756 }
4757 if (do_diff)
4758 {
4759 fd2 = mch_fopen((char *)fname2, READBIN);
4760 if (fd2 == NULL)
4761 {
4762 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004763 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004764 return;
4765 }
4766 }
4767
4768 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004769 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4770 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4771 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4772 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4773 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004774
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004775 if (opt.jo_term_name == NULL)
4776 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004777 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004778
Bram Moolenaar51e14382019-05-25 20:21:28 +02004779 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004780 if (fname_tofree != NULL)
4781 {
4782 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4783 opt.jo_term_name = fname_tofree;
4784 }
4785 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004786
Bram Moolenaar87abab92019-06-03 21:14:59 +02004787 if (opt.jo_bufnr_buf != NULL)
4788 {
4789 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
4790
4791 // With "bufnr" argument: enter the window with this buffer and make it
4792 // empty.
4793 if (wp == NULL)
4794 semsg(_(e_invarg2), "bufnr");
4795 else
4796 {
4797 buf = curbuf;
4798 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
4799 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02004800 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02004801 redraw_later(NOT_VALID);
4802 }
4803 }
4804 else
4805 // Create a new terminal window.
4806 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
4807
Bram Moolenaard96ff162018-02-18 22:13:29 +01004808 if (buf != NULL && buf->b_term != NULL)
4809 {
4810 int i;
4811 linenr_T bot_lnum;
4812 linenr_T lnum;
4813 term_T *term = buf->b_term;
4814 int width;
4815 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004816 VTermPos cursor_pos1;
4817 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004818
Bram Moolenaar52acb112018-03-18 19:20:22 +01004819 init_default_colors(term);
4820
Bram Moolenaard96ff162018-02-18 22:13:29 +01004821 rettv->vval.v_number = buf->b_fnum;
4822
4823 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004824 width = read_dump_file(fd1, &cursor_pos1);
4825
4826 /* position the cursor */
4827 if (cursor_pos1.row >= 0)
4828 {
4829 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4830 coladvance(cursor_pos1.col);
4831 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004832
4833 /* Delete the empty line that was in the empty buffer. */
4834 ml_delete(1, FALSE);
4835
4836 /* For term_dumpload() we are done here. */
4837 if (!do_diff)
4838 goto theend;
4839
4840 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4841
Bram Moolenaar4a696342018-04-05 18:45:26 +02004842 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004843 if (textline == NULL)
4844 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004845 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4846 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4847 vim_free(textline);
4848
4849 textline = get_separator(width, fname2);
4850 if (textline == NULL)
4851 goto theend;
4852 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4853 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004854 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004855
4856 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004857 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004858 if (width2 > width)
4859 {
4860 vim_free(textline);
4861 textline = alloc(width2 + 1);
4862 if (textline == NULL)
4863 goto theend;
4864 width = width2;
4865 textline[width] = NUL;
4866 }
4867 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4868
4869 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4870 {
4871 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4872 {
4873 /* bottom part has fewer rows, fill with "-" */
4874 for (i = 0; i < width; ++i)
4875 textline[i] = '-';
4876 }
4877 else
4878 {
4879 char_u *line1;
4880 char_u *line2;
4881 char_u *p1;
4882 char_u *p2;
4883 int col;
4884 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4885 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4886 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4887 ->sb_cells;
4888
4889 /* Make a copy, getting the second line will invalidate it. */
4890 line1 = vim_strsave(ml_get(lnum));
4891 if (line1 == NULL)
4892 break;
4893 p1 = line1;
4894
4895 line2 = ml_get(lnum + bot_lnum);
4896 p2 = line2;
4897 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4898 {
4899 int len1 = utfc_ptr2len(p1);
4900 int len2 = utfc_ptr2len(p2);
4901
4902 textline[col] = ' ';
4903 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004904 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004905 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004906 else if (lnum == cursor_pos1.row + 1
4907 && col == cursor_pos1.col
4908 && (cursor_pos1.row != cursor_pos2.row
4909 || cursor_pos1.col != cursor_pos2.col))
4910 /* cursor in first but not in second */
4911 textline[col] = '>';
4912 else if (lnum == cursor_pos2.row + 1
4913 && col == cursor_pos2.col
4914 && (cursor_pos1.row != cursor_pos2.row
4915 || cursor_pos1.col != cursor_pos2.col))
4916 /* cursor in second but not in first */
4917 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004918 else if (cellattr1 != NULL && cellattr2 != NULL)
4919 {
4920 if ((cellattr1 + col)->width
4921 != (cellattr2 + col)->width)
4922 textline[col] = 'w';
4923 else if (!same_color(&(cellattr1 + col)->fg,
4924 &(cellattr2 + col)->fg))
4925 textline[col] = 'f';
4926 else if (!same_color(&(cellattr1 + col)->bg,
4927 &(cellattr2 + col)->bg))
4928 textline[col] = 'b';
4929 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4930 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4931 textline[col] = 'a';
4932 }
4933 p1 += len1;
4934 p2 += len2;
4935 /* TODO: handle different width */
4936 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004937
4938 while (col < width)
4939 {
4940 if (*p1 == NUL && *p2 == NUL)
4941 textline[col] = '?';
4942 else if (*p1 == NUL)
4943 {
4944 textline[col] = '+';
4945 p2 += utfc_ptr2len(p2);
4946 }
4947 else
4948 {
4949 textline[col] = '-';
4950 p1 += utfc_ptr2len(p1);
4951 }
4952 ++col;
4953 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01004954
4955 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004956 }
4957 if (add_empty_scrollback(term, &term->tl_default_color,
4958 term->tl_top_diff_rows) == OK)
4959 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4960 ++bot_lnum;
4961 }
4962
4963 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4964 {
4965 /* bottom part has more rows, fill with "+" */
4966 for (i = 0; i < width; ++i)
4967 textline[i] = '+';
4968 if (add_empty_scrollback(term, &term->tl_default_color,
4969 term->tl_top_diff_rows) == OK)
4970 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4971 ++lnum;
4972 ++bot_lnum;
4973 }
4974
4975 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004976
4977 /* looks better without wrapping */
4978 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004979 }
4980
4981theend:
4982 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004983 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004984 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004985 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004986 fclose(fd2);
4987}
4988
4989/*
4990 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4991 * bottom files.
4992 * Return FAIL when this is not possible.
4993 */
4994 int
4995term_swap_diff()
4996{
4997 term_T *term = curbuf->b_term;
4998 linenr_T line_count;
4999 linenr_T top_rows;
5000 linenr_T bot_rows;
5001 linenr_T bot_start;
5002 linenr_T lnum;
5003 char_u *p;
5004 sb_line_T *sb_line;
5005
5006 if (term == NULL
5007 || !term_is_finished(curbuf)
5008 || term->tl_top_diff_rows == 0
5009 || term->tl_scrollback.ga_len == 0)
5010 return FAIL;
5011
5012 line_count = curbuf->b_ml.ml_line_count;
5013 top_rows = term->tl_top_diff_rows;
5014 bot_rows = term->tl_bot_diff_rows;
5015 bot_start = line_count - bot_rows;
5016 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5017
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005018 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005019 for (lnum = 1; lnum <= top_rows; ++lnum)
5020 {
5021 p = vim_strsave(ml_get(1));
5022 if (p == NULL)
5023 return OK;
5024 ml_append(bot_start, p, 0, FALSE);
5025 ml_delete(1, FALSE);
5026 vim_free(p);
5027 }
5028
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005029 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005030 for (lnum = 1; lnum <= bot_rows; ++lnum)
5031 {
5032 p = vim_strsave(ml_get(bot_start + lnum));
5033 if (p == NULL)
5034 return OK;
5035 ml_delete(bot_start + lnum, FALSE);
5036 ml_append(lnum - 1, p, 0, FALSE);
5037 vim_free(p);
5038 }
5039
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005040 // move top title to bottom
5041 p = vim_strsave(ml_get(bot_rows + 1));
5042 if (p == NULL)
5043 return OK;
5044 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5045 ml_delete(bot_rows + 1, FALSE);
5046 vim_free(p);
5047
5048 // move bottom title to top
5049 p = vim_strsave(ml_get(line_count - top_rows));
5050 if (p == NULL)
5051 return OK;
5052 ml_delete(line_count - top_rows, FALSE);
5053 ml_append(bot_rows, p, 0, FALSE);
5054 vim_free(p);
5055
Bram Moolenaard96ff162018-02-18 22:13:29 +01005056 if (top_rows == bot_rows)
5057 {
5058 /* rows counts are equal, can swap cell properties */
5059 for (lnum = 0; lnum < top_rows; ++lnum)
5060 {
5061 sb_line_T temp;
5062
5063 temp = *(sb_line + lnum);
5064 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5065 *(sb_line + bot_start + lnum) = temp;
5066 }
5067 }
5068 else
5069 {
5070 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005071 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005072
5073 /* need to copy cell properties into temp memory */
5074 if (temp != NULL)
5075 {
5076 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5077 mch_memmove(term->tl_scrollback.ga_data,
5078 temp + bot_start,
5079 sizeof(sb_line_T) * bot_rows);
5080 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5081 temp + top_rows,
5082 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5083 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5084 + line_count - top_rows,
5085 temp,
5086 sizeof(sb_line_T) * top_rows);
5087 vim_free(temp);
5088 }
5089 }
5090
5091 term->tl_top_diff_rows = bot_rows;
5092 term->tl_bot_diff_rows = top_rows;
5093
5094 update_screen(NOT_VALID);
5095 return OK;
5096}
5097
5098/*
5099 * "term_dumpdiff(filename, filename, options)" function
5100 */
5101 void
5102f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5103{
5104 term_load_dump(argvars, rettv, TRUE);
5105}
5106
5107/*
5108 * "term_dumpload(filename, options)" function
5109 */
5110 void
5111f_term_dumpload(typval_T *argvars, typval_T *rettv)
5112{
5113 term_load_dump(argvars, rettv, FALSE);
5114}
5115
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005116/*
5117 * "term_getaltscreen(buf)" function
5118 */
5119 void
5120f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5121{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005122 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005123
5124 if (buf == NULL)
5125 return;
5126 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5127}
5128
5129/*
5130 * "term_getattr(attr, name)" function
5131 */
5132 void
5133f_term_getattr(typval_T *argvars, typval_T *rettv)
5134{
5135 int attr;
5136 size_t i;
5137 char_u *name;
5138
5139 static struct {
5140 char *name;
5141 int attr;
5142 } attrs[] = {
5143 {"bold", HL_BOLD},
5144 {"italic", HL_ITALIC},
5145 {"underline", HL_UNDERLINE},
5146 {"strike", HL_STRIKETHROUGH},
5147 {"reverse", HL_INVERSE},
5148 };
5149
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005150 attr = tv_get_number(&argvars[0]);
5151 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005152 if (name == NULL)
5153 return;
5154
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005155 if (attr > HL_ALL)
5156 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005157 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5158 if (STRCMP(name, attrs[i].name) == 0)
5159 {
5160 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5161 break;
5162 }
5163}
5164
5165/*
5166 * "term_getcursor(buf)" function
5167 */
5168 void
5169f_term_getcursor(typval_T *argvars, typval_T *rettv)
5170{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005171 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005172 term_T *term;
5173 list_T *l;
5174 dict_T *d;
5175
5176 if (rettv_list_alloc(rettv) == FAIL)
5177 return;
5178 if (buf == NULL)
5179 return;
5180 term = buf->b_term;
5181
5182 l = rettv->vval.v_list;
5183 list_append_number(l, term->tl_cursor_pos.row + 1);
5184 list_append_number(l, term->tl_cursor_pos.col + 1);
5185
5186 d = dict_alloc();
5187 if (d != NULL)
5188 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005189 dict_add_number(d, "visible", term->tl_cursor_visible);
5190 dict_add_number(d, "blink", blink_state_is_inverted()
5191 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5192 dict_add_number(d, "shape", term->tl_cursor_shape);
5193 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005194 list_append_dict(l, d);
5195 }
5196}
5197
5198/*
5199 * "term_getjob(buf)" function
5200 */
5201 void
5202f_term_getjob(typval_T *argvars, typval_T *rettv)
5203{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005204 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005205
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005206 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005207 {
5208 rettv->v_type = VAR_SPECIAL;
5209 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005210 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005211 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005212
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005213 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005214 rettv->vval.v_job = buf->b_term->tl_job;
5215 if (rettv->vval.v_job != NULL)
5216 ++rettv->vval.v_job->jv_refcount;
5217}
5218
5219 static int
5220get_row_number(typval_T *tv, term_T *term)
5221{
5222 if (tv->v_type == VAR_STRING
5223 && tv->vval.v_string != NULL
5224 && STRCMP(tv->vval.v_string, ".") == 0)
5225 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005226 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005227}
5228
5229/*
5230 * "term_getline(buf, row)" function
5231 */
5232 void
5233f_term_getline(typval_T *argvars, typval_T *rettv)
5234{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005235 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005236 term_T *term;
5237 int row;
5238
5239 rettv->v_type = VAR_STRING;
5240 if (buf == NULL)
5241 return;
5242 term = buf->b_term;
5243 row = get_row_number(&argvars[1], term);
5244
5245 if (term->tl_vterm == NULL)
5246 {
5247 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5248
5249 /* vterm is finished, get the text from the buffer */
5250 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5251 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5252 }
5253 else
5254 {
5255 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5256 VTermRect rect;
5257 int len;
5258 char_u *p;
5259
5260 if (row < 0 || row >= term->tl_rows)
5261 return;
5262 len = term->tl_cols * MB_MAXBYTES + 1;
5263 p = alloc(len);
5264 if (p == NULL)
5265 return;
5266 rettv->vval.v_string = p;
5267
5268 rect.start_col = 0;
5269 rect.end_col = term->tl_cols;
5270 rect.start_row = row;
5271 rect.end_row = row + 1;
5272 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5273 }
5274}
5275
5276/*
5277 * "term_getscrolled(buf)" function
5278 */
5279 void
5280f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5281{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005282 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005283
5284 if (buf == NULL)
5285 return;
5286 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5287}
5288
5289/*
5290 * "term_getsize(buf)" function
5291 */
5292 void
5293f_term_getsize(typval_T *argvars, typval_T *rettv)
5294{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005295 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005296 list_T *l;
5297
5298 if (rettv_list_alloc(rettv) == FAIL)
5299 return;
5300 if (buf == NULL)
5301 return;
5302
5303 l = rettv->vval.v_list;
5304 list_append_number(l, buf->b_term->tl_rows);
5305 list_append_number(l, buf->b_term->tl_cols);
5306}
5307
5308/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005309 * "term_setsize(buf, rows, cols)" function
5310 */
5311 void
5312f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5313{
5314 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5315 term_T *term;
5316 varnumber_T rows, cols;
5317
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005318 if (buf == NULL)
5319 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005320 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005321 return;
5322 }
5323 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005324 return;
5325 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005326 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005327 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005328 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005329 cols = cols <= 0 ? term->tl_cols : cols;
5330 vterm_set_size(term->tl_vterm, rows, cols);
5331 /* handle_resize() will resize the windows */
5332
5333 /* Get and remember the size we ended up with. Update the pty. */
5334 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5335 term_report_winsize(term, term->tl_rows, term->tl_cols);
5336}
5337
5338/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005339 * "term_getstatus(buf)" function
5340 */
5341 void
5342f_term_getstatus(typval_T *argvars, typval_T *rettv)
5343{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005344 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005345 term_T *term;
5346 char_u val[100];
5347
5348 rettv->v_type = VAR_STRING;
5349 if (buf == NULL)
5350 return;
5351 term = buf->b_term;
5352
5353 if (term_job_running(term))
5354 STRCPY(val, "running");
5355 else
5356 STRCPY(val, "finished");
5357 if (term->tl_normal_mode)
5358 STRCAT(val, ",normal");
5359 rettv->vval.v_string = vim_strsave(val);
5360}
5361
5362/*
5363 * "term_gettitle(buf)" function
5364 */
5365 void
5366f_term_gettitle(typval_T *argvars, typval_T *rettv)
5367{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005368 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005369
5370 rettv->v_type = VAR_STRING;
5371 if (buf == NULL)
5372 return;
5373
5374 if (buf->b_term->tl_title != NULL)
5375 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5376}
5377
5378/*
5379 * "term_gettty(buf)" function
5380 */
5381 void
5382f_term_gettty(typval_T *argvars, typval_T *rettv)
5383{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005384 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005385 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005386 int num = 0;
5387
5388 rettv->v_type = VAR_STRING;
5389 if (buf == NULL)
5390 return;
5391 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005392 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005393
5394 switch (num)
5395 {
5396 case 0:
5397 if (buf->b_term->tl_job != NULL)
5398 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005399 break;
5400 case 1:
5401 if (buf->b_term->tl_job != NULL)
5402 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005403 break;
5404 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005405 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005406 return;
5407 }
5408 if (p != NULL)
5409 rettv->vval.v_string = vim_strsave(p);
5410}
5411
5412/*
5413 * "term_list()" function
5414 */
5415 void
5416f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5417{
5418 term_T *tp;
5419 list_T *l;
5420
5421 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5422 return;
5423
5424 l = rettv->vval.v_list;
5425 for (tp = first_term; tp != NULL; tp = tp->tl_next)
5426 if (tp != NULL && tp->tl_buffer != NULL)
5427 if (list_append_number(l,
5428 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5429 return;
5430}
5431
5432/*
5433 * "term_scrape(buf, row)" function
5434 */
5435 void
5436f_term_scrape(typval_T *argvars, typval_T *rettv)
5437{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005438 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005439 VTermScreen *screen = NULL;
5440 VTermPos pos;
5441 list_T *l;
5442 term_T *term;
5443 char_u *p;
5444 sb_line_T *line;
5445
5446 if (rettv_list_alloc(rettv) == FAIL)
5447 return;
5448 if (buf == NULL)
5449 return;
5450 term = buf->b_term;
5451
5452 l = rettv->vval.v_list;
5453 pos.row = get_row_number(&argvars[1], term);
5454
5455 if (term->tl_vterm != NULL)
5456 {
5457 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005458 if (screen == NULL) // can't really happen
5459 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005460 p = NULL;
5461 line = NULL;
5462 }
5463 else
5464 {
5465 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5466
5467 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5468 return;
5469 p = ml_get_buf(buf, lnum + 1, FALSE);
5470 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5471 }
5472
5473 for (pos.col = 0; pos.col < term->tl_cols; )
5474 {
5475 dict_T *dcell;
5476 int width;
5477 VTermScreenCellAttrs attrs;
5478 VTermColor fg, bg;
5479 char_u rgb[8];
5480 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5481 int off = 0;
5482 int i;
5483
5484 if (screen == NULL)
5485 {
5486 cellattr_T *cellattr;
5487 int len;
5488
5489 /* vterm has finished, get the cell from scrollback */
5490 if (pos.col >= line->sb_cols)
5491 break;
5492 cellattr = line->sb_cells + pos.col;
5493 width = cellattr->width;
5494 attrs = cellattr->attrs;
5495 fg = cellattr->fg;
5496 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005497 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005498 mch_memmove(mbs, p, len);
5499 mbs[len] = NUL;
5500 p += len;
5501 }
5502 else
5503 {
5504 VTermScreenCell cell;
5505 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5506 break;
5507 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5508 {
5509 if (cell.chars[i] == 0)
5510 break;
5511 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5512 }
5513 mbs[off] = NUL;
5514 width = cell.width;
5515 attrs = cell.attrs;
5516 fg = cell.fg;
5517 bg = cell.bg;
5518 }
5519 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005520 if (dcell == NULL)
5521 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005522 list_append_dict(l, dcell);
5523
Bram Moolenaare0be1672018-07-08 16:50:37 +02005524 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005525
5526 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5527 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005528 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005529 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5530 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005531 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005532
Bram Moolenaare0be1672018-07-08 16:50:37 +02005533 dict_add_number(dcell, "attr", cell2attr(attrs, fg, bg));
5534 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005535
5536 ++pos.col;
5537 if (width == 2)
5538 ++pos.col;
5539 }
5540}
5541
5542/*
5543 * "term_sendkeys(buf, keys)" function
5544 */
5545 void
5546f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5547{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005548 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005549 char_u *msg;
5550 term_T *term;
5551
5552 rettv->v_type = VAR_UNKNOWN;
5553 if (buf == NULL)
5554 return;
5555
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005556 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005557 if (msg == NULL)
5558 return;
5559 term = buf->b_term;
5560 if (term->tl_vterm == NULL)
5561 return;
5562
5563 while (*msg != NUL)
5564 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005565 int c;
5566
5567 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5568 {
5569 c = TO_SPECIAL(msg[1], msg[2]);
5570 msg += 3;
5571 }
5572 else
5573 {
5574 c = PTR2CHAR(msg);
5575 msg += MB_CPTR2LEN(msg);
5576 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005577 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005578 }
5579}
5580
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005581#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5582/*
5583 * "term_getansicolors(buf)" function
5584 */
5585 void
5586f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5587{
5588 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5589 term_T *term;
5590 VTermState *state;
5591 VTermColor color;
5592 char_u hexbuf[10];
5593 int index;
5594 list_T *list;
5595
5596 if (rettv_list_alloc(rettv) == FAIL)
5597 return;
5598
5599 if (buf == NULL)
5600 return;
5601 term = buf->b_term;
5602 if (term->tl_vterm == NULL)
5603 return;
5604
5605 list = rettv->vval.v_list;
5606 state = vterm_obtain_state(term->tl_vterm);
5607 for (index = 0; index < 16; index++)
5608 {
5609 vterm_state_get_palette_color(state, index, &color);
5610 sprintf((char *)hexbuf, "#%02x%02x%02x",
5611 color.red, color.green, color.blue);
5612 if (list_append_string(list, hexbuf, 7) == FAIL)
5613 return;
5614 }
5615}
5616
5617/*
5618 * "term_setansicolors(buf, list)" function
5619 */
5620 void
5621f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5622{
5623 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5624 term_T *term;
5625
5626 if (buf == NULL)
5627 return;
5628 term = buf->b_term;
5629 if (term->tl_vterm == NULL)
5630 return;
5631
5632 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5633 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005634 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005635 return;
5636 }
5637
5638 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005639 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005640}
5641#endif
5642
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005643/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005644 * "term_setapi(buf, api)" function
5645 */
5646 void
5647f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5648{
5649 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5650 term_T *term;
5651 char_u *api;
5652
5653 if (buf == NULL)
5654 return;
5655 term = buf->b_term;
5656 vim_free(term->tl_api);
5657 api = tv_get_string_chk(&argvars[1]);
5658 if (api != NULL)
5659 term->tl_api = vim_strsave(api);
5660 else
5661 term->tl_api = NULL;
5662}
5663
5664/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005665 * "term_setrestore(buf, command)" function
5666 */
5667 void
5668f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5669{
5670#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005671 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005672 term_T *term;
5673 char_u *cmd;
5674
5675 if (buf == NULL)
5676 return;
5677 term = buf->b_term;
5678 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005679 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005680 if (cmd != NULL)
5681 term->tl_command = vim_strsave(cmd);
5682 else
5683 term->tl_command = NULL;
5684#endif
5685}
5686
5687/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005688 * "term_setkill(buf, how)" function
5689 */
5690 void
5691f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5692{
5693 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5694 term_T *term;
5695 char_u *how;
5696
5697 if (buf == NULL)
5698 return;
5699 term = buf->b_term;
5700 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005701 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005702 if (how != NULL)
5703 term->tl_kill = vim_strsave(how);
5704 else
5705 term->tl_kill = NULL;
5706}
5707
5708/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005709 * "term_start(command, options)" function
5710 */
5711 void
5712f_term_start(typval_T *argvars, typval_T *rettv)
5713{
5714 jobopt_T opt;
5715 buf_T *buf;
5716
5717 init_job_options(&opt);
5718 if (argvars[1].v_type != VAR_UNKNOWN
5719 && get_job_options(&argvars[1], &opt,
5720 JO_TIMEOUT_ALL + JO_STOPONEXIT
5721 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5722 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5723 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5724 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005725 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005726 + JO2_NORESTORE + JO2_TERM_KILL
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005727 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005728 return;
5729
Bram Moolenaar13568252018-03-16 20:46:58 +01005730 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005731
5732 if (buf != NULL && buf->b_term != NULL)
5733 rettv->vval.v_number = buf->b_fnum;
5734}
5735
5736/*
5737 * "term_wait" function
5738 */
5739 void
5740f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5741{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005742 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005743
5744 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005745 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005746 if (buf->b_term->tl_job == NULL)
5747 {
5748 ch_log(NULL, "term_wait(): no job to wait for");
5749 return;
5750 }
5751 if (buf->b_term->tl_job->jv_channel == NULL)
5752 /* channel is closed, nothing to do */
5753 return;
5754
5755 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005756 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005757 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5758 {
5759 /* The job is dead, keep reading channel I/O until the channel is
5760 * closed. buf->b_term may become NULL if the terminal was closed while
5761 * waiting. */
5762 ch_log(NULL, "term_wait(): waiting for channel to close");
5763 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5764 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005765 term_flush_messages();
5766
Bram Moolenaard45aa552018-05-21 22:50:29 +02005767 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01005768 if (!buf_valid(buf))
5769 /* If the terminal is closed when the channel is closed the
5770 * buffer disappears. */
5771 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005772 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005773
5774 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005775 }
5776 else
5777 {
5778 long wait = 10L;
5779
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005780 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005781
5782 /* Wait for some time for any channel I/O. */
5783 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005784 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005785 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005786
5787 /* Flushing messages on channels is hopefully sufficient.
5788 * TODO: is there a better way? */
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02005789 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005790 }
5791}
5792
5793/*
5794 * Called when a channel has sent all the lines to a terminal.
5795 * Send a CTRL-D to mark the end of the text.
5796 */
5797 void
5798term_send_eof(channel_T *ch)
5799{
5800 term_T *term;
5801
5802 for (term = first_term; term != NULL; term = term->tl_next)
5803 if (term->tl_job == ch->ch_job)
5804 {
5805 if (term->tl_eof_chars != NULL)
5806 {
5807 channel_send(ch, PART_IN, term->tl_eof_chars,
5808 (int)STRLEN(term->tl_eof_chars), NULL);
5809 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5810 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01005811# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005812 else
5813 /* Default: CTRL-D */
5814 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5815# endif
5816 }
5817}
5818
Bram Moolenaar113e1072019-01-20 15:30:40 +01005819#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005820 job_T *
5821term_getjob(term_T *term)
5822{
5823 return term != NULL ? term->tl_job : NULL;
5824}
Bram Moolenaar113e1072019-01-20 15:30:40 +01005825#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02005826
Bram Moolenaar4f974752019-02-17 17:44:42 +01005827# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005828
5829/**************************************
5830 * 2. MS-Windows implementation.
5831 */
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005832#ifdef PROTO
5833typedef int COORD;
5834typedef int DWORD;
5835typedef int HANDLE;
5836typedef int *DWORD_PTR;
5837typedef int HPCON;
5838typedef int HRESULT;
5839typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02005840typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005841typedef int PSIZE_T;
5842typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005843typedef int BOOL;
5844# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02005845#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005846
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005847HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
5848HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
5849HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01005850BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
5851BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
5852void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005853
5854 static int
5855dyn_conpty_init(int verbose)
5856{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005857 static HMODULE hKerneldll = NULL;
5858 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005859 static struct
5860 {
5861 char *name;
5862 FARPROC *ptr;
5863 } conpty_entry[] =
5864 {
5865 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
5866 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
5867 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
5868 {"InitializeProcThreadAttributeList",
5869 (FARPROC*)&pInitializeProcThreadAttributeList},
5870 {"UpdateProcThreadAttribute",
5871 (FARPROC*)&pUpdateProcThreadAttribute},
5872 {"DeleteProcThreadAttributeList",
5873 (FARPROC*)&pDeleteProcThreadAttributeList},
5874 {NULL, NULL}
5875 };
5876
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01005877 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005878 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005879 if (verbose)
5880 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005881 return FAIL;
5882 }
5883
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005884 // No need to initialize twice.
5885 if (hKerneldll)
5886 return OK;
5887
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005888 hKerneldll = vimLoadLib("kernel32.dll");
5889 for (i = 0; conpty_entry[i].name != NULL
5890 && conpty_entry[i].ptr != NULL; ++i)
5891 {
5892 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
5893 conpty_entry[i].name)) == NULL)
5894 {
5895 if (verbose)
5896 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01005897 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005898 return FAIL;
5899 }
5900 }
5901
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005902 return OK;
5903}
5904
5905 static int
5906conpty_term_and_job_init(
5907 term_T *term,
5908 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02005909 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005910 jobopt_T *opt,
5911 jobopt_T *orig_opt)
5912{
5913 WCHAR *cmd_wchar = NULL;
5914 WCHAR *cmd_wchar_copy = NULL;
5915 WCHAR *cwd_wchar = NULL;
5916 WCHAR *env_wchar = NULL;
5917 channel_T *channel = NULL;
5918 job_T *job = NULL;
5919 HANDLE jo = NULL;
5920 garray_T ga_cmd, ga_env;
5921 char_u *cmd = NULL;
5922 HRESULT hr;
5923 COORD consize;
5924 SIZE_T breq;
5925 PROCESS_INFORMATION proc_info;
5926 HANDLE i_theirs = NULL;
5927 HANDLE o_theirs = NULL;
5928 HANDLE i_ours = NULL;
5929 HANDLE o_ours = NULL;
5930
5931 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5932 ga_init2(&ga_env, (int)sizeof(char*), 20);
5933
5934 if (argvar->v_type == VAR_STRING)
5935 {
5936 cmd = argvar->vval.v_string;
5937 }
5938 else if (argvar->v_type == VAR_LIST)
5939 {
5940 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
5941 goto failed;
5942 cmd = ga_cmd.ga_data;
5943 }
5944 if (cmd == NULL || *cmd == NUL)
5945 {
5946 emsg(_(e_invarg));
5947 goto failed;
5948 }
5949
5950 term->tl_arg0_cmd = vim_strsave(cmd);
5951
5952 cmd_wchar = enc_to_utf16(cmd, NULL);
5953
5954 if (cmd_wchar != NULL)
5955 {
5956 /* Request by CreateProcessW */
5957 breq = wcslen(cmd_wchar) + 1 + 1; /* Addition of NUL by API */
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005958 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005959 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
5960 }
5961
5962 ga_clear(&ga_cmd);
5963 if (cmd_wchar == NULL)
5964 goto failed;
5965 if (opt->jo_cwd != NULL)
5966 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
5967
5968 win32_build_env(opt->jo_env, &ga_env, TRUE);
5969 env_wchar = ga_env.ga_data;
5970
5971 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
5972 goto failed;
5973 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
5974 goto failed;
5975
5976 consize.X = term->tl_cols;
5977 consize.Y = term->tl_rows;
5978 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
5979 &term->tl_conpty);
5980 if (FAILED(hr))
5981 goto failed;
5982
5983 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
5984
5985 /* Set up pipe inheritance safely: Vista or later. */
5986 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005987 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005988 if (!term->tl_siex.lpAttributeList)
5989 goto failed;
5990 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
5991 0, &breq))
5992 goto failed;
5993 if (!pUpdateProcThreadAttribute(
5994 term->tl_siex.lpAttributeList, 0,
5995 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
5996 sizeof(HPCON), NULL, NULL))
5997 goto failed;
5998
5999 channel = add_channel();
6000 if (channel == NULL)
6001 goto failed;
6002
6003 job = job_alloc();
6004 if (job == NULL)
6005 goto failed;
6006 if (argvar->v_type == VAR_STRING)
6007 {
6008 int argc;
6009
6010 build_argv_from_string(cmd, &job->jv_argv, &argc);
6011 }
6012 else
6013 {
6014 int argc;
6015
6016 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6017 }
6018
6019 if (opt->jo_set & JO_IN_BUF)
6020 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6021
6022 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6023 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6024 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6025 | CREATE_DEFAULT_ERROR_MODE,
6026 env_wchar, cwd_wchar,
6027 &term->tl_siex.StartupInfo, &proc_info))
6028 goto failed;
6029
6030 CloseHandle(i_theirs);
6031 CloseHandle(o_theirs);
6032
6033 channel_set_pipes(channel,
6034 (sock_T)i_ours,
6035 (sock_T)o_ours,
6036 (sock_T)o_ours);
6037
6038 /* Write lines with CR instead of NL. */
6039 channel->ch_write_text_mode = TRUE;
6040
6041 /* Use to explicitly delete anonymous pipe handle. */
6042 channel->ch_anonymous_pipe = TRUE;
6043
6044 jo = CreateJobObject(NULL, NULL);
6045 if (jo == NULL)
6046 goto failed;
6047
6048 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6049 {
6050 /* Failed, switch the way to terminate process with TerminateProcess. */
6051 CloseHandle(jo);
6052 jo = NULL;
6053 }
6054
6055 ResumeThread(proc_info.hThread);
6056 CloseHandle(proc_info.hThread);
6057
6058 vim_free(cmd_wchar);
6059 vim_free(cmd_wchar_copy);
6060 vim_free(cwd_wchar);
6061 vim_free(env_wchar);
6062
6063 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6064 goto failed;
6065
6066#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6067 if (opt->jo_set2 & JO2_ANSI_COLORS)
6068 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6069 else
6070 init_vterm_ansi_colors(term->tl_vterm);
6071#endif
6072
6073 channel_set_job(channel, job, opt);
6074 job_set_options(job, opt);
6075
6076 job->jv_channel = channel;
6077 job->jv_proc_info = proc_info;
6078 job->jv_job_object = jo;
6079 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006080 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006081 ++job->jv_refcount;
6082 term->tl_job = job;
6083
6084 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6085 * open the file here and handle it in. opt->jo_io was changed in
6086 * setup_job_options(), use the original flags here. */
6087 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6088 {
6089 char_u *fname = opt->jo_io_name[PART_OUT];
6090
6091 ch_log(channel, "Opening output file %s", fname);
6092 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6093 if (term->tl_out_fd == NULL)
6094 semsg(_(e_notopen), fname);
6095 }
6096
6097 return OK;
6098
6099failed:
6100 ga_clear(&ga_cmd);
6101 ga_clear(&ga_env);
6102 vim_free(cmd_wchar);
6103 vim_free(cmd_wchar_copy);
6104 vim_free(cwd_wchar);
6105 if (channel != NULL)
6106 channel_clear(channel);
6107 if (job != NULL)
6108 {
6109 job->jv_channel = NULL;
6110 job_cleanup(job);
6111 }
6112 term->tl_job = NULL;
6113 if (jo != NULL)
6114 CloseHandle(jo);
6115
6116 if (term->tl_siex.lpAttributeList != NULL)
6117 {
6118 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6119 vim_free(term->tl_siex.lpAttributeList);
6120 }
6121 term->tl_siex.lpAttributeList = NULL;
6122 if (o_theirs != NULL)
6123 CloseHandle(o_theirs);
6124 if (o_ours != NULL)
6125 CloseHandle(o_ours);
6126 if (i_ours != NULL)
6127 CloseHandle(i_ours);
6128 if (i_theirs != NULL)
6129 CloseHandle(i_theirs);
6130 if (term->tl_conpty != NULL)
6131 pClosePseudoConsole(term->tl_conpty);
6132 term->tl_conpty = NULL;
6133 return FAIL;
6134}
6135
6136 static void
6137conpty_term_report_winsize(term_T *term, int rows, int cols)
6138{
6139 COORD consize;
6140
6141 consize.X = cols;
6142 consize.Y = rows;
6143 pResizePseudoConsole(term->tl_conpty, consize);
6144}
6145
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006146 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006147term_free_conpty(term_T *term)
6148{
6149 if (term->tl_siex.lpAttributeList != NULL)
6150 {
6151 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6152 vim_free(term->tl_siex.lpAttributeList);
6153 }
6154 term->tl_siex.lpAttributeList = NULL;
6155 if (term->tl_conpty != NULL)
6156 pClosePseudoConsole(term->tl_conpty);
6157 term->tl_conpty = NULL;
6158}
6159
6160 int
6161use_conpty(void)
6162{
6163 return has_conpty;
6164}
6165
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006166# ifndef PROTO
6167
6168#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6169#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006170#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006171
6172void* (*winpty_config_new)(UINT64, void*);
6173void* (*winpty_open)(void*, void*);
6174void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6175BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6176void (*winpty_config_set_mouse_mode)(void*, int);
6177void (*winpty_config_set_initial_size)(void*, int, int);
6178LPCWSTR (*winpty_conin_name)(void*);
6179LPCWSTR (*winpty_conout_name)(void*);
6180LPCWSTR (*winpty_conerr_name)(void*);
6181void (*winpty_free)(void*);
6182void (*winpty_config_free)(void*);
6183void (*winpty_spawn_config_free)(void*);
6184void (*winpty_error_free)(void*);
6185LPCWSTR (*winpty_error_msg)(void*);
6186BOOL (*winpty_set_size)(void*, int, int, void*);
6187HANDLE (*winpty_agent_process)(void*);
6188
6189#define WINPTY_DLL "winpty.dll"
6190
6191static HINSTANCE hWinPtyDLL = NULL;
6192# endif
6193
6194 static int
6195dyn_winpty_init(int verbose)
6196{
6197 int i;
6198 static struct
6199 {
6200 char *name;
6201 FARPROC *ptr;
6202 } winpty_entry[] =
6203 {
6204 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6205 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6206 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6207 {"winpty_config_set_mouse_mode",
6208 (FARPROC*)&winpty_config_set_mouse_mode},
6209 {"winpty_config_set_initial_size",
6210 (FARPROC*)&winpty_config_set_initial_size},
6211 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6212 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6213 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6214 {"winpty_free", (FARPROC*)&winpty_free},
6215 {"winpty_open", (FARPROC*)&winpty_open},
6216 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6217 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6218 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6219 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6220 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6221 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6222 {NULL, NULL}
6223 };
6224
6225 /* No need to initialize twice. */
6226 if (hWinPtyDLL)
6227 return OK;
6228 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6229 * winpty.dll. */
6230 if (*p_winptydll != NUL)
6231 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6232 if (!hWinPtyDLL)
6233 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6234 if (!hWinPtyDLL)
6235 {
6236 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006237 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006238 : (char_u *)WINPTY_DLL);
6239 return FAIL;
6240 }
6241 for (i = 0; winpty_entry[i].name != NULL
6242 && winpty_entry[i].ptr != NULL; ++i)
6243 {
6244 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6245 winpty_entry[i].name)) == NULL)
6246 {
6247 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006248 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006249 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006250 return FAIL;
6251 }
6252 }
6253
6254 return OK;
6255}
6256
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006257 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006258winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006259 term_T *term,
6260 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006261 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006262 jobopt_T *opt,
6263 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006264{
6265 WCHAR *cmd_wchar = NULL;
6266 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006267 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006268 channel_T *channel = NULL;
6269 job_T *job = NULL;
6270 DWORD error;
6271 HANDLE jo = NULL;
6272 HANDLE child_process_handle;
6273 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006274 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006275 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006276 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006277 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006278
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006279 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6280 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006281
6282 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006283 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006284 cmd = argvar->vval.v_string;
6285 }
6286 else if (argvar->v_type == VAR_LIST)
6287 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006288 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006289 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006290 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006291 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006292 if (cmd == NULL || *cmd == NUL)
6293 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006294 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006295 goto failed;
6296 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006297
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006298 term->tl_arg0_cmd = vim_strsave(cmd);
6299
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006300 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006301 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006302 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006303 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006304 if (opt->jo_cwd != NULL)
6305 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006306
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006307 win32_build_env(opt->jo_env, &ga_env, TRUE);
6308 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006309
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006310 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6311 if (term->tl_winpty_config == NULL)
6312 goto failed;
6313
6314 winpty_config_set_mouse_mode(term->tl_winpty_config,
6315 WINPTY_MOUSE_MODE_FORCE);
6316 winpty_config_set_initial_size(term->tl_winpty_config,
6317 term->tl_cols, term->tl_rows);
6318 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6319 if (term->tl_winpty == NULL)
6320 goto failed;
6321
6322 spawn_config = winpty_spawn_config_new(
6323 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6324 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6325 NULL,
6326 cmd_wchar,
6327 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006328 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006329 &winpty_err);
6330 if (spawn_config == NULL)
6331 goto failed;
6332
6333 channel = add_channel();
6334 if (channel == NULL)
6335 goto failed;
6336
6337 job = job_alloc();
6338 if (job == NULL)
6339 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006340 if (argvar->v_type == VAR_STRING)
6341 {
6342 int argc;
6343
6344 build_argv_from_string(cmd, &job->jv_argv, &argc);
6345 }
6346 else
6347 {
6348 int argc;
6349
6350 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6351 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006352
6353 if (opt->jo_set & JO_IN_BUF)
6354 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6355
6356 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6357 &child_thread_handle, &error, &winpty_err))
6358 goto failed;
6359
6360 channel_set_pipes(channel,
6361 (sock_T)CreateFileW(
6362 winpty_conin_name(term->tl_winpty),
6363 GENERIC_WRITE, 0, NULL,
6364 OPEN_EXISTING, 0, NULL),
6365 (sock_T)CreateFileW(
6366 winpty_conout_name(term->tl_winpty),
6367 GENERIC_READ, 0, NULL,
6368 OPEN_EXISTING, 0, NULL),
6369 (sock_T)CreateFileW(
6370 winpty_conerr_name(term->tl_winpty),
6371 GENERIC_READ, 0, NULL,
6372 OPEN_EXISTING, 0, NULL));
6373
6374 /* Write lines with CR instead of NL. */
6375 channel->ch_write_text_mode = TRUE;
6376
6377 jo = CreateJobObject(NULL, NULL);
6378 if (jo == NULL)
6379 goto failed;
6380
6381 if (!AssignProcessToJobObject(jo, child_process_handle))
6382 {
6383 /* Failed, switch the way to terminate process with TerminateProcess. */
6384 CloseHandle(jo);
6385 jo = NULL;
6386 }
6387
6388 winpty_spawn_config_free(spawn_config);
6389 vim_free(cmd_wchar);
6390 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006391 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006392
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006393 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6394 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006395
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006396#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6397 if (opt->jo_set2 & JO2_ANSI_COLORS)
6398 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6399 else
6400 init_vterm_ansi_colors(term->tl_vterm);
6401#endif
6402
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006403 channel_set_job(channel, job, opt);
6404 job_set_options(job, opt);
6405
6406 job->jv_channel = channel;
6407 job->jv_proc_info.hProcess = child_process_handle;
6408 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6409 job->jv_job_object = jo;
6410 job->jv_status = JOB_STARTED;
6411 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006412 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006413 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006414 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006415 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006416 ++job->jv_refcount;
6417 term->tl_job = job;
6418
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006419 /* Redirecting stdout and stderr doesn't work at the job level. Instead
6420 * open the file here and handle it in. opt->jo_io was changed in
6421 * setup_job_options(), use the original flags here. */
6422 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6423 {
6424 char_u *fname = opt->jo_io_name[PART_OUT];
6425
6426 ch_log(channel, "Opening output file %s", fname);
6427 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6428 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006429 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006430 }
6431
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006432 return OK;
6433
6434failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006435 ga_clear(&ga_cmd);
6436 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006437 vim_free(cmd_wchar);
6438 vim_free(cwd_wchar);
6439 if (spawn_config != NULL)
6440 winpty_spawn_config_free(spawn_config);
6441 if (channel != NULL)
6442 channel_clear(channel);
6443 if (job != NULL)
6444 {
6445 job->jv_channel = NULL;
6446 job_cleanup(job);
6447 }
6448 term->tl_job = NULL;
6449 if (jo != NULL)
6450 CloseHandle(jo);
6451 if (term->tl_winpty != NULL)
6452 winpty_free(term->tl_winpty);
6453 term->tl_winpty = NULL;
6454 if (term->tl_winpty_config != NULL)
6455 winpty_config_free(term->tl_winpty_config);
6456 term->tl_winpty_config = NULL;
6457 if (winpty_err != NULL)
6458 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006459 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006460 (short_u *)winpty_error_msg(winpty_err), NULL);
6461
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006462 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006463 winpty_error_free(winpty_err);
6464 }
6465 return FAIL;
6466}
6467
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006468/*
6469 * Create a new terminal of "rows" by "cols" cells.
6470 * Store a reference in "term".
6471 * Return OK or FAIL.
6472 */
6473 static int
6474term_and_job_init(
6475 term_T *term,
6476 typval_T *argvar,
6477 char **argv UNUSED,
6478 jobopt_T *opt,
6479 jobopt_T *orig_opt)
6480{
6481 int use_winpty = FALSE;
6482 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006483 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006484
6485 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6486 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6487
6488 if (!has_winpty && !has_conpty)
6489 // If neither is available give the errors for winpty, since when
6490 // conpty is not available it can't be installed either.
6491 return dyn_winpty_init(TRUE);
6492
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006493 if (opt->jo_tty_type != NUL)
6494 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006495
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006496 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006497 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006498 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006499 use_conpty = TRUE;
6500 else if (has_winpty)
6501 use_winpty = TRUE;
6502 // else: error
6503 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006504 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006505 {
6506 if (has_winpty)
6507 use_winpty = TRUE;
6508 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006509 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006510 {
6511 if (has_conpty)
6512 use_conpty = TRUE;
6513 else
6514 return dyn_conpty_init(TRUE);
6515 }
6516
6517 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006518 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006519
6520 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006521 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006522
6523 // error
6524 return dyn_winpty_init(TRUE);
6525}
6526
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006527 static int
6528create_pty_only(term_T *term, jobopt_T *options)
6529{
6530 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6531 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6532 char in_name[80], out_name[80];
6533 channel_T *channel = NULL;
6534
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006535 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6536 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006537
6538 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6539 GetCurrentProcessId(),
6540 curbuf->b_fnum);
6541 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6542 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6543 PIPE_UNLIMITED_INSTANCES,
6544 0, 0, NMPWAIT_NOWAIT, NULL);
6545 if (hPipeIn == INVALID_HANDLE_VALUE)
6546 goto failed;
6547
6548 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6549 GetCurrentProcessId(),
6550 curbuf->b_fnum);
6551 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6552 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6553 PIPE_UNLIMITED_INSTANCES,
6554 0, 0, 0, NULL);
6555 if (hPipeOut == INVALID_HANDLE_VALUE)
6556 goto failed;
6557
6558 ConnectNamedPipe(hPipeIn, NULL);
6559 ConnectNamedPipe(hPipeOut, NULL);
6560
6561 term->tl_job = job_alloc();
6562 if (term->tl_job == NULL)
6563 goto failed;
6564 ++term->tl_job->jv_refcount;
6565
6566 /* behave like the job is already finished */
6567 term->tl_job->jv_status = JOB_FINISHED;
6568
6569 channel = add_channel();
6570 if (channel == NULL)
6571 goto failed;
6572 term->tl_job->jv_channel = channel;
6573 channel->ch_keep_open = TRUE;
6574 channel->ch_named_pipe = TRUE;
6575
6576 channel_set_pipes(channel,
6577 (sock_T)hPipeIn,
6578 (sock_T)hPipeOut,
6579 (sock_T)hPipeOut);
6580 channel_set_job(channel, term->tl_job, options);
6581 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6582 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6583
6584 return OK;
6585
6586failed:
6587 if (hPipeIn != NULL)
6588 CloseHandle(hPipeIn);
6589 if (hPipeOut != NULL)
6590 CloseHandle(hPipeOut);
6591 return FAIL;
6592}
6593
6594/*
6595 * Free the terminal emulator part of "term".
6596 */
6597 static void
6598term_free_vterm(term_T *term)
6599{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006600 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006601 if (term->tl_winpty != NULL)
6602 winpty_free(term->tl_winpty);
6603 term->tl_winpty = NULL;
6604 if (term->tl_winpty_config != NULL)
6605 winpty_config_free(term->tl_winpty_config);
6606 term->tl_winpty_config = NULL;
6607 if (term->tl_vterm != NULL)
6608 vterm_free(term->tl_vterm);
6609 term->tl_vterm = NULL;
6610}
6611
6612/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006613 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006614 */
6615 static void
6616term_report_winsize(term_T *term, int rows, int cols)
6617{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006618 if (term->tl_conpty)
6619 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006620 if (term->tl_winpty)
6621 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6622}
6623
6624 int
6625terminal_enabled(void)
6626{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006627 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006628}
6629
6630# else
6631
6632/**************************************
6633 * 3. Unix-like implementation.
6634 */
6635
6636/*
6637 * Create a new terminal of "rows" by "cols" cells.
6638 * Start job for "cmd".
6639 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006640 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006641 * Return OK or FAIL.
6642 */
6643 static int
6644term_and_job_init(
6645 term_T *term,
6646 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006647 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006648 jobopt_T *opt,
6649 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006650{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006651 term->tl_arg0_cmd = NULL;
6652
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006653 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6654 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006655
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006656#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6657 if (opt->jo_set2 & JO2_ANSI_COLORS)
6658 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6659 else
6660 init_vterm_ansi_colors(term->tl_vterm);
6661#endif
6662
Bram Moolenaar13568252018-03-16 20:46:58 +01006663 /* This may change a string in "argvar". */
Bram Moolenaar493359e2018-06-12 20:25:52 +02006664 term->tl_job = job_start(argvar, argv, opt, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006665 if (term->tl_job != NULL)
6666 ++term->tl_job->jv_refcount;
6667
6668 return term->tl_job != NULL
6669 && term->tl_job->jv_channel != NULL
6670 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6671}
6672
6673 static int
6674create_pty_only(term_T *term, jobopt_T *opt)
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
6679 term->tl_job = job_alloc();
6680 if (term->tl_job == NULL)
6681 return FAIL;
6682 ++term->tl_job->jv_refcount;
6683
6684 /* behave like the job is already finished */
6685 term->tl_job->jv_status = JOB_FINISHED;
6686
6687 return mch_create_pty_channel(term->tl_job, opt);
6688}
6689
6690/*
6691 * Free the terminal emulator part of "term".
6692 */
6693 static void
6694term_free_vterm(term_T *term)
6695{
6696 if (term->tl_vterm != NULL)
6697 vterm_free(term->tl_vterm);
6698 term->tl_vterm = NULL;
6699}
6700
6701/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006702 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006703 */
6704 static void
6705term_report_winsize(term_T *term, int rows, int cols)
6706{
6707 /* Use an ioctl() to report the new window size to the job. */
6708 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6709 {
6710 int fd = -1;
6711 int part;
6712
6713 for (part = PART_OUT; part < PART_COUNT; ++part)
6714 {
6715 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006716 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006717 break;
6718 }
6719 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6720 mch_signal_job(term->tl_job, (char_u *)"winch");
6721 }
6722}
6723
6724# endif
6725
6726#endif /* FEAT_TERMINAL */