blob: f7b653a6854220a8ce33cbfe90a2af1a1bc79e15 [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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010054// This is VTermScreenCell without the characters, thus much smaller.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020055typedef 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 Moolenaar0d6f5d92019-12-05 21:33:15 +010086// typedef term_T in structs.h
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020087struct 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)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010094 int tl_system; // when non-zero used for :!cmd output
95 int tl_toprow; // row with first line of system terminal
Bram Moolenaar13568252018-03-16 20:46:58 +010096#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020097
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +010098 // Set when setting the size of a vterm, reset after redrawing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020099 int tl_vterm_size_changed;
100
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100101 int tl_normal_mode; // TRUE: Terminal-Normal mode
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200102 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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100107#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
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100130 // last known vterm size
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200131 int tl_rows;
132 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200133
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100134 char_u *tl_title; // NULL or allocated
135 char_u *tl_status_text; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100137 // Range of screen rows to update. Zero based.
138 int tl_dirty_row_start; // MAX_ROW if nothing dirty
139 int tl_dirty_row_end; // row below last one to update
140 int tl_dirty_snapshot; // text updated after making snapshot
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200141#ifdef FEAT_TIMERS
142 int tl_timer_set;
143 proftime_T tl_timer_due;
144#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100145 int tl_postponed_scroll; // to be scrolled up
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200146
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 Moolenaar83d47902020-03-26 20:34:00 +0100151 char_u *tl_highlight_name; // replaces "Terminal"; allocated
152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200153 cellattr_T tl_default_color;
154
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100155 linenr_T tl_top_diff_rows; // rows of top diff file or zero
156 linenr_T tl_bot_diff_rows; // rows of bottom diff file
Bram Moolenaard96ff162018-02-18 22:13:29 +0100157
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200158 VTermPos tl_cursor_pos;
159 int tl_cursor_visible;
160 int tl_cursor_blink;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100161 int tl_cursor_shape; // 1: block, 2: underline, 3: bar
162 char_u *tl_cursor_color; // NULL or allocated
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200163
164 int tl_using_altscreen;
165};
166
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100167#define TMODE_ONCE 1 // CTRL-\ CTRL-N used
168#define TMODE_LOOP 2 // CTRL-W N used
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200169
170/*
171 * List of all active terminals.
172 */
173static term_T *first_term = NULL;
174
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100175// Terminal active in terminal_loop().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200176static term_T *in_terminal_loop = NULL;
177
Bram Moolenaar4f974752019-02-17 17:44:42 +0100178#ifdef MSWIN
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100179static BOOL has_winpty = FALSE;
180static BOOL has_conpty = FALSE;
181#endif
182
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100183#define MAX_ROW 999999 // used for tl_dirty_row_end to update all rows
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200184#define KEY_BUF_LEN 200
185
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200186#define FOR_ALL_TERMS(term) \
187 for ((term) = first_term; (term) != NULL; (term) = (term)->tl_next)
188
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189/*
190 * Functions with separate implementation for MS-Windows and Unix-like systems.
191 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200192static 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 +0200193static int create_pty_only(term_T *term, jobopt_T *opt);
194static void term_report_winsize(term_T *term, int rows, int cols);
195static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100196#ifdef FEAT_GUI
197static void update_system_term(term_T *term);
198#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200199
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100200static void handle_postponed_scrollback(term_T *term);
201
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100202// The character that we know (or assume) that the terminal expects for the
203// backspace key.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200204static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200205
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100206// "Terminal" highlight group colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100207static int term_default_cterm_fg = -1;
208static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100210// Store the last set and the desired cursor properties, so that we only update
211// them when needed. Doing it unnecessary may result in flicker.
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200212static char_u *last_set_cursor_color = NULL;
213static char_u *desired_cursor_color = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +0100214static int last_set_cursor_shape = -1;
215static int desired_cursor_shape = -1;
216static int last_set_cursor_blink = -1;
217static int desired_cursor_blink = -1;
218
219
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100220///////////////////////////////////////
221// 1. Generic code for all systems.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200222
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200223 static int
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200224cursor_color_equal(char_u *lhs_color, char_u *rhs_color)
225{
226 if (lhs_color != NULL && rhs_color != NULL)
227 return STRCMP(lhs_color, rhs_color) == 0;
228 return lhs_color == NULL && rhs_color == NULL;
229}
230
Bram Moolenaar05af9a42018-05-21 18:48:12 +0200231 static void
232cursor_color_copy(char_u **to_color, char_u *from_color)
233{
234 // Avoid a free & alloc if the value is already right.
235 if (cursor_color_equal(*to_color, from_color))
236 return;
237 vim_free(*to_color);
238 *to_color = (from_color == NULL) ? NULL : vim_strsave(from_color);
239}
240
241 static char_u *
Bram Moolenaar4f7fd562018-05-21 14:55:28 +0200242cursor_color_get(char_u *color)
243{
244 return (color == NULL) ? (char_u *)"" : color;
245}
246
247
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200248/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200249 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200250 * current window.
251 * Sets "rows" and/or "cols" to zero when it should follow the window size.
252 * Return TRUE if the size is the minimum size: "24*80".
253 */
254 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200255parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200256{
257 int minsize = FALSE;
258
259 *rows = 0;
260 *cols = 0;
261
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200262 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200263 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200264 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200265
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100266 // Syntax of value was already checked when it's set.
Bram Moolenaar498c2562018-04-15 23:45:15 +0200267 if (p == NULL)
268 {
269 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200270 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200271 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200272 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200273 *cols = atoi((char *)p + 1);
274 }
275 return minsize;
276}
277
278/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200279 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200280 */
281 static void
282set_term_and_win_size(term_T *term)
283{
Bram Moolenaar13568252018-03-16 20:46:58 +0100284#ifdef FEAT_GUI
285 if (term->tl_system)
286 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100287 // Use the whole screen for the system command. However, it will start
288 // at the command line and scroll up as needed, using tl_toprow.
Bram Moolenaar13568252018-03-16 20:46:58 +0100289 term->tl_rows = Rows;
290 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200291 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100292 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100293#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200294 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200295 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200296 if (term->tl_rows != 0)
297 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
298 if (term->tl_cols != 0)
299 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200300 }
301 if (term->tl_rows == 0)
302 term->tl_rows = curwin->w_height;
303 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200304 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200305 if (term->tl_cols == 0)
306 term->tl_cols = curwin->w_width;
307 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200308 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200309}
310
311/*
312 * Initialize job options for a terminal job.
313 * Caller may overrule some of them.
314 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100315 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200316init_job_options(jobopt_T *opt)
317{
318 clear_job_options(opt);
319
320 opt->jo_mode = MODE_RAW;
321 opt->jo_out_mode = MODE_RAW;
322 opt->jo_err_mode = MODE_RAW;
323 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
324}
325
326/*
327 * Set job options mandatory for a terminal job.
328 */
329 static void
330setup_job_options(jobopt_T *opt, int rows, int cols)
331{
Bram Moolenaar4f974752019-02-17 17:44:42 +0100332#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100333 // Win32: Redirecting the job output won't work, thus always connect stdout
334 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200335 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200336#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200337 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100338 // Connect stdout to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200339 opt->jo_io[PART_OUT] = JIO_BUFFER;
340 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
341 opt->jo_modifiable[PART_OUT] = 0;
342 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
343 }
344
Bram Moolenaar4f974752019-02-17 17:44:42 +0100345#ifndef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100346 // Win32: Redirecting the job output won't work, thus always connect stderr
347 // here.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200348 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200349#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200350 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100351 // Connect stderr to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200352 opt->jo_io[PART_ERR] = JIO_BUFFER;
353 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
354 opt->jo_modifiable[PART_ERR] = 0;
355 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
356 }
357
358 opt->jo_pty = TRUE;
359 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
360 opt->jo_term_rows = rows;
361 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
362 opt->jo_term_cols = cols;
363}
364
365/*
Bram Moolenaar5c381eb2019-06-25 06:50:31 +0200366 * Flush messages on channels.
367 */
368 static void
369term_flush_messages()
370{
371 mch_check_messages();
372 parse_queued_messages();
373}
374
375/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100376 * Close a terminal buffer (and its window). Used when creating the terminal
377 * fails.
378 */
379 static void
380term_close_buffer(buf_T *buf, buf_T *old_curbuf)
381{
382 free_terminal(buf);
383 if (old_curbuf != NULL)
384 {
385 --curbuf->b_nwindows;
386 curbuf = old_curbuf;
387 curwin->w_buffer = curbuf;
388 ++curbuf->b_nwindows;
389 }
Bram Moolenaarcee52202020-03-11 14:19:58 +0100390 CHECK_CURBUF;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100391
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100392 // Wiping out the buffer will also close the window and call
393 // free_terminal().
Bram Moolenaard96ff162018-02-18 22:13:29 +0100394 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
395}
396
397/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200398 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100399 * Use either "argvar" or "argv", the other must be NULL.
400 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
401 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200402 * Returns NULL when failed.
403 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100404 buf_T *
405term_start(
406 typval_T *argvar,
407 char **argv,
408 jobopt_T *opt,
409 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200410{
411 exarg_T split_ea;
412 win_T *old_curwin = curwin;
413 term_T *term;
414 buf_T *old_curbuf = NULL;
415 int res;
416 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100417 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200418 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200419
420 if (check_restricted() || check_secure())
421 return NULL;
422
423 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
424 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
425 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
Bram Moolenaarb0992022020-01-30 14:55:42 +0100426 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF))
427 || (argvar != NULL
428 && argvar->v_type == VAR_LIST
429 && argvar->vval.v_list != NULL
430 && argvar->vval.v_list->lv_first == &range_list_item))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200431 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100432 emsg(_(e_invarg));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200433 return NULL;
434 }
435
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200436 term = ALLOC_CLEAR_ONE(term_T);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 if (term == NULL)
438 return NULL;
439 term->tl_dirty_row_end = MAX_ROW;
440 term->tl_cursor_visible = TRUE;
441 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
442 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100443#ifdef FEAT_GUI
444 term->tl_system = (flags & TERM_START_SYSTEM);
445#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200446 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100447 ga_init2(&term->tl_scrollback_postponed, sizeof(sb_line_T), 300);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200448
Bram Moolenaara80faa82020-04-12 19:37:17 +0200449 CLEAR_FIELD(split_ea);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200450 if (opt->jo_curwin)
451 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100452 // Create a new buffer in the current window.
Bram Moolenaar13568252018-03-16 20:46:58 +0100453 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200454 {
455 no_write_message();
456 vim_free(term);
457 return NULL;
458 }
459 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100460 ECMD_HIDE
461 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
462 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200463 {
464 vim_free(term);
465 return NULL;
466 }
467 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100468 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 {
470 buf_T *buf;
471
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100472 // Create a new buffer without a window. Make it the current buffer for
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100473 // a moment to be able to do the initializations.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200474 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
475 BLN_NEW | BLN_LISTED);
476 if (buf == NULL || ml_open(buf) == FAIL)
477 {
478 vim_free(term);
479 return NULL;
480 }
481 old_curbuf = curbuf;
482 --curbuf->b_nwindows;
483 curbuf = buf;
484 curwin->w_buffer = buf;
485 ++curbuf->b_nwindows;
486 }
487 else
488 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100489 // Open a new window or tab.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200490 split_ea.cmdidx = CMD_new;
491 split_ea.cmd = (char_u *)"new";
492 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100493 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200494 {
495 split_ea.line2 = opt->jo_term_rows;
496 split_ea.addr_count = 1;
497 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100498 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200499 {
500 split_ea.line2 = opt->jo_term_cols;
501 split_ea.addr_count = 1;
502 }
503
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100504 if (vertical)
505 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200506 ex_splitview(&split_ea);
507 if (curwin == old_curwin)
508 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100509 // split failed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200510 vim_free(term);
511 return NULL;
512 }
513 }
514 term->tl_buffer = curbuf;
515 curbuf->b_term = term;
516
517 if (!opt->jo_hidden)
518 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100519 // Only one size was taken care of with :new, do the other one. With
520 // "curwin" both need to be done.
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100521 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200522 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100523 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200524 win_setwidth(opt->jo_term_cols);
525 }
526
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100527 // Link the new terminal in the list of active terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200528 term->tl_next = first_term;
529 first_term = term;
530
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100531 apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
532
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200533 if (opt->jo_term_name != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100534 {
535 vim_free(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200536 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100537 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100538 else if (argv != NULL)
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100539 {
540 vim_free(curbuf->b_ffname);
Bram Moolenaar13568252018-03-16 20:46:58 +0100541 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaard5bc32d2020-03-22 19:25:50 +0100542 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200543 else
544 {
545 int i;
546 size_t len;
547 char_u *cmd, *p;
548
549 if (argvar->v_type == VAR_STRING)
550 {
551 cmd = argvar->vval.v_string;
552 if (cmd == NULL)
553 cmd = (char_u *)"";
554 else if (STRCMP(cmd, "NONE") == 0)
555 cmd = (char_u *)"pty";
556 }
557 else if (argvar->v_type != VAR_LIST
558 || argvar->vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +0100559 || argvar->vval.v_list->lv_len == 0
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100560 || (cmd = tv_get_string_chk(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
562 cmd = (char_u*)"";
563
564 len = STRLEN(cmd) + 10;
Bram Moolenaar51e14382019-05-25 20:21:28 +0200565 p = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200566
567 for (i = 0; p != NULL; ++i)
568 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100569 // Prepend a ! to the command name to avoid the buffer name equals
570 // the executable, otherwise ":w!" would overwrite it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200571 if (i == 0)
572 vim_snprintf((char *)p, len, "!%s", cmd);
573 else
574 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
575 if (buflist_findname(p) == NULL)
576 {
577 vim_free(curbuf->b_ffname);
578 curbuf->b_ffname = p;
579 break;
580 }
581 }
582 }
Bram Moolenaare010c722020-02-24 21:37:54 +0100583 vim_free(curbuf->b_sfname);
584 curbuf->b_sfname = vim_strsave(curbuf->b_ffname);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200585 curbuf->b_fname = curbuf->b_ffname;
586
Bram Moolenaar5e94a292020-03-19 18:46:57 +0100587 apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
588
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200589 if (opt->jo_term_opencmd != NULL)
590 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
591
592 if (opt->jo_eof_chars != NULL)
593 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
594
595 set_string_option_direct((char_u *)"buftype", -1,
596 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar7da1fb52018-08-04 16:54:11 +0200597 // Avoid that 'buftype' is reset when this buffer is entered.
598 curbuf->b_p_initialized = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200599
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100600 // Mark the buffer as not modifiable. It can only be made modifiable after
601 // the job finished.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200602 curbuf->b_p_ma = FALSE;
603
604 set_term_and_win_size(term);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100605#ifdef MSWIN
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200606 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
607#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200608 setup_job_options(opt, term->tl_rows, term->tl_cols);
609
Bram Moolenaar13568252018-03-16 20:46:58 +0100610 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100611 return curbuf;
612
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100613#if defined(FEAT_SESSION)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100614 // Remember the command for the session file.
Bram Moolenaar13568252018-03-16 20:46:58 +0100615 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100616 term->tl_command = vim_strsave((char_u *)"NONE");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100617 else if (argvar->v_type == VAR_STRING)
618 {
619 char_u *cmd = argvar->vval.v_string;
620
621 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
622 term->tl_command = vim_strsave(cmd);
623 }
624 else if (argvar->v_type == VAR_LIST
625 && argvar->vval.v_list != NULL
626 && argvar->vval.v_list->lv_len > 0)
627 {
628 garray_T ga;
629 listitem_T *item;
630
631 ga_init2(&ga, 1, 100);
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200632 FOR_ALL_LIST_ITEMS(argvar->vval.v_list, item)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100633 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +0100634 char_u *s = tv_get_string_chk(&item->li_tv);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100635 char_u *p;
636
637 if (s == NULL)
638 break;
639 p = vim_strsave_fnameescape(s, FALSE);
640 if (p == NULL)
641 break;
642 ga_concat(&ga, p);
643 vim_free(p);
644 ga_append(&ga, ' ');
645 }
646 if (item == NULL)
647 {
648 ga_append(&ga, NUL);
649 term->tl_command = ga.ga_data;
650 }
651 else
652 ga_clear(&ga);
653 }
654#endif
655
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100656 if (opt->jo_term_kill != NULL)
657 {
658 char_u *p = skiptowhite(opt->jo_term_kill);
659
660 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
661 }
662
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200663 if (opt->jo_term_api != NULL)
Bram Moolenaar21109272020-01-30 16:27:20 +0100664 {
665 char_u *p = skiptowhite(opt->jo_term_api);
666
667 term->tl_api = vim_strnsave(opt->jo_term_api, p - opt->jo_term_api);
668 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200669 else
670 term->tl_api = vim_strsave((char_u *)"Tapi_");
671
Bram Moolenaar83d47902020-03-26 20:34:00 +0100672 if (opt->jo_set2 & JO2_TERM_HIGHLIGHT)
673 term->tl_highlight_name = vim_strsave(opt->jo_term_highlight);
674
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100675 // System dependent: setup the vterm and maybe start the job in it.
Bram Moolenaar13568252018-03-16 20:46:58 +0100676 if (argv == NULL
677 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200678 && argvar->vval.v_string != NULL
679 && STRCMP(argvar->vval.v_string, "NONE") == 0)
680 res = create_pty_only(term, opt);
681 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200682 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200683
684 newbuf = curbuf;
685 if (res == OK)
686 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100687 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200688 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
689 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100690#ifdef FEAT_GUI
691 if (term->tl_system)
692 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100693 // display first line below typed command
Bram Moolenaar13568252018-03-16 20:46:58 +0100694 term->tl_toprow = msg_row + 1;
695 term->tl_dirty_row_end = 0;
696 }
697#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200698
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100699 // Make sure we don't get stuck on sending keys to the job, it leads to
700 // a deadlock if the job is waiting for Vim to read.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200701 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
702
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200703 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200704 {
705 --curbuf->b_nwindows;
706 curbuf = old_curbuf;
707 curwin->w_buffer = curbuf;
708 ++curbuf->b_nwindows;
709 }
710 }
711 else
712 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100713 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200714 return NULL;
715 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100716
Bram Moolenaar13568252018-03-16 20:46:58 +0100717 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar28ed4df2019-10-26 16:21:40 +0200718 if (!opt->jo_hidden && !(flags & TERM_START_SYSTEM))
719 apply_autocmds(EVENT_TERMINALWINOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200720 return newbuf;
721}
722
723/*
724 * ":terminal": open a terminal window and execute a job in it.
725 */
726 void
727ex_terminal(exarg_T *eap)
728{
729 typval_T argvar[2];
730 jobopt_T opt;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100731 int opt_shell = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200732 char_u *cmd;
733 char_u *tofree = NULL;
734
735 init_job_options(&opt);
736
737 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100738 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200739 {
740 char_u *p, *ep;
741
742 cmd += 2;
743 p = skiptowhite(cmd);
744 ep = vim_strchr(cmd, '=');
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200745 if (ep != NULL)
746 {
747 if (ep < p)
748 p = ep;
749 else
750 ep = NULL;
751 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200753# define OPTARG_HAS(name) ((int)(p - cmd) == sizeof(name) - 1 \
754 && STRNICMP(cmd, name, sizeof(name) - 1) == 0)
755 if (OPTARG_HAS("close"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200756 opt.jo_term_finish = 'c';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200757 else if (OPTARG_HAS("noclose"))
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100758 opt.jo_term_finish = 'n';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200759 else if (OPTARG_HAS("open"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200760 opt.jo_term_finish = 'o';
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200761 else if (OPTARG_HAS("curwin"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200762 opt.jo_curwin = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200763 else if (OPTARG_HAS("hidden"))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200764 opt.jo_hidden = 1;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200765 else if (OPTARG_HAS("norestore"))
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100766 opt.jo_term_norestore = 1;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100767 else if (OPTARG_HAS("shell"))
768 opt_shell = TRUE;
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200769 else if (OPTARG_HAS("kill") && ep != NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100770 {
771 opt.jo_set2 |= JO2_TERM_KILL;
772 opt.jo_term_kill = ep + 1;
773 p = skiptowhite(cmd);
774 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200775 else if (OPTARG_HAS("api"))
776 {
777 opt.jo_set2 |= JO2_TERM_API;
778 if (ep != NULL)
779 {
780 opt.jo_term_api = ep + 1;
781 p = skiptowhite(cmd);
782 }
783 else
784 opt.jo_term_api = NULL;
785 }
786 else if (OPTARG_HAS("rows") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787 {
788 opt.jo_set2 |= JO2_TERM_ROWS;
789 opt.jo_term_rows = atoi((char *)ep + 1);
790 p = skiptowhite(cmd);
791 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200792 else if (OPTARG_HAS("cols") && ep != NULL && isdigit(ep[1]))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200793 {
794 opt.jo_set2 |= JO2_TERM_COLS;
795 opt.jo_term_cols = atoi((char *)ep + 1);
796 p = skiptowhite(cmd);
797 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200798 else if (OPTARG_HAS("eof") && ep != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200799 {
800 char_u *buf = NULL;
801 char_u *keys;
802
Bram Moolenaar21109272020-01-30 16:27:20 +0100803 vim_free(opt.jo_eof_chars);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200804 p = skiptowhite(cmd);
805 *p = NUL;
Bram Moolenaar459fd782019-10-13 16:43:39 +0200806 keys = replace_termcodes(ep + 1, &buf,
807 REPTERM_FROM_PART | REPTERM_DO_LT | REPTERM_SPECIAL, NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200808 opt.jo_set2 |= JO2_EOF_CHARS;
809 opt.jo_eof_chars = vim_strsave(keys);
810 vim_free(buf);
811 *p = ' ';
812 }
Bram Moolenaar4f974752019-02-17 17:44:42 +0100813#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100814 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "type", 4) == 0
815 && ep != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100816 {
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100817 int tty_type = NUL;
818
819 p = skiptowhite(cmd);
820 if (STRNICMP(ep + 1, "winpty", p - (ep + 1)) == 0)
821 tty_type = 'w';
822 else if (STRNICMP(ep + 1, "conpty", p - (ep + 1)) == 0)
823 tty_type = 'c';
824 else
825 {
826 semsg(e_invargval, "type");
827 goto theend;
828 }
829 opt.jo_set2 |= JO2_TTY_TYPE;
830 opt.jo_tty_type = tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100831 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100832#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 else
834 {
835 if (*p)
836 *p = NUL;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100837 semsg(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100838 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200839 }
Bram Moolenaard2842ea2019-09-26 23:08:54 +0200840# undef OPTARG_HAS
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200841 cmd = skipwhite(p);
842 }
843 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100844 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100845 // Make a copy of 'shell', an autocommand may change the option.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200846 tofree = cmd = vim_strsave(p_sh);
847
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100848 // default to close when the shell exits
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100849 if (opt.jo_term_finish == NUL)
850 opt.jo_term_finish = 'c';
851 }
852
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200853 if (eap->addr_count > 0)
854 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100855 // Write lines from current buffer to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200856 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
857 opt.jo_io[PART_IN] = JIO_BUFFER;
858 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
859 opt.jo_in_top = eap->line1;
860 opt.jo_in_bot = eap->line2;
861 }
862
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100863 if (opt_shell && tofree == NULL)
864 {
865#ifdef UNIX
866 char **argv = NULL;
867 char_u *tofree1 = NULL;
868 char_u *tofree2 = NULL;
869
870 // :term ++shell command
871 if (unix_build_argv(cmd, &argv, &tofree1, &tofree2) == OK)
872 term_start(NULL, argv, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaaradf4aa22019-11-10 22:36:44 +0100873 vim_free(argv);
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100874 vim_free(tofree1);
875 vim_free(tofree2);
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100876 goto theend;
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100877#else
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100878# ifdef MSWIN
879 long_u cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
880 char_u *newcmd;
881
882 newcmd = alloc(cmdlen);
883 if (newcmd == NULL)
884 goto theend;
885 tofree = newcmd;
886 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
887 cmd = newcmd;
888# else
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100889 emsg(_("E279: Sorry, ++shell is not supported on this system"));
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100890 goto theend;
891# endif
Bram Moolenaar197c6b72019-11-03 23:37:12 +0100892#endif
893 }
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100894 argvar[0].v_type = VAR_STRING;
895 argvar[0].vval.v_string = cmd;
896 argvar[1].v_type = VAR_UNKNOWN;
897 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100898
899theend:
Bram Moolenaar2d6d76f2019-11-04 23:18:35 +0100900 vim_free(tofree);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901 vim_free(opt.jo_eof_chars);
902}
903
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100904#if defined(FEAT_SESSION) || defined(PROTO)
905/*
906 * Write a :terminal command to the session file to restore the terminal in
907 * window "wp".
908 * Return FAIL if writing fails.
909 */
910 int
911term_write_session(FILE *fd, win_T *wp)
912{
913 term_T *term = wp->w_buffer->b_term;
914
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +0100915 // Create the terminal and run the command. This is not without
916 // risk, but let's assume the user only creates a session when this
917 // will be OK.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100918 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
919 term->tl_cols, term->tl_rows) < 0)
920 return FAIL;
Bram Moolenaar4f974752019-02-17 17:44:42 +0100921#ifdef MSWIN
Bram Moolenaarc6ddce32019-02-08 12:47:03 +0100922 if (fprintf(fd, "++type=%s ", term->tl_job->jv_tty_type) < 0)
923 return FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100924#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100925 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
926 return FAIL;
927
928 return put_eol(fd);
929}
930
931/*
932 * Return TRUE if "buf" has a terminal that should be restored.
933 */
934 int
935term_should_restore(buf_T *buf)
936{
937 term_T *term = buf->b_term;
938
939 return term != NULL && (term->tl_command == NULL
940 || STRCMP(term->tl_command, "NONE") != 0);
941}
942#endif
943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200944/*
945 * Free the scrollback buffer for "term".
946 */
947 static void
948free_scrollback(term_T *term)
949{
950 int i;
951
952 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
953 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
954 ga_clear(&term->tl_scrollback);
Bram Moolenaar29ae2232019-02-14 21:22:01 +0100955 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
956 vim_free(((sb_line_T *)term->tl_scrollback_postponed.ga_data + i)->sb_cells);
957 ga_clear(&term->tl_scrollback_postponed);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200958}
959
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100960
961// Terminals that need to be freed soon.
Bram Moolenaar840d16f2019-09-10 21:27:18 +0200962static term_T *terminals_to_free = NULL;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100963
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200964/*
965 * Free a terminal and everything it refers to.
966 * Kills the job if there is one.
967 * Called when wiping out a buffer.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100968 * The actual terminal structure is freed later in free_unused_terminals(),
969 * because callbacks may wipe out a buffer while the terminal is still
970 * referenced.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200971 */
972 void
973free_terminal(buf_T *buf)
974{
975 term_T *term = buf->b_term;
976 term_T *tp;
977
978 if (term == NULL)
979 return;
Bram Moolenaar2a4857a2019-01-29 22:29:07 +0100980
981 // Unlink the terminal form the list of terminals.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200982 if (first_term == term)
983 first_term = term->tl_next;
984 else
985 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
986 if (tp->tl_next == term)
987 {
988 tp->tl_next = term->tl_next;
989 break;
990 }
991
992 if (term->tl_job != NULL)
993 {
994 if (term->tl_job->jv_status != JOB_ENDED
995 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100996 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200997 job_stop(term->tl_job, NULL, "kill");
998 job_unref(term->tl_job);
999 }
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001000 term->tl_next = terminals_to_free;
1001 terminals_to_free = term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001002
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001003 buf->b_term = NULL;
1004 if (in_terminal_loop == term)
1005 in_terminal_loop = NULL;
1006}
1007
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001008 void
1009free_unused_terminals()
1010{
1011 while (terminals_to_free != NULL)
1012 {
1013 term_T *term = terminals_to_free;
1014
1015 terminals_to_free = term->tl_next;
1016
1017 free_scrollback(term);
1018
1019 term_free_vterm(term);
Bram Moolenaard2842ea2019-09-26 23:08:54 +02001020 vim_free(term->tl_api);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001021 vim_free(term->tl_title);
1022#ifdef FEAT_SESSION
1023 vim_free(term->tl_command);
1024#endif
1025 vim_free(term->tl_kill);
1026 vim_free(term->tl_status_text);
1027 vim_free(term->tl_opencmd);
1028 vim_free(term->tl_eof_chars);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001029 vim_free(term->tl_arg0_cmd);
Bram Moolenaar4f974752019-02-17 17:44:42 +01001030#ifdef MSWIN
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001031 if (term->tl_out_fd != NULL)
1032 fclose(term->tl_out_fd);
1033#endif
Bram Moolenaar83d47902020-03-26 20:34:00 +01001034 vim_free(term->tl_highlight_name);
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001035 vim_free(term->tl_cursor_color);
1036 vim_free(term);
1037 }
1038}
1039
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001040/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001041 * Get the part that is connected to the tty. Normally this is PART_IN, but
1042 * when writing buffer lines to the job it can be another. This makes it
1043 * possible to do "1,5term vim -".
1044 */
1045 static ch_part_T
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001046get_tty_part(term_T *term UNUSED)
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001047{
1048#ifdef UNIX
1049 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1050 int i;
1051
1052 for (i = 0; i < 3; ++i)
1053 {
1054 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1055
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01001056 if (mch_isatty(fd))
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001057 return parts[i];
1058 }
1059#endif
1060 return PART_IN;
1061}
1062
1063/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001064 * Write job output "msg[len]" to the vterm.
1065 */
1066 static void
1067term_write_job_output(term_T *term, char_u *msg, size_t len)
1068{
1069 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001070 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001071
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001072 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001073
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001074 // flush vterm buffer when vterm responded to control sequence
Bram Moolenaarb50773c2018-01-30 22:31:19 +01001075 if (prevlen != vterm_output_get_buffer_current(vterm))
1076 {
1077 char buf[KEY_BUF_LEN];
1078 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
1079
1080 if (curlen > 0)
1081 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1082 (char_u *)buf, (int)curlen, NULL);
1083 }
1084
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001085 // this invokes the damage callbacks
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001086 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
1087}
1088
1089 static void
1090update_cursor(term_T *term, int redraw)
1091{
1092 if (term->tl_normal_mode)
1093 return;
Bram Moolenaar13568252018-03-16 20:46:58 +01001094#ifdef FEAT_GUI
1095 if (term->tl_system)
1096 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
1097 term->tl_cursor_pos.col);
1098 else
1099#endif
1100 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001101 if (redraw)
1102 {
1103 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
1104 cursor_on();
1105 out_flush();
1106#ifdef FEAT_GUI
1107 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001108 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001109 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +01001110 gui_mch_flush();
1111 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001112#endif
1113 }
1114}
1115
1116/*
1117 * Invoked when "msg" output from a job was received. Write it to the terminal
1118 * of "buffer".
1119 */
1120 void
1121write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
1122{
1123 size_t len = STRLEN(msg);
1124 term_T *term = buffer->b_term;
1125
Bram Moolenaar4f974752019-02-17 17:44:42 +01001126#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001127 // Win32: Cannot redirect output of the job, intercept it here and write to
1128 // the file.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02001129 if (term->tl_out_fd != NULL)
1130 {
1131 ch_log(channel, "Writing %d bytes to output file", (int)len);
1132 fwrite(msg, len, 1, term->tl_out_fd);
1133 return;
1134 }
1135#endif
1136
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001137 if (term->tl_vterm == NULL)
1138 {
1139 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
1140 return;
1141 }
1142 ch_log(channel, "writing %d bytes to terminal", (int)len);
1143 term_write_job_output(term, msg, len);
1144
Bram Moolenaar13568252018-03-16 20:46:58 +01001145#ifdef FEAT_GUI
1146 if (term->tl_system)
1147 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001148 // show system output, scrolling up the screen as needed
Bram Moolenaar13568252018-03-16 20:46:58 +01001149 update_system_term(term);
1150 update_cursor(term, TRUE);
1151 }
1152 else
1153#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001154 // In Terminal-Normal mode we are displaying the buffer, not the terminal
1155 // contents, thus no screen update is needed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001156 if (!term->tl_normal_mode)
1157 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001158 // Don't use update_screen() when editing the command line, it gets
1159 // cleared.
1160 // TODO: only update once in a while.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001161 ch_log(term->tl_job->jv_channel, "updating screen");
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001162 if (buffer == curbuf && (State & CMDLINE) == 0)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001163 {
Bram Moolenaar0ce74132018-06-18 22:15:50 +02001164 update_screen(VALID_NO_UPDATE);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001165 // update_screen() can be slow, check the terminal wasn't closed
1166 // already
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02001167 if (buffer == curbuf && curbuf->b_term != NULL)
1168 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001169 }
1170 else
1171 redraw_after_callback(TRUE);
1172 }
1173}
1174
1175/*
1176 * Send a mouse position and click to the vterm
1177 */
1178 static int
1179term_send_mouse(VTerm *vterm, int button, int pressed)
1180{
1181 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001182 int row = mouse_row - W_WINROW(curwin);
1183 int col = mouse_col - curwin->w_wincol;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001184
Bram Moolenaar219c7d02020-02-01 21:57:29 +01001185#ifdef FEAT_PROP_POPUP
1186 if (popup_is_popup(curwin))
1187 {
1188 row -= popup_top_extra(curwin);
1189 col -= popup_left_extra(curwin);
1190 }
1191#endif
1192 vterm_mouse_move(vterm, row, col, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001193 if (button != 0)
1194 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001195 return TRUE;
1196}
1197
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001198static int enter_mouse_col = -1;
1199static int enter_mouse_row = -1;
1200
1201/*
1202 * Handle a mouse click, drag or release.
1203 * Return TRUE when a mouse event is sent to the terminal.
1204 */
1205 static int
1206term_mouse_click(VTerm *vterm, int key)
1207{
1208#if defined(FEAT_CLIPBOARD)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001209 // For modeless selection mouse drag and release events are ignored, unless
1210 // they are preceded with a mouse down event
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001211 static int ignore_drag_release = TRUE;
1212 VTermMouseState mouse_state;
1213
1214 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1215 if (mouse_state.flags == 0)
1216 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001217 // Terminal is not using the mouse, use modeless selection.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001218 switch (key)
1219 {
1220 case K_LEFTDRAG:
1221 case K_LEFTRELEASE:
1222 case K_RIGHTDRAG:
1223 case K_RIGHTRELEASE:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001224 // Ignore drag and release events when the button-down wasn't
1225 // seen before.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001226 if (ignore_drag_release)
1227 {
1228 int save_mouse_col, save_mouse_row;
1229
1230 if (enter_mouse_col < 0)
1231 break;
1232
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001233 // mouse click in the window gave us focus, handle that
1234 // click now
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001235 save_mouse_col = mouse_col;
1236 save_mouse_row = mouse_row;
1237 mouse_col = enter_mouse_col;
1238 mouse_row = enter_mouse_row;
1239 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1240 mouse_col = save_mouse_col;
1241 mouse_row = save_mouse_row;
1242 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001243 // FALLTHROUGH
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001244 case K_LEFTMOUSE:
1245 case K_RIGHTMOUSE:
1246 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1247 ignore_drag_release = TRUE;
1248 else
1249 ignore_drag_release = FALSE;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001250 // Should we call mouse_has() here?
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001251 if (clip_star.available)
1252 {
1253 int button, is_click, is_drag;
1254
1255 button = get_mouse_button(KEY2TERMCAP1(key),
1256 &is_click, &is_drag);
1257 if (mouse_model_popup() && button == MOUSE_LEFT
1258 && (mod_mask & MOD_MASK_SHIFT))
1259 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001260 // Translate shift-left to right button.
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001261 button = MOUSE_RIGHT;
1262 mod_mask &= ~MOD_MASK_SHIFT;
1263 }
1264 clip_modeless(button, is_click, is_drag);
1265 }
1266 break;
1267
1268 case K_MIDDLEMOUSE:
1269 if (clip_star.available)
1270 insert_reg('*', TRUE);
1271 break;
1272 }
1273 enter_mouse_col = -1;
1274 return FALSE;
1275 }
1276#endif
1277 enter_mouse_col = -1;
1278
1279 switch (key)
1280 {
1281 case K_LEFTMOUSE:
1282 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1283 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1284 case K_LEFTRELEASE:
1285 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1286 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1287 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1288 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1289 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1290 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1291 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1292 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1293 }
1294 return TRUE;
1295}
1296
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001298 * Convert typed key "c" with modifiers "modmask" into bytes to send to the
1299 * job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001300 * Return the number of bytes in "buf".
1301 */
1302 static int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001303term_convert_key(term_T *term, int c, int modmask, char *buf)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001304{
1305 VTerm *vterm = term->tl_vterm;
1306 VTermKey key = VTERM_KEY_NONE;
1307 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001308 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001309
1310 switch (c)
1311 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001312 // don't use VTERM_KEY_ENTER, it may do an unwanted conversion
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001313
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001314 // don't use VTERM_KEY_BACKSPACE, it always
1315 // becomes 0x7f DEL
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001316 case K_BS: c = term_backspace_char; break;
1317
1318 case ESC: key = VTERM_KEY_ESCAPE; break;
1319 case K_DEL: key = VTERM_KEY_DEL; break;
1320 case K_DOWN: key = VTERM_KEY_DOWN; break;
1321 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1322 key = VTERM_KEY_DOWN; break;
1323 case K_END: key = VTERM_KEY_END; break;
1324 case K_S_END: mod = VTERM_MOD_SHIFT;
1325 key = VTERM_KEY_END; break;
1326 case K_C_END: mod = VTERM_MOD_CTRL;
1327 key = VTERM_KEY_END; break;
1328 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1329 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1330 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1331 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1332 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1333 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1334 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1335 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1336 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1337 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1338 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1339 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1340 case K_HOME: key = VTERM_KEY_HOME; break;
1341 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1342 key = VTERM_KEY_HOME; break;
1343 case K_C_HOME: mod = VTERM_MOD_CTRL;
1344 key = VTERM_KEY_HOME; break;
1345 case K_INS: key = VTERM_KEY_INS; break;
1346 case K_K0: key = VTERM_KEY_KP_0; break;
1347 case K_K1: key = VTERM_KEY_KP_1; break;
1348 case K_K2: key = VTERM_KEY_KP_2; break;
1349 case K_K3: key = VTERM_KEY_KP_3; break;
1350 case K_K4: key = VTERM_KEY_KP_4; break;
1351 case K_K5: key = VTERM_KEY_KP_5; break;
1352 case K_K6: key = VTERM_KEY_KP_6; break;
1353 case K_K7: key = VTERM_KEY_KP_7; break;
1354 case K_K8: key = VTERM_KEY_KP_8; break;
1355 case K_K9: key = VTERM_KEY_KP_9; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001356 case K_KDEL: key = VTERM_KEY_DEL; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001357 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001358 case K_KEND: key = VTERM_KEY_KP_1; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001359 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001360 case K_KHOME: key = VTERM_KEY_KP_7; break; // TODO
1361 case K_KINS: key = VTERM_KEY_KP_0; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001362 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1363 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001364 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; // TODO
1365 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; // TODO
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001366 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1367 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1368 case K_LEFT: key = VTERM_KEY_LEFT; break;
1369 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1370 key = VTERM_KEY_LEFT; break;
1371 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1372 key = VTERM_KEY_LEFT; break;
1373 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1374 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1375 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1376 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1377 key = VTERM_KEY_RIGHT; break;
1378 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1379 key = VTERM_KEY_RIGHT; break;
1380 case K_UP: key = VTERM_KEY_UP; break;
1381 case K_S_UP: mod = VTERM_MOD_SHIFT;
1382 key = VTERM_KEY_UP; break;
1383 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001384 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1385 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001386
Bram Moolenaara42ad572017-11-16 13:08:04 +01001387 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1388 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001389 case K_MOUSELEFT: /* TODO */ return 0;
1390 case K_MOUSERIGHT: /* TODO */ return 0;
1391
1392 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001393 case K_LEFTMOUSE_NM:
1394 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001395 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001396 case K_LEFTRELEASE_NM:
1397 case K_MOUSEMOVE:
1398 case K_MIDDLEMOUSE:
1399 case K_MIDDLEDRAG:
1400 case K_MIDDLERELEASE:
1401 case K_RIGHTMOUSE:
1402 case K_RIGHTDRAG:
1403 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1404 return 0;
1405 other = TRUE;
1406 break;
1407
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001408 case K_X1MOUSE: /* TODO */ return 0;
1409 case K_X1DRAG: /* TODO */ return 0;
1410 case K_X1RELEASE: /* TODO */ return 0;
1411 case K_X2MOUSE: /* TODO */ return 0;
1412 case K_X2DRAG: /* TODO */ return 0;
1413 case K_X2RELEASE: /* TODO */ return 0;
1414
1415 case K_IGNORE: return 0;
1416 case K_NOP: return 0;
1417 case K_UNDO: return 0;
1418 case K_HELP: return 0;
1419 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1420 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1421 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1422 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1423 case K_SELECT: return 0;
1424#ifdef FEAT_GUI
1425 case K_VER_SCROLLBAR: return 0;
1426 case K_HOR_SCROLLBAR: return 0;
1427#endif
1428#ifdef FEAT_GUI_TABLINE
1429 case K_TABLINE: return 0;
1430 case K_TABMENU: return 0;
1431#endif
1432#ifdef FEAT_NETBEANS_INTG
1433 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1434#endif
1435#ifdef FEAT_DND
1436 case K_DROP: return 0;
1437#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001438 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001439 case K_PS: vterm_keyboard_start_paste(vterm);
1440 other = TRUE;
1441 break;
1442 case K_PE: vterm_keyboard_end_paste(vterm);
1443 other = TRUE;
1444 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001445 }
1446
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001447 // add modifiers for the typed key
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001448 if (modmask & MOD_MASK_SHIFT)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001449 mod |= VTERM_MOD_SHIFT;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001450 if (modmask & MOD_MASK_CTRL)
Bram Moolenaar459fd782019-10-13 16:43:39 +02001451 mod |= VTERM_MOD_CTRL;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01001452 if (modmask & (MOD_MASK_ALT | MOD_MASK_META))
Bram Moolenaar459fd782019-10-13 16:43:39 +02001453 mod |= VTERM_MOD_ALT;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02001454
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001455 /*
1456 * Convert special keys to vterm keys:
1457 * - Write keys to vterm: vterm_keyboard_key()
1458 * - Write output to channel.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001459 */
1460 if (key != VTERM_KEY_NONE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001461 // Special key, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001462 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001463 else if (!other)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001464 // Normal character, let vterm convert it.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001465 vterm_keyboard_unichar(vterm, c, mod);
1466
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001467 // Read back the converted escape sequence.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001468 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1469}
1470
1471/*
1472 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001473 * If "check_job_status" is TRUE update the job status.
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001474 * NOTE: "term" may be freed by callbacks.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001475 */
1476 static int
1477term_job_running_check(term_T *term, int check_job_status)
1478{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001479 // Also consider the job finished when the channel is closed, to avoid a
1480 // race condition when updating the title.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001481 if (term != NULL
1482 && term->tl_job != NULL
1483 && channel_is_open(term->tl_job->jv_channel))
1484 {
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001485 job_T *job = term->tl_job;
1486
1487 // Careful: Checking the job status may invoked callbacks, which close
1488 // the buffer and terminate "term". However, "job" will not be freed
1489 // yet.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001490 if (check_job_status)
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01001491 job_status(job);
1492 return (job->jv_status == JOB_STARTED
1493 || (job->jv_channel != NULL && job->jv_channel->ch_keep_open));
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001494 }
1495 return FALSE;
1496}
1497
1498/*
1499 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001500 */
1501 int
1502term_job_running(term_T *term)
1503{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001504 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001505}
1506
1507/*
1508 * Return TRUE if "term" has an active channel and used ":term NONE".
1509 */
1510 int
1511term_none_open(term_T *term)
1512{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001513 // Also consider the job finished when the channel is closed, to avoid a
1514 // race condition when updating the title.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001515 return term != NULL
1516 && term->tl_job != NULL
1517 && channel_is_open(term->tl_job->jv_channel)
1518 && term->tl_job->jv_channel->ch_keep_open;
1519}
1520
1521/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001522 * Used when exiting: kill the job in "buf" if so desired.
1523 * Return OK when the job finished.
1524 * Return FAIL when the job is still running.
1525 */
1526 int
1527term_try_stop_job(buf_T *buf)
1528{
1529 int count;
1530 char *how = (char *)buf->b_term->tl_kill;
1531
1532#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1533 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1534 {
1535 char_u buff[DIALOG_MSG_SIZE];
1536 int ret;
1537
1538 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1539 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1540 if (ret == VIM_YES)
1541 how = "kill";
1542 else if (ret == VIM_CANCEL)
1543 return FAIL;
1544 }
1545#endif
1546 if (how == NULL || *how == NUL)
1547 return FAIL;
1548
1549 job_stop(buf->b_term->tl_job, NULL, how);
1550
Bram Moolenaar9172d232019-01-29 23:06:54 +01001551 // wait for up to a second for the job to die
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001552 for (count = 0; count < 100; ++count)
1553 {
Bram Moolenaar9172d232019-01-29 23:06:54 +01001554 job_T *job;
1555
1556 // buffer, terminal and job may be cleaned up while waiting
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001557 if (!buf_valid(buf)
1558 || buf->b_term == NULL
1559 || buf->b_term->tl_job == NULL)
1560 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001561 job = buf->b_term->tl_job;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001562
Bram Moolenaar9172d232019-01-29 23:06:54 +01001563 // Call job_status() to update jv_status. It may cause the job to be
1564 // cleaned up but it won't be freed.
1565 job_status(job);
1566 if (job->jv_status >= JOB_ENDED)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001567 return OK;
Bram Moolenaar9172d232019-01-29 23:06:54 +01001568
Bram Moolenaar8f7ab4b2019-10-23 23:16:45 +02001569 ui_delay(10L, TRUE);
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02001570 term_flush_messages();
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001571 }
1572 return FAIL;
1573}
1574
1575/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576 * Add the last line of the scrollback buffer to the buffer in the window.
1577 */
1578 static void
1579add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1580{
1581 buf_T *buf = term->tl_buffer;
1582 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1583 linenr_T lnum = buf->b_ml.ml_line_count;
1584
Bram Moolenaar4f974752019-02-17 17:44:42 +01001585#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001586 if (!enc_utf8 && enc_codepage > 0)
1587 {
1588 WCHAR *ret = NULL;
1589 int length = 0;
1590
1591 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1592 &ret, &length);
1593 if (ret != NULL)
1594 {
1595 WideCharToMultiByte_alloc(enc_codepage, 0,
1596 ret, length, (char **)&text, &len, 0, 0);
1597 vim_free(ret);
1598 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1599 vim_free(text);
1600 }
1601 }
1602 else
1603#endif
1604 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1605 if (empty)
1606 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001607 // Delete the empty line that was in the empty buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001608 curbuf = buf;
1609 ml_delete(1, FALSE);
1610 curbuf = curwin->w_buffer;
1611 }
1612}
1613
1614 static void
1615cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1616{
1617 attr->width = cell->width;
1618 attr->attrs = cell->attrs;
1619 attr->fg = cell->fg;
1620 attr->bg = cell->bg;
1621}
1622
1623 static int
1624equal_celattr(cellattr_T *a, cellattr_T *b)
1625{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001626 // Comparing the colors should be sufficient.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001627 return a->fg.red == b->fg.red
1628 && a->fg.green == b->fg.green
1629 && a->fg.blue == b->fg.blue
1630 && a->bg.red == b->bg.red
1631 && a->bg.green == b->bg.green
1632 && a->bg.blue == b->bg.blue;
1633}
1634
Bram Moolenaard96ff162018-02-18 22:13:29 +01001635/*
1636 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1637 * line at this position. Otherwise at the end.
1638 */
1639 static int
1640add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1641{
1642 if (ga_grow(&term->tl_scrollback, 1) == OK)
1643 {
1644 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1645 + term->tl_scrollback.ga_len;
1646
1647 if (lnum > 0)
1648 {
1649 int i;
1650
1651 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1652 {
1653 *line = *(line - 1);
1654 --line;
1655 }
1656 }
1657 line->sb_cols = 0;
1658 line->sb_cells = NULL;
1659 line->sb_fill_attr = *fill_attr;
1660 ++term->tl_scrollback.ga_len;
1661 return OK;
1662 }
1663 return FALSE;
1664}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001665
1666/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001667 * Remove the terminal contents from the scrollback and the buffer.
1668 * Used before adding a new scrollback line or updating the buffer for lines
1669 * displayed in the terminal.
1670 */
1671 static void
1672cleanup_scrollback(term_T *term)
1673{
1674 sb_line_T *line;
1675 garray_T *gap;
1676
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001677 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001678 gap = &term->tl_scrollback;
1679 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1680 && gap->ga_len > 0)
1681 {
1682 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1683 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1684 vim_free(line->sb_cells);
1685 --gap->ga_len;
1686 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001687 curbuf = curwin->w_buffer;
1688 if (curbuf == term->tl_buffer)
1689 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001690}
1691
1692/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001693 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001694 */
1695 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001696update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001697{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001698 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001699 int len;
1700 int lines_skipped = 0;
1701 VTermPos pos;
1702 VTermScreenCell cell;
1703 cellattr_T fill_attr, new_fill_attr;
1704 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001705
1706 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1707 "Adding terminal window snapshot to buffer");
1708
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001709 // First remove the lines that were appended before, they might be
1710 // outdated.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001711 cleanup_scrollback(term);
1712
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 screen = vterm_obtain_screen(term->tl_vterm);
1714 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001715 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1716 {
1717 len = 0;
1718 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1719 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1720 && cell.chars[0] != NUL)
1721 {
1722 len = pos.col + 1;
1723 new_fill_attr = term->tl_default_color;
1724 }
1725 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001726 // Assume the last attr is the filler attr.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001727 cell2cellattr(&cell, &new_fill_attr);
1728
1729 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1730 ++lines_skipped;
1731 else
1732 {
1733 while (lines_skipped > 0)
1734 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001735 // Line was skipped, add an empty line.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001737 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001738 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001739 }
1740
1741 if (len == 0)
1742 p = NULL;
1743 else
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001744 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001745 if ((p != NULL || len == 0)
1746 && ga_grow(&term->tl_scrollback, 1) == OK)
1747 {
1748 garray_T ga;
1749 int width;
1750 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1751 + term->tl_scrollback.ga_len;
1752
1753 ga_init2(&ga, 1, 100);
1754 for (pos.col = 0; pos.col < len; pos.col += width)
1755 {
1756 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1757 {
1758 width = 1;
Bram Moolenaara80faa82020-04-12 19:37:17 +02001759 CLEAR_POINTER(p + pos.col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001760 if (ga_grow(&ga, 1) == OK)
1761 ga.ga_len += utf_char2bytes(' ',
1762 (char_u *)ga.ga_data + ga.ga_len);
1763 }
1764 else
1765 {
1766 width = cell.width;
1767
1768 cell2cellattr(&cell, &p[pos.col]);
1769
Bram Moolenaara79fd562018-12-20 20:47:32 +01001770 // Each character can be up to 6 bytes.
1771 if (ga_grow(&ga, VTERM_MAX_CHARS_PER_CELL * 6) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772 {
1773 int i;
1774 int c;
1775
1776 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1777 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1778 (char_u *)ga.ga_data + ga.ga_len);
1779 }
1780 }
1781 }
1782 line->sb_cols = len;
1783 line->sb_cells = p;
1784 line->sb_fill_attr = new_fill_attr;
1785 fill_attr = new_fill_attr;
1786 ++term->tl_scrollback.ga_len;
1787
1788 if (ga_grow(&ga, 1) == FAIL)
1789 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1790 else
1791 {
1792 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1793 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1794 }
1795 ga_clear(&ga);
1796 }
1797 else
1798 vim_free(p);
1799 }
1800 }
1801
Bram Moolenaarf3aea592018-11-11 22:18:21 +01001802 // Add trailing empty lines.
1803 for (pos.row = term->tl_scrollback.ga_len;
1804 pos.row < term->tl_scrollback_scrolled + term->tl_cursor_pos.row;
1805 ++pos.row)
1806 {
1807 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
1808 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1809 }
1810
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001811 term->tl_dirty_snapshot = FALSE;
1812#ifdef FEAT_TIMERS
1813 term->tl_timer_set = FALSE;
1814#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001815}
1816
1817/*
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001818 * Loop over all windows in the current tab, and also curwin, which is not
1819 * encountered when using a terminal in a popup window.
1820 * Return TRUE if "*wp" was set to the next window.
1821 */
1822 static int
1823for_all_windows_and_curwin(win_T **wp, int *did_curwin)
1824{
1825 if (*wp == NULL)
1826 *wp = firstwin;
1827 else if ((*wp)->w_next != NULL)
1828 *wp = (*wp)->w_next;
1829 else if (!*did_curwin)
1830 *wp = curwin;
1831 else
1832 return FALSE;
1833 if (*wp == curwin)
1834 *did_curwin = TRUE;
1835 return TRUE;
1836}
1837
1838/*
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001839 * If needed, add the current lines of the terminal to scrollback and to the
1840 * buffer. Called after the job has ended and when switching to
1841 * Terminal-Normal mode.
1842 * When "redraw" is TRUE redraw the windows that show the terminal.
1843 */
1844 static void
1845may_move_terminal_to_buffer(term_T *term, int redraw)
1846{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001847 if (term->tl_vterm == NULL)
1848 return;
1849
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001850 // Update the snapshot only if something changes or the buffer does not
1851 // have all the lines.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001852 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1853 <= term->tl_scrollback_scrolled)
1854 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001855
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001856 // Obtain the current background color.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1858 &term->tl_default_color.fg, &term->tl_default_color.bg);
1859
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001860 if (redraw)
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001861 {
1862 win_T *wp = NULL;
1863 int did_curwin = FALSE;
1864
1865 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001867 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001868 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001869 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1870 wp->w_cursor.col = 0;
1871 wp->w_valid = 0;
1872 if (wp->w_cursor.lnum >= wp->w_height)
1873 {
1874 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001875
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001876 if (wp->w_topline < min_topline)
1877 wp->w_topline = min_topline;
1878 }
1879 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001880 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001881 }
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001882 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001883}
1884
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001885#if defined(FEAT_TIMERS) || defined(PROTO)
1886/*
1887 * Check if any terminal timer expired. If so, copy text from the terminal to
1888 * the buffer.
1889 * Return the time until the next timer will expire.
1890 */
1891 int
1892term_check_timers(int next_due_arg, proftime_T *now)
1893{
1894 term_T *term;
1895 int next_due = next_due_arg;
1896
Bram Moolenaaraeea7212020-04-02 18:50:46 +02001897 FOR_ALL_TERMS(term)
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001898 {
1899 if (term->tl_timer_set && !term->tl_normal_mode)
1900 {
1901 long this_due = proftime_time_left(&term->tl_timer_due, now);
1902
1903 if (this_due <= 1)
1904 {
1905 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001906 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001907 }
1908 else if (next_due == -1 || next_due > this_due)
1909 next_due = this_due;
1910 }
1911 }
1912
1913 return next_due;
1914}
1915#endif
1916
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001917/*
1918 * When "normal_mode" is TRUE set the terminal to Terminal-Normal mode,
1919 * otherwise end it.
1920 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001921 static void
1922set_terminal_mode(term_T *term, int normal_mode)
1923{
1924 term->tl_normal_mode = normal_mode;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001925 if (!normal_mode)
1926 handle_postponed_scrollback(term);
Bram Moolenaard23a8232018-02-10 18:45:26 +01001927 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001928 if (term->tl_buffer == curbuf)
1929 maketitle();
1930}
1931
1932/*
1933 * Called after the job if finished and Terminal mode is not active:
1934 * Move the vterm contents into the scrollback buffer and free the vterm.
1935 */
1936 static void
1937cleanup_vterm(term_T *term)
1938{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01001939 set_terminal_mode(term, FALSE);
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001940 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001941 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001942 term_free_vterm(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001943}
1944
1945/*
1946 * Switch from Terminal-Job mode to Terminal-Normal mode.
1947 * Suspends updating the terminal window.
1948 */
1949 static void
1950term_enter_normal_mode(void)
1951{
1952 term_T *term = curbuf->b_term;
1953
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001954 set_terminal_mode(term, TRUE);
1955
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001956 // Append the current terminal contents to the buffer.
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001957 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001958
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001959 // Move the window cursor to the position of the cursor in the
1960 // terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001961 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1962 + term->tl_cursor_pos.row + 1;
1963 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001964 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1965 coladvance(MAXCOL);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001966 curwin->w_set_curswant = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001967
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01001968 // Display the same lines as in the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001969 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1970}
1971
1972/*
1973 * Returns TRUE if the current window contains a terminal and we are in
1974 * Terminal-Normal mode.
1975 */
1976 int
1977term_in_normal_mode(void)
1978{
1979 term_T *term = curbuf->b_term;
1980
1981 return term != NULL && term->tl_normal_mode;
1982}
1983
1984/*
1985 * Switch from Terminal-Normal mode to Terminal-Job mode.
1986 * Restores updating the terminal window.
1987 */
1988 void
1989term_enter_job_mode()
1990{
1991 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001992
1993 set_terminal_mode(term, FALSE);
1994
1995 if (term->tl_channel_closed)
1996 cleanup_vterm(term);
1997 redraw_buf_and_status_later(curbuf, NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01001998#ifdef FEAT_PROP_POPUP
1999 if (WIN_IS_POPUP(curwin))
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01002000 redraw_later(NOT_VALID);
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002001#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002002}
2003
2004/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002005 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002006 * Note: while waiting a terminal may be closed and freed if the channel is
2007 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008 */
2009 static int
2010term_vgetc()
2011{
2012 int c;
2013 int save_State = State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002014 int modify_other_keys =
2015 vterm_is_modify_other_keys(curbuf->b_term->tl_vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002016
2017 State = TERMINAL;
2018 got_int = FALSE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002019#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002020 ctrl_break_was_pressed = FALSE;
2021#endif
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002022 if (modify_other_keys)
2023 ++no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002024 c = vgetc();
2025 got_int = FALSE;
2026 State = save_State;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002027 if (modify_other_keys)
2028 --no_reduce_keys;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002029 return c;
2030}
2031
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002032static int mouse_was_outside = FALSE;
2033
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002034/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002035 * Send key "c" with modifiers "modmask" to terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002036 * Return FAIL when the key needs to be handled in Normal mode.
2037 * Return OK when the key was dropped or sent to the terminal.
2038 */
2039 int
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002040send_keys_to_term(term_T *term, int c, int modmask, int typed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002041{
2042 char msg[KEY_BUF_LEN];
2043 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002044 int dragging_outside = FALSE;
2045
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002046 // Catch keys that need to be handled as in Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002047 switch (c)
2048 {
2049 case NUL:
2050 case K_ZERO:
2051 if (typed)
2052 stuffcharReadbuff(c);
2053 return FAIL;
2054
Bram Moolenaar231a2db2018-05-06 13:53:50 +02002055 case K_TABLINE:
2056 stuffcharReadbuff(c);
2057 return FAIL;
2058
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002059 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002060 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002061 return FAIL;
2062
2063 case K_LEFTDRAG:
2064 case K_MIDDLEDRAG:
2065 case K_RIGHTDRAG:
2066 case K_X1DRAG:
2067 case K_X2DRAG:
2068 dragging_outside = mouse_was_outside;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002069 // FALLTHROUGH
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002070 case K_LEFTMOUSE:
2071 case K_LEFTMOUSE_NM:
2072 case K_LEFTRELEASE:
2073 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01002074 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002075 case K_MIDDLEMOUSE:
2076 case K_MIDDLERELEASE:
2077 case K_RIGHTMOUSE:
2078 case K_RIGHTRELEASE:
2079 case K_X1MOUSE:
2080 case K_X1RELEASE:
2081 case K_X2MOUSE:
2082 case K_X2RELEASE:
2083
2084 case K_MOUSEUP:
2085 case K_MOUSEDOWN:
2086 case K_MOUSELEFT:
2087 case K_MOUSERIGHT:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002088 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002089 int row = mouse_row;
2090 int col = mouse_col;
2091
2092#ifdef FEAT_PROP_POPUP
2093 if (popup_is_popup(curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002094 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002095 row -= popup_top_extra(curwin);
2096 col -= popup_left_extra(curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002097 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002098#endif
2099 if (row < W_WINROW(curwin)
2100 || row >= (W_WINROW(curwin) + curwin->w_height)
2101 || col < curwin->w_wincol
2102 || col >= W_ENDCOL(curwin)
2103 || dragging_outside)
2104 {
2105 // click or scroll outside the current window or on status
2106 // line or vertical separator
2107 if (typed)
2108 {
2109 stuffcharReadbuff(c);
2110 mouse_was_outside = TRUE;
2111 }
2112 return FAIL;
2113 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002114 }
2115 }
2116 if (typed)
2117 mouse_was_outside = FALSE;
2118
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002119 // Convert the typed key to a sequence of bytes for the job.
2120 len = term_convert_key(term, c, modmask, msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 if (len > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002122 // TODO: if FAIL is returned, stop?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002123 channel_send(term->tl_job->jv_channel, get_tty_part(term),
2124 (char_u *)msg, (int)len, NULL);
2125
2126 return OK;
2127}
2128
2129 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002130position_cursor(win_T *wp, VTermPos *pos, int add_off UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002131{
2132 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
2133 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002134#ifdef FEAT_PROP_POPUP
2135 if (add_off && popup_is_popup(curwin))
2136 {
2137 wp->w_wrow += popup_top_extra(curwin);
2138 wp->w_wcol += popup_left_extra(curwin);
2139 }
2140#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002141 wp->w_valid |= (VALID_WCOL|VALID_WROW);
2142}
2143
2144/*
2145 * Handle CTRL-W "": send register contents to the job.
2146 */
2147 static void
2148term_paste_register(int prev_c UNUSED)
2149{
2150 int c;
2151 list_T *l;
2152 listitem_T *item;
2153 long reglen = 0;
2154 int type;
2155
2156#ifdef FEAT_CMDL_INFO
2157 if (add_to_showcmd(prev_c))
2158 if (add_to_showcmd('"'))
2159 out_flush();
2160#endif
2161 c = term_vgetc();
2162#ifdef FEAT_CMDL_INFO
2163 clear_showcmd();
2164#endif
2165 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002166 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002167 return;
2168
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002169 // CTRL-W "= prompt for expression to evaluate.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002170 if (c == '=' && get_expr_register() != '=')
2171 return;
2172 if (!term_use_loop())
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002173 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 return;
2175
2176 l = (list_T *)get_reg_contents(c, GREG_LIST);
2177 if (l != NULL)
2178 {
2179 type = get_reg_type(c, &reglen);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002180 FOR_ALL_LIST_ITEMS(l, item)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002181 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01002182 char_u *s = tv_get_string(&item->li_tv);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002183#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002184 char_u *tmp = s;
2185
2186 if (!enc_utf8 && enc_codepage > 0)
2187 {
2188 WCHAR *ret = NULL;
2189 int length = 0;
2190
2191 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
2192 (int)STRLEN(s), &ret, &length);
2193 if (ret != NULL)
2194 {
2195 WideCharToMultiByte_alloc(CP_UTF8, 0,
2196 ret, length, (char **)&s, &length, 0, 0);
2197 vim_free(ret);
2198 }
2199 }
2200#endif
2201 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2202 s, (int)STRLEN(s), NULL);
Bram Moolenaar4f974752019-02-17 17:44:42 +01002203#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 if (tmp != s)
2205 vim_free(s);
2206#endif
2207
2208 if (item->li_next != NULL || type == MLINE)
2209 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
2210 (char_u *)"\r", 1, NULL);
2211 }
2212 list_free(l);
2213 }
2214}
2215
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002217 * Return TRUE when waiting for a character in the terminal, the cursor of the
2218 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219 */
2220 int
2221terminal_is_active()
2222{
2223 return in_terminal_loop != NULL;
2224}
2225
Bram Moolenaar83d47902020-03-26 20:34:00 +01002226/*
2227 * Return the highight group name for the terminal; "Terminal" if not set.
2228 */
2229 static char_u *
2230term_get_highlight_name(term_T *term)
2231{
2232 if (term->tl_highlight_name == NULL)
2233 return (char_u *)"Terminal";
2234 return term->tl_highlight_name;
2235}
2236
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02002237#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002238 cursorentry_T *
2239term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
2240{
2241 term_T *term = in_terminal_loop;
2242 static cursorentry_T entry;
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002243 int id;
2244 guicolor_T term_fg, term_bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002245
Bram Moolenaara80faa82020-04-12 19:37:17 +02002246 CLEAR_FIELD(entry);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002247 entry.shape = entry.mshape =
2248 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
2249 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
2250 SHAPE_BLOCK;
2251 entry.percentage = 20;
2252 if (term->tl_cursor_blink)
2253 {
2254 entry.blinkwait = 700;
2255 entry.blinkon = 400;
2256 entry.blinkoff = 250;
2257 }
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002258
Bram Moolenaar83d47902020-03-26 20:34:00 +01002259 // The highlight group overrules the defaults.
2260 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002261 if (id != 0)
2262 {
2263 syn_id2colors(id, &term_fg, &term_bg);
2264 *fg = term_bg;
2265 }
2266 else
2267 *fg = gui.back_pixel;
2268
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002269 if (term->tl_cursor_color == NULL)
Bram Moolenaar29e7fe52018-10-16 22:13:00 +02002270 {
2271 if (id != 0)
2272 *bg = term_fg;
2273 else
2274 *bg = gui.norm_pixel;
2275 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002276 else
2277 *bg = color_name2handle(term->tl_cursor_color);
2278 entry.name = "n";
2279 entry.used_for = SHAPE_CURSOR;
2280
2281 return &entry;
2282}
2283#endif
2284
Bram Moolenaard317b382018-02-08 22:33:31 +01002285 static void
2286may_output_cursor_props(void)
2287{
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002288 if (!cursor_color_equal(last_set_cursor_color, desired_cursor_color)
Bram Moolenaard317b382018-02-08 22:33:31 +01002289 || last_set_cursor_shape != desired_cursor_shape
2290 || last_set_cursor_blink != desired_cursor_blink)
2291 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002292 cursor_color_copy(&last_set_cursor_color, desired_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002293 last_set_cursor_shape = desired_cursor_shape;
2294 last_set_cursor_blink = desired_cursor_blink;
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002295 term_cursor_color(cursor_color_get(desired_cursor_color));
Bram Moolenaard317b382018-02-08 22:33:31 +01002296 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002297 // this will restore the initial cursor style, if possible
Bram Moolenaard317b382018-02-08 22:33:31 +01002298 ui_cursor_shape_forced(TRUE);
2299 else
2300 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
2301 }
2302}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002303
Bram Moolenaard317b382018-02-08 22:33:31 +01002304/*
2305 * Set the cursor color and shape, if not last set to these.
2306 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002307 static void
2308may_set_cursor_props(term_T *term)
2309{
2310#ifdef FEAT_GUI
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002311 // For the GUI the cursor properties are obtained with
2312 // term_get_cursor_shape().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002313 if (gui.in_use)
2314 return;
2315#endif
2316 if (in_terminal_loop == term)
2317 {
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002318 cursor_color_copy(&desired_cursor_color, term->tl_cursor_color);
Bram Moolenaard317b382018-02-08 22:33:31 +01002319 desired_cursor_shape = term->tl_cursor_shape;
2320 desired_cursor_blink = term->tl_cursor_blink;
2321 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002322 }
2323}
2324
Bram Moolenaard317b382018-02-08 22:33:31 +01002325/*
2326 * Reset the desired cursor properties and restore them when needed.
2327 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002328 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002329prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002330{
2331#ifdef FEAT_GUI
2332 if (gui.in_use)
2333 return;
2334#endif
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02002335 cursor_color_copy(&desired_cursor_color, NULL);
Bram Moolenaard317b382018-02-08 22:33:31 +01002336 desired_cursor_shape = -1;
2337 desired_cursor_blink = -1;
2338 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002339}
2340
2341/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002342 * Returns TRUE if the current window contains a terminal and we are sending
2343 * keys to the job.
2344 * If "check_job_status" is TRUE update the job status.
2345 */
2346 static int
2347term_use_loop_check(int check_job_status)
2348{
2349 term_T *term = curbuf->b_term;
2350
2351 return term != NULL
2352 && !term->tl_normal_mode
2353 && term->tl_vterm != NULL
2354 && term_job_running_check(term, check_job_status);
2355}
2356
2357/*
2358 * Returns TRUE if the current window contains a terminal and we are sending
2359 * keys to the job.
2360 */
2361 int
2362term_use_loop(void)
2363{
2364 return term_use_loop_check(FALSE);
2365}
2366
2367/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002368 * Called when entering a window with the mouse. If this is a terminal window
2369 * we may want to change state.
2370 */
2371 void
2372term_win_entered()
2373{
2374 term_T *term = curbuf->b_term;
2375
2376 if (term != NULL)
2377 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002378 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002379 {
2380 reset_VIsual_and_resel();
2381 if (State & INSERT)
2382 stop_insert_mode = TRUE;
2383 }
2384 mouse_was_outside = FALSE;
2385 enter_mouse_col = mouse_col;
2386 enter_mouse_row = mouse_row;
2387 }
2388}
2389
2390/*
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002391 * vgetc() may not include CTRL in the key when modify_other_keys is set.
2392 * Return the Ctrl-key value in that case.
2393 */
2394 static int
2395raw_c_to_ctrl(int c)
2396{
2397 if ((mod_mask & MOD_MASK_CTRL)
2398 && ((c >= '`' && c <= 0x7f) || (c >= '@' && c <= '_')))
2399 return c & 0x1f;
2400 return c;
2401}
2402
2403/*
2404 * When modify_other_keys is set then do the reverse of raw_c_to_ctrl().
2405 * May set "mod_mask".
2406 */
2407 static int
2408ctrl_to_raw_c(int c)
2409{
2410 if (c < 0x20 && vterm_is_modify_other_keys(curbuf->b_term->tl_vterm))
2411 {
2412 mod_mask |= MOD_MASK_CTRL;
2413 return c + '@';
2414 }
2415 return c;
2416}
2417
2418/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 * Wait for input and send it to the job.
2420 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2421 * when there is no more typahead.
2422 * Return when the start of a CTRL-W command is typed or anything else that
2423 * should be handled as a Normal mode command.
2424 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2425 * the terminal was closed.
2426 */
2427 int
2428terminal_loop(int blocking)
2429{
2430 int c;
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002431 int raw_c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002432 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002433 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002434#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002435 int tty_fd = curbuf->b_term->tl_job->jv_channel
2436 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002437#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002438 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002439
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002440 // Remember the terminal we are sending keys to. However, the terminal
2441 // might be closed while waiting for a character, e.g. typing "exit" in a
2442 // shell and ++close was used. Therefore use curbuf->b_term instead of a
2443 // stored reference.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002444 in_terminal_loop = curbuf->b_term;
2445
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002446 if (*curwin->w_p_twk != NUL)
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002447 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002448 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002449 if (termwinkey == Ctrl_W)
2450 termwinkey = 0;
2451 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002452 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002453 may_set_cursor_props(curbuf->b_term);
2454
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002455 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002456 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002457#ifdef FEAT_GUI
2458 if (!curbuf->b_term->tl_system)
2459#endif
Bram Moolenaar2a4857a2019-01-29 22:29:07 +01002460 // TODO: skip screen update when handling a sequence of keys.
2461 // Repeat redrawing in case a message is received while redrawing.
Bram Moolenaar13568252018-03-16 20:46:58 +01002462 while (must_redraw != 0)
2463 if (update_screen(0) == FAIL)
2464 break;
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002465 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002466 // job finished while redrawing
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002467 break;
2468
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002469 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002470 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002471
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002472 raw_c = term_vgetc();
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002473 if (!term_use_loop_check(TRUE) || in_terminal_loop != curbuf->b_term)
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002474 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002475 // Job finished while waiting for a character. Push back the
2476 // received character.
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002477 if (raw_c != K_IGNORE)
2478 vungetc(raw_c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002480 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002481 if (raw_c == K_IGNORE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002482 continue;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002483 c = raw_c_to_ctrl(raw_c);
Bram Moolenaar6a0299d2019-10-10 21:14:03 +02002484
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002485#ifdef UNIX
2486 /*
2487 * The shell or another program may change the tty settings. Getting
2488 * them for every typed character is a bit of overhead, but it's needed
2489 * for the first character typed, e.g. when Vim starts in a shell.
2490 */
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01002491 if (mch_isatty(tty_fd))
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002492 {
2493 ttyinfo_T info;
2494
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002495 // Get the current backspace character of the pty.
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002496 if (get_tty_info(tty_fd, &info) == OK)
2497 term_backspace_char = info.backspace;
2498 }
2499#endif
2500
Bram Moolenaar4f974752019-02-17 17:44:42 +01002501#ifdef MSWIN
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002502 // On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2503 // Use CTRL-BREAK to kill the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002504 if (ctrl_break_was_pressed)
2505 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2506#endif
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002507 // Was either CTRL-W (termwinkey) or CTRL-\ pressed?
2508 // Not in a system terminal.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002509 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002510#ifdef FEAT_GUI
2511 && !curbuf->b_term->tl_system
2512#endif
2513 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002514 {
2515 int prev_c = c;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002516 int prev_raw_c = raw_c;
2517 int prev_mod_mask = mod_mask;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002518
2519#ifdef FEAT_CMDL_INFO
2520 if (add_to_showcmd(c))
2521 out_flush();
2522#endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002523 raw_c = term_vgetc();
2524 c = raw_c_to_ctrl(raw_c);
2525
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526#ifdef FEAT_CMDL_INFO
2527 clear_showcmd();
2528#endif
Bram Moolenaar05af9a42018-05-21 18:48:12 +02002529 if (!term_use_loop_check(TRUE)
2530 || in_terminal_loop != curbuf->b_term)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002531 // job finished while waiting for a character
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002532 break;
2533
2534 if (prev_c == Ctrl_BSL)
2535 {
2536 if (c == Ctrl_N)
2537 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002538 // CTRL-\ CTRL-N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539 term_enter_normal_mode();
2540 ret = FAIL;
2541 goto theend;
2542 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002543 // Send both keys to the terminal, first one here, second one
2544 // below.
2545 send_keys_to_term(curbuf->b_term, prev_raw_c, prev_mod_mask,
2546 TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002547 }
2548 else if (c == Ctrl_C)
2549 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002550 // "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2552 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002553 else if (c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002555 // "CTRL-W .": send CTRL-W to the job
2556 // "'termwinkey' .": send 'termwinkey' to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002557 raw_c = ctrl_to_raw_c(termwinkey == 0 ? Ctrl_W : termwinkey);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002558 }
Bram Moolenaardcdeaaf2018-06-17 22:19:12 +02002559 else if (c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002560 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002561 // "CTRL-W CTRL-\": send CTRL-\ to the job
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002562 raw_c = ctrl_to_raw_c(Ctrl_BSL);
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002563 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564 else if (c == 'N')
2565 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002566 // CTRL-W N : go to Terminal-Normal mode.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567 term_enter_normal_mode();
2568 ret = FAIL;
2569 goto theend;
2570 }
2571 else if (c == '"')
2572 {
2573 term_paste_register(prev_c);
2574 continue;
2575 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002576 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002577 {
Bram Moolenaara4b26992019-08-15 20:58:54 +02002578 char_u buf[MB_MAXBYTES + 2];
2579
2580 // Put the command into the typeahead buffer, when using the
2581 // stuff buffer KeyStuffed is set and 'langmap' won't be used.
2582 buf[0] = Ctrl_W;
2583 buf[(*mb_char2bytes)(c, buf + 1) + 1] = NUL;
2584 ins_typebuf(buf, REMAP_NONE, 0, TRUE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002585 ret = OK;
2586 goto theend;
2587 }
2588 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01002589# ifdef MSWIN
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002590 if (!enc_utf8 && has_mbyte && raw_c >= 0x80)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002591 {
2592 WCHAR wc;
2593 char_u mb[3];
2594
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002595 mb[0] = (unsigned)raw_c >> 8;
2596 mb[1] = raw_c;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002597 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002598 raw_c = wc;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002599 }
2600# endif
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002601 if (send_keys_to_term(curbuf->b_term, raw_c, mod_mask, TRUE) != OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002602 {
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01002603 if (raw_c == K_MOUSEMOVE)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002604 // We are sure to come back here, don't reset the cursor color
2605 // and shape to avoid flickering.
Bram Moolenaard317b382018-02-08 22:33:31 +01002606 restore_cursor = FALSE;
2607
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002608 ret = OK;
2609 goto theend;
2610 }
2611 }
2612 ret = FAIL;
2613
2614theend:
2615 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002616 if (restore_cursor)
2617 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002618
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002619 // Move a snapshot of the screen contents to the buffer, so that completion
2620 // works in other buffers.
Bram Moolenaar620020e2018-05-13 19:06:12 +02002621 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2622 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002623
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624 return ret;
2625}
2626
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 static void
2628may_toggle_cursor(term_T *term)
2629{
2630 if (in_terminal_loop == term)
2631 {
2632 if (term->tl_cursor_visible)
2633 cursor_on();
2634 else
2635 cursor_off();
2636 }
2637}
2638
2639/*
Bram Moolenaar83d47902020-03-26 20:34:00 +01002640 * Cache "Terminal" highlight group colors.
2641 */
2642 void
2643set_terminal_default_colors(int cterm_fg, int cterm_bg)
2644{
2645 term_default_cterm_fg = cterm_fg - 1;
2646 term_default_cterm_bg = cterm_bg - 1;
2647}
2648
2649 static int
2650get_default_cterm_fg(term_T *term)
2651{
2652 if (term->tl_highlight_name != NULL)
2653 {
2654 int id = syn_name2id(term->tl_highlight_name);
2655 int fg = -1;
2656 int bg = -1;
2657
2658 if (id > 0)
2659 syn_id2cterm_bg(id, &fg, &bg);
2660 return fg;
2661 }
2662 return term_default_cterm_fg;
2663}
2664
2665 static int
2666get_default_cterm_bg(term_T *term)
2667{
2668 if (term->tl_highlight_name != NULL)
2669 {
2670 int id = syn_name2id(term->tl_highlight_name);
2671 int fg = -1;
2672 int bg = -1;
2673
2674 if (id > 0)
2675 syn_id2cterm_bg(id, &fg, &bg);
2676 return bg;
2677 }
2678 return term_default_cterm_bg;
2679}
2680
2681/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002682 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002683 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002684 */
2685 static int
2686color2index(VTermColor *color, int fg, int *boldp)
2687{
2688 int red = color->red;
2689 int blue = color->blue;
2690 int green = color->green;
2691
Bram Moolenaar46359e12017-11-29 22:33:38 +01002692 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002693 {
Bram Moolenaar1d79ce82019-04-12 22:27:39 +02002694 // The first 16 colors and default: use the ANSI index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002695 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002696 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002697 case 0: return 0;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002698 case 1: return lookup_color( 0, fg, boldp) + 1; // black
2699 case 2: return lookup_color( 4, fg, boldp) + 1; // dark red
2700 case 3: return lookup_color( 2, fg, boldp) + 1; // dark green
2701 case 4: return lookup_color( 6, fg, boldp) + 1; // brown
2702 case 5: return lookup_color( 1, fg, boldp) + 1; // dark blue
2703 case 6: return lookup_color( 5, fg, boldp) + 1; // dark magenta
2704 case 7: return lookup_color( 3, fg, boldp) + 1; // dark cyan
2705 case 8: return lookup_color( 8, fg, boldp) + 1; // light grey
2706 case 9: return lookup_color(12, fg, boldp) + 1; // dark grey
2707 case 10: return lookup_color(20, fg, boldp) + 1; // red
2708 case 11: return lookup_color(16, fg, boldp) + 1; // green
2709 case 12: return lookup_color(24, fg, boldp) + 1; // yellow
2710 case 13: return lookup_color(14, fg, boldp) + 1; // blue
2711 case 14: return lookup_color(22, fg, boldp) + 1; // magenta
2712 case 15: return lookup_color(18, fg, boldp) + 1; // cyan
2713 case 16: return lookup_color(26, fg, boldp) + 1; // white
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002714 }
2715 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 if (t_colors >= 256)
2718 {
2719 if (red == blue && red == green)
2720 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002721 // 24-color greyscale plus white and black
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002722 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002723 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2724 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2725 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002726 int i;
2727
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002728 if (red < 5)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002729 return 17; // 00/00/00
2730 if (red > 245) // ff/ff/ff
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002731 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002732 for (i = 0; i < 23; ++i)
2733 if (red < cutoff[i])
2734 return i + 233;
2735 return 256;
2736 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002737 {
2738 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2739 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002740
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002741 // 216-color cube
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002742 for (ri = 0; ri < 5; ++ri)
2743 if (red < cutoff[ri])
2744 break;
2745 for (gi = 0; gi < 5; ++gi)
2746 if (green < cutoff[gi])
2747 break;
2748 for (bi = 0; bi < 5; ++bi)
2749 if (blue < cutoff[bi])
2750 break;
2751 return 17 + ri * 36 + gi * 6 + bi;
2752 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002753 }
2754 return 0;
2755}
2756
2757/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002758 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002759 */
2760 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002761vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002762{
2763 int attr = 0;
2764
2765 if (cellattrs.bold)
2766 attr |= HL_BOLD;
2767 if (cellattrs.underline)
2768 attr |= HL_UNDERLINE;
2769 if (cellattrs.italic)
2770 attr |= HL_ITALIC;
2771 if (cellattrs.strike)
2772 attr |= HL_STRIKETHROUGH;
2773 if (cellattrs.reverse)
2774 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002775 return attr;
2776}
2777
2778/*
2779 * Store Vterm attributes in "cell" from highlight flags.
2780 */
2781 static void
2782hl2vtermAttr(int attr, cellattr_T *cell)
2783{
Bram Moolenaara80faa82020-04-12 19:37:17 +02002784 CLEAR_FIELD(cell->attrs);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002785 if (attr & HL_BOLD)
2786 cell->attrs.bold = 1;
2787 if (attr & HL_UNDERLINE)
2788 cell->attrs.underline = 1;
2789 if (attr & HL_ITALIC)
2790 cell->attrs.italic = 1;
2791 if (attr & HL_STRIKETHROUGH)
2792 cell->attrs.strike = 1;
2793 if (attr & HL_INVERSE)
2794 cell->attrs.reverse = 1;
2795}
2796
2797/*
2798 * Convert the attributes of a vterm cell into an attribute index.
2799 */
2800 static int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002801cell2attr(
Bram Moolenaar83d47902020-03-26 20:34:00 +01002802 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002803 win_T *wp,
2804 VTermScreenCellAttrs cellattrs,
2805 VTermColor cellfg,
2806 VTermColor cellbg)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002807{
2808 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002809
2810#ifdef FEAT_GUI
2811 if (gui.in_use)
2812 {
2813 guicolor_T fg, bg;
2814
2815 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2816 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2817 return get_gui_attr_idx(attr, fg, bg);
2818 }
2819 else
2820#endif
2821#ifdef FEAT_TERMGUICOLORS
2822 if (p_tgc)
2823 {
2824 guicolor_T fg, bg;
2825
2826 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2827 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2828
2829 return get_tgc_attr_idx(attr, fg, bg);
2830 }
2831 else
2832#endif
2833 {
2834 int bold = MAYBE;
2835 int fg = color2index(&cellfg, TRUE, &bold);
2836 int bg = color2index(&cellbg, FALSE, &bold);
2837
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002838 // Use the 'wincolor' or "Terminal" highlighting for the default
2839 // colors.
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002840 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002841 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002842 int wincolor_fg = -1;
2843 int wincolor_bg = -1;
2844
2845 if (wp != NULL && *wp->w_p_wcr != NUL)
2846 {
2847 int id = syn_name2id(curwin->w_p_wcr);
2848
2849 // Get the 'wincolor' group colors.
2850 if (id > 0)
2851 syn_id2cterm_bg(id, &wincolor_fg, &wincolor_bg);
2852 }
2853 if (fg == 0)
2854 {
2855 if (wincolor_fg >= 0)
2856 fg = wincolor_fg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002857 else
2858 {
2859 int cterm_fg = get_default_cterm_fg(term);
2860
2861 if (cterm_fg >= 0)
2862 fg = cterm_fg + 1;
2863 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002864 }
2865 if (bg == 0)
2866 {
2867 if (wincolor_bg >= 0)
2868 bg = wincolor_bg + 1;
Bram Moolenaar83d47902020-03-26 20:34:00 +01002869 else
2870 {
2871 int cterm_bg = get_default_cterm_bg(term);
2872
2873 if (cterm_bg >= 0)
2874 bg = cterm_bg + 1;
2875 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002876 }
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002877 }
2878
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002879 // with 8 colors set the bold attribute to get a bright foreground
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002880 if (bold == TRUE)
2881 attr |= HL_BOLD;
2882 return get_cterm_attr_idx(attr, fg, bg);
2883 }
2884 return 0;
2885}
2886
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002887 static void
2888set_dirty_snapshot(term_T *term)
2889{
2890 term->tl_dirty_snapshot = TRUE;
2891#ifdef FEAT_TIMERS
2892 if (!term->tl_normal_mode)
2893 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002894 // Update the snapshot after 100 msec of not getting updates.
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002895 profile_setlimit(100L, &term->tl_timer_due);
2896 term->tl_timer_set = TRUE;
2897 }
2898#endif
2899}
2900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002901 static int
2902handle_damage(VTermRect rect, void *user)
2903{
2904 term_T *term = (term_T *)user;
2905
2906 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2907 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002908 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002909 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002910 return 1;
2911}
2912
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002913 static void
2914term_scroll_up(term_T *term, int start_row, int count)
2915{
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002916 win_T *wp = NULL;
2917 int did_curwin = FALSE;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002918 VTermColor fg, bg;
2919 VTermScreenCellAttrs attr;
2920 int clear_attr;
2921
Bram Moolenaara80faa82020-04-12 19:37:17 +02002922 CLEAR_FIELD(attr);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002923
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002924 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002925 {
2926 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002927 {
2928 // Set the color to clear lines with.
2929 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2930 &fg, &bg);
Bram Moolenaar83d47902020-03-26 20:34:00 +01002931 clear_attr = cell2attr(term, wp, attr, fg, bg);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002932 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002933 }
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002934 }
2935}
2936
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002937 static int
2938handle_moverect(VTermRect dest, VTermRect src, void *user)
2939{
2940 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002941 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002942
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002943 // Scrolling up is done much more efficiently by deleting lines instead of
2944 // redrawing the text. But avoid doing this multiple times, postpone until
2945 // the redraw happens.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002946 if (dest.start_col == src.start_col
2947 && dest.end_col == src.end_col
2948 && dest.start_row < src.start_row)
2949 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002950 if (dest.start_row == 0)
2951 term->tl_postponed_scroll += count;
2952 else
2953 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002954 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002955
2956 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2957 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002958 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002959
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01002960 // Note sure if the scrolling will work correctly, let's do a complete
2961 // redraw later.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002962 redraw_buf_later(term->tl_buffer, NOT_VALID);
2963 return 1;
2964}
2965
2966 static int
2967handle_movecursor(
2968 VTermPos pos,
2969 VTermPos oldpos UNUSED,
2970 int visible,
2971 void *user)
2972{
2973 term_T *term = (term_T *)user;
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002974 win_T *wp = NULL;
2975 int did_curwin = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002976
2977 term->tl_cursor_pos = pos;
2978 term->tl_cursor_visible = visible;
2979
Bram Moolenaare52e0c82020-02-28 22:20:10 +01002980 while (for_all_windows_and_curwin(&wp, &did_curwin))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002981 {
2982 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar219c7d02020-02-01 21:57:29 +01002983 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002984 }
2985 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2986 {
2987 may_toggle_cursor(term);
2988 update_cursor(term, term->tl_cursor_visible);
2989 }
2990
2991 return 1;
2992}
2993
2994 static int
2995handle_settermprop(
2996 VTermProp prop,
2997 VTermValue *value,
2998 void *user)
2999{
3000 term_T *term = (term_T *)user;
3001
3002 switch (prop)
3003 {
3004 case VTERM_PROP_TITLE:
3005 vim_free(term->tl_title);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003006 // a blank title isn't useful, make it empty, so that "running" is
3007 // displayed
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003008 if (*skipwhite((char_u *)value->string) == NUL)
3009 term->tl_title = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01003010 // Same as blank
3011 else if (term->tl_arg0_cmd != NULL
3012 && STRNCMP(term->tl_arg0_cmd, (char_u *)value->string,
3013 (int)STRLEN(term->tl_arg0_cmd)) == 0)
3014 term->tl_title = NULL;
3015 // Empty corrupted data of winpty
3016 else if (STRNCMP(" - ", (char_u *)value->string, 4) == 0)
3017 term->tl_title = NULL;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003018#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003019 else if (!enc_utf8 && enc_codepage > 0)
3020 {
3021 WCHAR *ret = NULL;
3022 int length = 0;
3023
3024 MultiByteToWideChar_alloc(CP_UTF8, 0,
3025 (char*)value->string, (int)STRLEN(value->string),
3026 &ret, &length);
3027 if (ret != NULL)
3028 {
3029 WideCharToMultiByte_alloc(enc_codepage, 0,
3030 ret, length, (char**)&term->tl_title,
3031 &length, 0, 0);
3032 vim_free(ret);
3033 }
3034 }
3035#endif
3036 else
3037 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01003038 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003039 if (term == curbuf->b_term)
3040 maketitle();
3041 break;
3042
3043 case VTERM_PROP_CURSORVISIBLE:
3044 term->tl_cursor_visible = value->boolean;
3045 may_toggle_cursor(term);
3046 out_flush();
3047 break;
3048
3049 case VTERM_PROP_CURSORBLINK:
3050 term->tl_cursor_blink = value->boolean;
3051 may_set_cursor_props(term);
3052 break;
3053
3054 case VTERM_PROP_CURSORSHAPE:
3055 term->tl_cursor_shape = value->number;
3056 may_set_cursor_props(term);
3057 break;
3058
3059 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaar4f7fd562018-05-21 14:55:28 +02003060 cursor_color_copy(&term->tl_cursor_color, (char_u*)value->string);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003061 may_set_cursor_props(term);
3062 break;
3063
3064 case VTERM_PROP_ALTSCREEN:
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003065 // TODO: do anything else?
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003066 term->tl_using_altscreen = value->boolean;
3067 break;
3068
3069 default:
3070 break;
3071 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003072 // Always return 1, otherwise vterm doesn't store the value internally.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003073 return 1;
3074}
3075
3076/*
3077 * The job running in the terminal resized the terminal.
3078 */
3079 static int
3080handle_resize(int rows, int cols, void *user)
3081{
3082 term_T *term = (term_T *)user;
3083 win_T *wp;
3084
3085 term->tl_rows = rows;
3086 term->tl_cols = cols;
3087 if (term->tl_vterm_size_changed)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003088 // Size was set by vterm_set_size(), don't set the window size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003089 term->tl_vterm_size_changed = FALSE;
3090 else
3091 {
3092 FOR_ALL_WINDOWS(wp)
3093 {
3094 if (wp->w_buffer == term->tl_buffer)
3095 {
3096 win_setheight_win(rows, wp);
3097 win_setwidth_win(cols, wp);
3098 }
3099 }
3100 redraw_buf_later(term->tl_buffer, NOT_VALID);
3101 }
3102 return 1;
3103}
3104
3105/*
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003106 * If the number of lines that are stored goes over 'termscrollback' then
3107 * delete the first 10%.
3108 * "gap" points to tl_scrollback or tl_scrollback_postponed.
3109 * "update_buffer" is TRUE when the buffer should be updated.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003110 */
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003111 static void
3112limit_scrollback(term_T *term, garray_T *gap, int update_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003113{
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003114 if (gap->ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003115 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02003116 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003117 int i;
3118
3119 curbuf = term->tl_buffer;
3120 for (i = 0; i < todo; ++i)
3121 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003122 vim_free(((sb_line_T *)gap->ga_data + i)->sb_cells);
3123 if (update_buffer)
3124 ml_delete(1, FALSE);
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003125 }
3126 curbuf = curwin->w_buffer;
3127
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003128 gap->ga_len -= todo;
3129 mch_memmove(gap->ga_data,
3130 (sb_line_T *)gap->ga_data + todo,
3131 sizeof(sb_line_T) * gap->ga_len);
3132 if (update_buffer)
3133 term->tl_scrollback_scrolled -= todo;
3134 }
3135}
3136
3137/*
3138 * Handle a line that is pushed off the top of the screen.
3139 */
3140 static int
3141handle_pushline(int cols, const VTermScreenCell *cells, void *user)
3142{
3143 term_T *term = (term_T *)user;
3144 garray_T *gap;
3145 int update_buffer;
3146
3147 if (term->tl_normal_mode)
3148 {
3149 // In Terminal-Normal mode the user interacts with the buffer, thus we
3150 // must not change it. Postpone adding the scrollback lines.
3151 gap = &term->tl_scrollback_postponed;
3152 update_buffer = FALSE;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003153 }
3154 else
3155 {
3156 // First remove the lines that were appended before, the pushed line
3157 // goes above it.
3158 cleanup_scrollback(term);
3159 gap = &term->tl_scrollback;
3160 update_buffer = TRUE;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02003161 }
3162
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003163 limit_scrollback(term, gap, update_buffer);
3164
3165 if (ga_grow(gap, 1) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003166 {
3167 cellattr_T *p = NULL;
3168 int len = 0;
3169 int i;
3170 int c;
3171 int col;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003172 int text_len;
3173 char_u *text;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003174 sb_line_T *line;
3175 garray_T ga;
3176 cellattr_T fill_attr = term->tl_default_color;
3177
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003178 // do not store empty cells at the end
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003179 for (i = 0; i < cols; ++i)
3180 if (cells[i].chars[0] != 0)
3181 len = i + 1;
3182 else
3183 cell2cellattr(&cells[i], &fill_attr);
3184
3185 ga_init2(&ga, 1, 100);
3186 if (len > 0)
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003187 p = ALLOC_MULT(cellattr_T, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003188 if (p != NULL)
3189 {
3190 for (col = 0; col < len; col += cells[col].width)
3191 {
3192 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
3193 {
3194 ga.ga_len = 0;
3195 break;
3196 }
3197 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
3198 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
3199 (char_u *)ga.ga_data + ga.ga_len);
3200 cell2cellattr(&cells[col], &p[col]);
3201 }
3202 }
3203 if (ga_grow(&ga, 1) == FAIL)
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003204 {
3205 if (update_buffer)
3206 text = (char_u *)"";
3207 else
3208 text = vim_strsave((char_u *)"");
3209 text_len = 0;
3210 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003211 else
3212 {
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003213 text = ga.ga_data;
3214 text_len = ga.ga_len;
3215 *(text + text_len) = NUL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003216 }
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003217 if (update_buffer)
3218 add_scrollback_line_to_buffer(term, text, text_len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003219
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003220 line = (sb_line_T *)gap->ga_data + gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003221 line->sb_cols = len;
3222 line->sb_cells = p;
3223 line->sb_fill_attr = fill_attr;
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003224 if (update_buffer)
3225 {
3226 line->sb_text = NULL;
3227 ++term->tl_scrollback_scrolled;
3228 ga_clear(&ga); // free the text
3229 }
3230 else
3231 {
3232 line->sb_text = text;
3233 ga_init(&ga); // text is kept in tl_scrollback_postponed
3234 }
3235 ++gap->ga_len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003237 return 0; // ignored
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003238}
3239
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003240/*
3241 * Called when leaving Terminal-Normal mode: deal with any scrollback that was
3242 * received and stored in tl_scrollback_postponed.
3243 */
3244 static void
3245handle_postponed_scrollback(term_T *term)
3246{
3247 int i;
3248
Bram Moolenaar8376c3d2019-03-19 20:50:43 +01003249 if (term->tl_scrollback_postponed.ga_len == 0)
3250 return;
3251 ch_log(NULL, "Moving postponed scrollback to scrollback");
3252
Bram Moolenaar29ae2232019-02-14 21:22:01 +01003253 // First remove the lines that were appended before, the pushed lines go
3254 // above it.
3255 cleanup_scrollback(term);
3256
3257 for (i = 0; i < term->tl_scrollback_postponed.ga_len; ++i)
3258 {
3259 char_u *text;
3260 sb_line_T *pp_line;
3261 sb_line_T *line;
3262
3263 if (ga_grow(&term->tl_scrollback, 1) == FAIL)
3264 break;
3265 pp_line = (sb_line_T *)term->tl_scrollback_postponed.ga_data + i;
3266
3267 text = pp_line->sb_text;
3268 if (text == NULL)
3269 text = (char_u *)"";
3270 add_scrollback_line_to_buffer(term, text, (int)STRLEN(text));
3271 vim_free(pp_line->sb_text);
3272
3273 line = (sb_line_T *)term->tl_scrollback.ga_data
3274 + term->tl_scrollback.ga_len;
3275 line->sb_cols = pp_line->sb_cols;
3276 line->sb_cells = pp_line->sb_cells;
3277 line->sb_fill_attr = pp_line->sb_fill_attr;
3278 line->sb_text = NULL;
3279 ++term->tl_scrollback_scrolled;
3280 ++term->tl_scrollback.ga_len;
3281 }
3282
3283 ga_clear(&term->tl_scrollback_postponed);
3284 limit_scrollback(term, &term->tl_scrollback, TRUE);
3285}
3286
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003287static VTermScreenCallbacks screen_callbacks = {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003288 handle_damage, // damage
3289 handle_moverect, // moverect
3290 handle_movecursor, // movecursor
3291 handle_settermprop, // settermprop
3292 NULL, // bell
3293 handle_resize, // resize
3294 handle_pushline, // sb_pushline
3295 NULL // sb_popline
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003296};
3297
3298/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003299 * Do the work after the channel of a terminal was closed.
3300 * Must be called only when updating_screen is FALSE.
3301 * Returns TRUE when a buffer was closed (list of terminals may have changed).
3302 */
3303 static int
3304term_after_channel_closed(term_T *term)
3305{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003306 // Unless in Terminal-Normal mode: clear the vterm.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003307 if (!term->tl_normal_mode)
3308 {
3309 int fnum = term->tl_buffer->b_fnum;
3310
3311 cleanup_vterm(term);
3312
3313 if (term->tl_finish == TL_FINISH_CLOSE)
3314 {
3315 aco_save_T aco;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003316 int do_set_w_closing = term->tl_buffer->b_nwindows == 0;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003317#ifdef FEAT_PROP_POPUP
3318 win_T *pwin = NULL;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003319
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003320 // If this was a terminal in a popup window, go back to the
3321 // previous window.
3322 if (popup_is_popup(curwin) && curbuf == term->tl_buffer)
3323 {
3324 pwin = curwin;
3325 if (win_valid(prevwin))
3326 win_enter(prevwin, FALSE);
3327 }
3328 else
3329#endif
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003330 // If this is the last normal window: exit Vim.
3331 if (term->tl_buffer->b_nwindows > 0 && only_one_window())
3332 {
3333 exarg_T ea;
3334
Bram Moolenaara80faa82020-04-12 19:37:17 +02003335 CLEAR_FIELD(ea);
Bram Moolenaar4d14bac2019-10-20 21:15:15 +02003336 ex_quit(&ea);
3337 return TRUE;
3338 }
3339
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003340 // ++close or term_finish == "close"
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003341 ch_log(NULL, "terminal job finished, closing window");
3342 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003343 // Avoid closing the window if we temporarily use it.
Bram Moolenaar517f71a2019-06-17 22:40:41 +02003344 if (curwin == aucmd_win)
3345 do_set_w_closing = TRUE;
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003346 if (do_set_w_closing)
3347 curwin->w_closing = TRUE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003348 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaar5db7eec2018-08-07 16:33:18 +02003349 if (do_set_w_closing)
3350 curwin->w_closing = FALSE;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003351 aucmd_restbuf(&aco);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003352#ifdef FEAT_PROP_POPUP
3353 if (pwin != NULL)
3354 popup_close_with_retval(pwin, 0);
3355#endif
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003356 return TRUE;
3357 }
3358 if (term->tl_finish == TL_FINISH_OPEN
3359 && term->tl_buffer->b_nwindows == 0)
3360 {
3361 char buf[50];
3362
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003363 // TODO: use term_opencmd
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003364 ch_log(NULL, "terminal job finished, opening window");
3365 vim_snprintf(buf, sizeof(buf),
3366 term->tl_opencmd == NULL
3367 ? "botright sbuf %d"
3368 : (char *)term->tl_opencmd, fnum);
3369 do_cmdline_cmd((char_u *)buf);
3370 }
3371 else
3372 ch_log(NULL, "terminal job finished");
3373 }
3374
3375 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
3376 return FALSE;
3377}
3378
Bram Moolenaard98c0b62020-02-02 15:25:16 +01003379#if defined(FEAT_PROP_POPUP) || defined(PROTO)
3380/*
3381 * If the current window is a terminal in a popup window and the job has
3382 * finished, close the popup window and to back to the previous window.
3383 * Otherwise return FAIL.
3384 */
3385 int
3386may_close_term_popup(void)
3387{
3388 if (popup_is_popup(curwin) && curbuf->b_term != NULL
3389 && !term_job_running(curbuf->b_term))
3390 {
3391 win_T *pwin = curwin;
3392
3393 if (win_valid(prevwin))
3394 win_enter(prevwin, FALSE);
3395 popup_close_with_retval(pwin, 0);
3396 return OK;
3397 }
3398 return FAIL;
3399}
3400#endif
3401
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003402/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003403 * Called when a channel has been closed.
3404 * If this was a channel for a terminal window then finish it up.
3405 */
3406 void
3407term_channel_closed(channel_T *ch)
3408{
3409 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003410 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003411 int did_one = FALSE;
3412
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003413 for (term = first_term; term != NULL; term = next_term)
3414 {
3415 next_term = term->tl_next;
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02003416 if (term->tl_job == ch->ch_job && !term->tl_channel_closed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003417 {
3418 term->tl_channel_closed = TRUE;
3419 did_one = TRUE;
3420
Bram Moolenaard23a8232018-02-10 18:45:26 +01003421 VIM_CLEAR(term->tl_title);
3422 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar4f974752019-02-17 17:44:42 +01003423#ifdef MSWIN
Bram Moolenaar402c8392018-05-06 22:01:42 +02003424 if (term->tl_out_fd != NULL)
3425 {
3426 fclose(term->tl_out_fd);
3427 term->tl_out_fd = NULL;
3428 }
3429#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003430
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003431 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003432 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003433 // Cannot open or close windows now. Can happen when
3434 // 'lazyredraw' is set.
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003435 term->tl_channel_recently_closed = TRUE;
3436 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003437 }
3438
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003439 if (term_after_channel_closed(term))
3440 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003441 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003442 }
3443
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003444 if (did_one)
3445 {
3446 redraw_statuslines();
3447
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003448 // Need to break out of vgetc().
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003449 ins_char_typebuf(K_IGNORE);
3450 typebuf_was_filled = TRUE;
3451
3452 term = curbuf->b_term;
3453 if (term != NULL)
3454 {
3455 if (term->tl_job == ch->ch_job)
3456 maketitle();
3457 update_cursor(term, term->tl_cursor_visible);
3458 }
3459 }
3460}
3461
3462/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02003463 * To be called after resetting updating_screen: handle any terminal where the
3464 * channel was closed.
3465 */
3466 void
3467term_check_channel_closed_recently()
3468{
3469 term_T *term;
3470 term_T *next_term;
3471
3472 for (term = first_term; term != NULL; term = next_term)
3473 {
3474 next_term = term->tl_next;
3475 if (term->tl_channel_recently_closed)
3476 {
3477 term->tl_channel_recently_closed = FALSE;
3478 if (term_after_channel_closed(term))
3479 // start over, the list may have changed
3480 next_term = first_term;
3481 }
3482 }
3483}
3484
3485/*
Bram Moolenaar13568252018-03-16 20:46:58 +01003486 * Fill one screen line from a line of the terminal.
3487 * Advances "pos" to past the last column.
3488 */
3489 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003490term_line2screenline(
Bram Moolenaar83d47902020-03-26 20:34:00 +01003491 term_T *term,
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003492 win_T *wp,
3493 VTermScreen *screen,
3494 VTermPos *pos,
3495 int max_col)
Bram Moolenaar13568252018-03-16 20:46:58 +01003496{
3497 int off = screen_get_current_line_off();
3498
3499 for (pos->col = 0; pos->col < max_col; )
3500 {
3501 VTermScreenCell cell;
3502 int c;
3503
3504 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02003505 CLEAR_FIELD(cell);
Bram Moolenaar13568252018-03-16 20:46:58 +01003506
3507 c = cell.chars[0];
3508 if (c == NUL)
3509 {
3510 ScreenLines[off] = ' ';
3511 if (enc_utf8)
3512 ScreenLinesUC[off] = NUL;
3513 }
3514 else
3515 {
3516 if (enc_utf8)
3517 {
3518 int i;
3519
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003520 // composing chars
Bram Moolenaar13568252018-03-16 20:46:58 +01003521 for (i = 0; i < Screen_mco
3522 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
3523 {
3524 ScreenLinesC[i][off] = cell.chars[i + 1];
3525 if (cell.chars[i + 1] == 0)
3526 break;
3527 }
3528 if (c >= 0x80 || (Screen_mco > 0
3529 && ScreenLinesC[0][off] != 0))
3530 {
3531 ScreenLines[off] = ' ';
3532 ScreenLinesUC[off] = c;
3533 }
3534 else
3535 {
3536 ScreenLines[off] = c;
3537 ScreenLinesUC[off] = NUL;
3538 }
3539 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003540#ifdef MSWIN
Bram Moolenaar13568252018-03-16 20:46:58 +01003541 else if (has_mbyte && c >= 0x80)
3542 {
3543 char_u mb[MB_MAXBYTES+1];
3544 WCHAR wc = c;
3545
3546 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
3547 (char*)mb, 2, 0, 0) > 1)
3548 {
3549 ScreenLines[off] = mb[0];
3550 ScreenLines[off + 1] = mb[1];
3551 cell.width = mb_ptr2cells(mb);
3552 }
3553 else
3554 ScreenLines[off] = c;
3555 }
3556#endif
3557 else
3558 ScreenLines[off] = c;
3559 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003560 ScreenAttrs[off] = cell2attr(term, wp, cell.attrs, cell.fg, cell.bg);
Bram Moolenaar13568252018-03-16 20:46:58 +01003561
3562 ++pos->col;
3563 ++off;
3564 if (cell.width == 2)
3565 {
3566 if (enc_utf8)
3567 ScreenLinesUC[off] = NUL;
3568
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003569 // don't set the second byte to NUL for a DBCS encoding, it
3570 // has been set above
Bram Moolenaar13568252018-03-16 20:46:58 +01003571 if (enc_utf8 || !has_mbyte)
3572 ScreenLines[off] = NUL;
3573
3574 ++pos->col;
3575 ++off;
3576 }
3577 }
3578}
3579
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003580#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003581 static void
3582update_system_term(term_T *term)
3583{
3584 VTermPos pos;
3585 VTermScreen *screen;
3586
3587 if (term->tl_vterm == NULL)
3588 return;
3589 screen = vterm_obtain_screen(term->tl_vterm);
3590
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003591 // Scroll up to make more room for terminal lines if needed.
Bram Moolenaar13568252018-03-16 20:46:58 +01003592 while (term->tl_toprow > 0
3593 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3594 {
3595 int save_p_more = p_more;
3596
3597 p_more = FALSE;
3598 msg_row = Rows - 1;
Bram Moolenaar113e1072019-01-20 15:30:40 +01003599 msg_puts("\n");
Bram Moolenaar13568252018-03-16 20:46:58 +01003600 p_more = save_p_more;
3601 --term->tl_toprow;
3602 }
3603
3604 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3605 && pos.row < Rows; ++pos.row)
3606 {
3607 if (pos.row < term->tl_rows)
3608 {
3609 int max_col = MIN(Columns, term->tl_cols);
3610
Bram Moolenaar83d47902020-03-26 20:34:00 +01003611 term_line2screenline(term, NULL, screen, &pos, max_col);
Bram Moolenaar13568252018-03-16 20:46:58 +01003612 }
3613 else
3614 pos.col = 0;
3615
Bram Moolenaar4d784b22019-05-25 19:51:39 +02003616 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, 0);
Bram Moolenaar13568252018-03-16 20:46:58 +01003617 }
3618
3619 term->tl_dirty_row_start = MAX_ROW;
3620 term->tl_dirty_row_end = 0;
Bram Moolenaar13568252018-03-16 20:46:58 +01003621}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003622#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003623
3624/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003625 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3626 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003627 * Terminal-Normal mode.
3628 */
3629 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003630term_do_update_window(win_T *wp)
3631{
3632 term_T *term = wp->w_buffer->b_term;
3633
3634 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3635}
3636
3637/*
3638 * Called to update a window that contains an active terminal.
3639 */
3640 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003641term_update_window(win_T *wp)
3642{
3643 term_T *term = wp->w_buffer->b_term;
3644 VTerm *vterm;
3645 VTermScreen *screen;
3646 VTermState *state;
3647 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003648 int rows, cols;
3649 int newrows, newcols;
3650 int minsize;
3651 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003652
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003653 vterm = term->tl_vterm;
3654 screen = vterm_obtain_screen(vterm);
3655 state = vterm_obtain_state(vterm);
3656
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003657 // We use NOT_VALID on a resize or scroll, redraw everything then. With
3658 // SOME_VALID only redraw what was marked dirty.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003659 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003660 {
3661 term->tl_dirty_row_start = 0;
3662 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003663
3664 if (term->tl_postponed_scroll > 0
3665 && term->tl_postponed_scroll < term->tl_rows / 3)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003666 // Scrolling is usually faster than redrawing, when there are only
3667 // a few lines to scroll.
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003668 term_scroll_up(term, 0, term->tl_postponed_scroll);
3669 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003670 }
3671
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003672 /*
3673 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003674 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003675 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003676 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003677
Bram Moolenaar498c2562018-04-15 23:45:15 +02003678 newrows = 99999;
3679 newcols = 99999;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003680 for (twp = firstwin; ; twp = twp->w_next)
Bram Moolenaar498c2562018-04-15 23:45:15 +02003681 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003682 // Always use curwin, it may be a popup window.
3683 win_T *wwp = twp == NULL ? curwin : twp;
3684
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003685 // When more than one window shows the same terminal, use the
3686 // smallest size.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003687 if (wwp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003688 {
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003689 newrows = MIN(newrows, wwp->w_height);
3690 newcols = MIN(newcols, wwp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003691 }
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003692 if (twp == NULL)
3693 break;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003694 }
Bram Moolenaare0d749a2019-09-25 22:14:48 +02003695 if (newrows == 99999 || newcols == 99999)
3696 return; // safety exit
Bram Moolenaar498c2562018-04-15 23:45:15 +02003697 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3698 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3699
3700 if (term->tl_rows != newrows || term->tl_cols != newcols)
3701 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003702 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003703 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003704 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003705 newrows);
3706 term_report_winsize(term, newrows, newcols);
Bram Moolenaar875cf872018-07-08 20:49:07 +02003707
3708 // Updating the terminal size will cause the snapshot to be cleared.
3709 // When not in terminal_loop() we need to restore it.
3710 if (term != in_terminal_loop)
3711 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003712 }
3713
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003714 // The cursor may have been moved when resizing.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003715 vterm_state_get_cursorpos(state, &pos);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003716 position_cursor(wp, &pos, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003717
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003718 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3719 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003720 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003721 if (pos.row < term->tl_rows)
3722 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003723 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003724
Bram Moolenaar83d47902020-03-26 20:34:00 +01003725 term_line2screenline(term, wp, screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003726 }
3727 else
3728 pos.col = 0;
3729
Bram Moolenaarf118d482018-03-13 13:14:00 +01003730 screen_line(wp->w_winrow + pos.row
3731#ifdef FEAT_MENU
3732 + winbar_height(wp)
3733#endif
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003734 , wp->w_wincol, pos.col, wp->w_width,
3735#ifdef FEAT_PROP_POPUP
3736 popup_is_popup(wp) ? SLF_POPUP :
3737#endif
3738 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003739 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003740 term->tl_dirty_row_start = MAX_ROW;
3741 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003742}
3743
3744/*
3745 * Return TRUE if "wp" is a terminal window where the job has finished.
3746 */
3747 int
3748term_is_finished(buf_T *buf)
3749{
3750 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3751}
3752
3753/*
3754 * Return TRUE if "wp" is a terminal window where the job has finished or we
3755 * are in Terminal-Normal mode, thus we show the buffer contents.
3756 */
3757 int
3758term_show_buffer(buf_T *buf)
3759{
3760 term_T *term = buf->b_term;
3761
3762 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3763}
3764
3765/*
3766 * The current buffer is going to be changed. If there is terminal
3767 * highlighting remove it now.
3768 */
3769 void
3770term_change_in_curbuf(void)
3771{
3772 term_T *term = curbuf->b_term;
3773
3774 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3775 {
3776 free_scrollback(term);
3777 redraw_buf_later(term->tl_buffer, NOT_VALID);
3778
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003779 // The buffer is now like a normal buffer, it cannot be easily
3780 // abandoned when changed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003781 set_string_option_direct((char_u *)"buftype", -1,
3782 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3783 }
3784}
3785
3786/*
3787 * Get the screen attribute for a position in the buffer.
3788 * Use a negative "col" to get the filler background color.
3789 */
3790 int
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003791term_get_attr(win_T *wp, linenr_T lnum, int col)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003792{
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003793 buf_T *buf = wp->w_buffer;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003794 term_T *term = buf->b_term;
3795 sb_line_T *line;
3796 cellattr_T *cellattr;
3797
3798 if (lnum > term->tl_scrollback.ga_len)
3799 cellattr = &term->tl_default_color;
3800 else
3801 {
3802 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3803 if (col < 0 || col >= line->sb_cols)
3804 cellattr = &line->sb_fill_attr;
3805 else
3806 cellattr = line->sb_cells + col;
3807 }
Bram Moolenaar83d47902020-03-26 20:34:00 +01003808 return cell2attr(term, wp, cellattr->attrs, cellattr->fg, cellattr->bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003809}
3810
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003811/*
3812 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003813 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003814 */
3815 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003816cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003817{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003818 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003819}
3820
3821/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003822 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003823 */
3824 static void
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003825init_default_colors(term_T *term, win_T *wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003826{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003827 VTermColor *fg, *bg;
3828 int fgval, bgval;
3829 int id;
3830
Bram Moolenaara80faa82020-04-12 19:37:17 +02003831 CLEAR_FIELD(term->tl_default_color.attrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003832 term->tl_default_color.width = 1;
3833 fg = &term->tl_default_color.fg;
3834 bg = &term->tl_default_color.bg;
3835
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003836 // Vterm uses a default black background. Set it to white when
3837 // 'background' is "light".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003838 if (*p_bg == 'l')
3839 {
3840 fgval = 0;
3841 bgval = 255;
3842 }
3843 else
3844 {
3845 fgval = 255;
3846 bgval = 0;
3847 }
3848 fg->red = fg->green = fg->blue = fgval;
3849 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003850 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003851
Bram Moolenaar83d47902020-03-26 20:34:00 +01003852 // The 'wincolor' or the highlight group overrules the defaults.
Bram Moolenaar219c7d02020-02-01 21:57:29 +01003853 if (wp != NULL && *wp->w_p_wcr != NUL)
3854 id = syn_name2id(wp->w_p_wcr);
3855 else
Bram Moolenaar83d47902020-03-26 20:34:00 +01003856 id = syn_name2id(term_get_highlight_name(term));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003857
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003858 // Use the actual color for the GUI and when 'termguicolors' is set.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003859#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3860 if (0
3861# ifdef FEAT_GUI
3862 || gui.in_use
3863# endif
3864# ifdef FEAT_TERMGUICOLORS
3865 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003866# ifdef FEAT_VTP
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003867 // Finally get INVALCOLOR on this execution path
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003868 || (!p_tgc && t_colors >= 256)
3869# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003870# endif
3871 )
3872 {
3873 guicolor_T fg_rgb = INVALCOLOR;
3874 guicolor_T bg_rgb = INVALCOLOR;
3875
3876 if (id != 0)
3877 syn_id2colors(id, &fg_rgb, &bg_rgb);
3878
3879# ifdef FEAT_GUI
3880 if (gui.in_use)
3881 {
3882 if (fg_rgb == INVALCOLOR)
3883 fg_rgb = gui.norm_pixel;
3884 if (bg_rgb == INVALCOLOR)
3885 bg_rgb = gui.back_pixel;
3886 }
3887# ifdef FEAT_TERMGUICOLORS
3888 else
3889# endif
3890# endif
3891# ifdef FEAT_TERMGUICOLORS
3892 {
3893 if (fg_rgb == INVALCOLOR)
3894 fg_rgb = cterm_normal_fg_gui_color;
3895 if (bg_rgb == INVALCOLOR)
3896 bg_rgb = cterm_normal_bg_gui_color;
3897 }
3898# endif
3899 if (fg_rgb != INVALCOLOR)
3900 {
3901 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3902
3903 fg->red = (unsigned)(rgb >> 16);
3904 fg->green = (unsigned)(rgb >> 8) & 255;
3905 fg->blue = (unsigned)rgb & 255;
3906 }
3907 if (bg_rgb != INVALCOLOR)
3908 {
3909 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3910
3911 bg->red = (unsigned)(rgb >> 16);
3912 bg->green = (unsigned)(rgb >> 8) & 255;
3913 bg->blue = (unsigned)rgb & 255;
3914 }
3915 }
3916 else
3917#endif
3918 if (id != 0 && t_colors >= 16)
3919 {
Bram Moolenaar83d47902020-03-26 20:34:00 +01003920 int cterm_fg = get_default_cterm_fg(term);
3921 int cterm_bg = get_default_cterm_bg(term);
3922
3923 if (cterm_fg >= 0)
3924 cterm_color2vterm(cterm_fg, fg);
3925 if (cterm_bg >= 0)
3926 cterm_color2vterm(cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003927 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003928 else
3929 {
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003930#if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003931 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003932#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003933
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01003934 // In an MS-Windows console we know the normal colors.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003935 if (cterm_normal_fg_color > 0)
3936 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003937 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003938# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3939# ifdef VIMDLL
3940 if (!gui.in_use)
3941# endif
3942 {
3943 tmp = fg->red;
3944 fg->red = fg->blue;
3945 fg->blue = tmp;
3946 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003947# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003948 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003949# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003950 else
3951 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003952# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003953
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003954 if (cterm_normal_bg_color > 0)
3955 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003956 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003957# if defined(MSWIN) && (!defined(FEAT_GUI_MSWIN) || defined(VIMDLL))
3958# ifdef VIMDLL
3959 if (!gui.in_use)
3960# endif
3961 {
3962 tmp = fg->red;
3963 fg->red = fg->blue;
3964 fg->blue = tmp;
3965 }
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003966# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003967 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003968# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003969 else
3970 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003971# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003972 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003973}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003974
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003975#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3976/*
3977 * Set the 16 ANSI colors from array of RGB values
3978 */
3979 static void
3980set_vterm_palette(VTerm *vterm, long_u *rgb)
3981{
3982 int index = 0;
3983 VTermState *state = vterm_obtain_state(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01003984
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003985 for (; index < 16; index++)
3986 {
3987 VTermColor color;
Bram Moolenaaref8c83c2019-04-11 11:40:13 +02003988
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003989 color.red = (unsigned)(rgb[index] >> 16);
3990 color.green = (unsigned)(rgb[index] >> 8) & 255;
3991 color.blue = (unsigned)rgb[index] & 255;
3992 vterm_state_set_palette_color(state, index, &color);
3993 }
3994}
3995
3996/*
3997 * Set the ANSI color palette from a list of colors
3998 */
3999 static int
4000set_ansi_colors_list(VTerm *vterm, list_T *list)
4001{
4002 int n = 0;
4003 long_u rgb[16];
Bram Moolenaarb0992022020-01-30 14:55:42 +01004004 listitem_T *li;
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004005
Bram Moolenaarb0992022020-01-30 14:55:42 +01004006 for (li = list->lv_first; li != NULL && n < 16; li = li->li_next, n++)
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004007 {
4008 char_u *color_name;
4009 guicolor_T guicolor;
4010
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004011 color_name = tv_get_string_chk(&li->li_tv);
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004012 if (color_name == NULL)
4013 return FAIL;
4014
4015 guicolor = GUI_GET_COLOR(color_name);
4016 if (guicolor == INVALCOLOR)
4017 return FAIL;
4018
4019 rgb[n] = GUI_MCH_GET_RGB(guicolor);
4020 }
4021
4022 if (n != 16 || li != NULL)
4023 return FAIL;
4024
4025 set_vterm_palette(vterm, rgb);
4026
4027 return OK;
4028}
4029
4030/*
4031 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
4032 */
4033 static void
4034init_vterm_ansi_colors(VTerm *vterm)
4035{
4036 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
4037
4038 if (var != NULL
4039 && (var->di_tv.v_type != VAR_LIST
4040 || var->di_tv.vval.v_list == NULL
Bram Moolenaarb0992022020-01-30 14:55:42 +01004041 || var->di_tv.vval.v_list->lv_first == &range_list_item
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004042 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004043 semsg(_(e_invarg2), "g:terminal_ansi_colors");
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004044}
4045#endif
4046
Bram Moolenaar52acb112018-03-18 19:20:22 +01004047/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004048 * Handles a "drop" command from the job in the terminal.
4049 * "item" is the file name, "item->li_next" may have options.
4050 */
4051 static void
4052handle_drop_command(listitem_T *item)
4053{
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004054 char_u *fname = tv_get_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004055 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004056 int bufnr;
4057 win_T *wp;
4058 tabpage_T *tp;
4059 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004060 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004061
4062 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
4063 FOR_ALL_TAB_WINDOWS(tp, wp)
4064 {
4065 if (wp->w_buffer->b_fnum == bufnr)
4066 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004067 // buffer is in a window already, go there
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004068 goto_tabpage_win(tp, wp);
4069 return;
4070 }
4071 }
4072
Bram Moolenaara80faa82020-04-12 19:37:17 +02004073 CLEAR_FIELD(ea);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004074
4075 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
4076 && opt_item->li_tv.vval.v_dict != NULL)
4077 {
4078 dict_T *dict = opt_item->li_tv.vval.v_dict;
4079 char_u *p;
4080
Bram Moolenaar8f667172018-12-14 15:38:31 +01004081 p = dict_get_string(dict, (char_u *)"ff", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004082 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004083 p = dict_get_string(dict, (char_u *)"fileformat", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004084 if (p != NULL)
4085 {
4086 if (check_ff_value(p) == FAIL)
4087 ch_log(NULL, "Invalid ff argument to drop: %s", p);
4088 else
4089 ea.force_ff = *p;
4090 }
Bram Moolenaar8f667172018-12-14 15:38:31 +01004091 p = dict_get_string(dict, (char_u *)"enc", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004092 if (p == NULL)
Bram Moolenaar8f667172018-12-14 15:38:31 +01004093 p = dict_get_string(dict, (char_u *)"encoding", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004094 if (p != NULL)
4095 {
Bram Moolenaar51e14382019-05-25 20:21:28 +02004096 ea.cmd = alloc(STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004097 if (ea.cmd != NULL)
4098 {
4099 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
4100 ea.force_enc = 11;
4101 tofree = ea.cmd;
4102 }
4103 }
4104
Bram Moolenaar8f667172018-12-14 15:38:31 +01004105 p = dict_get_string(dict, (char_u *)"bad", FALSE);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004106 if (p != NULL)
4107 get_bad_opt(p, &ea);
4108
4109 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
4110 ea.force_bin = FORCE_BIN;
4111 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
4112 ea.force_bin = FORCE_BIN;
4113 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
4114 ea.force_bin = FORCE_NOBIN;
4115 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
4116 ea.force_bin = FORCE_NOBIN;
4117 }
4118
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004119 // open in new window, like ":split fname"
Bram Moolenaar333b80a2018-04-04 22:57:29 +02004120 if (ea.cmd == NULL)
4121 ea.cmd = (char_u *)"split";
4122 ea.arg = fname;
4123 ea.cmdidx = CMD_split;
4124 ex_splitview(&ea);
4125
4126 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004127}
4128
4129/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004130 * Return TRUE if "func" starts with "pat" and "pat" isn't empty.
4131 */
4132 static int
4133is_permitted_term_api(char_u *func, char_u *pat)
4134{
4135 return pat != NULL && *pat != NUL && STRNICMP(func, pat, STRLEN(pat)) == 0;
4136}
4137
4138/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004139 * Handles a function call from the job running in a terminal.
4140 * "item" is the function name, "item->li_next" has the arguments.
4141 */
4142 static void
4143handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
4144{
4145 char_u *func;
4146 typval_T argvars[2];
4147 typval_T rettv;
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004148 funcexe_T funcexe;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004149
4150 if (item->li_next == NULL)
4151 {
4152 ch_log(channel, "Missing function arguments for call");
4153 return;
4154 }
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004155 func = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004156
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004157 if (!is_permitted_term_api(func, term->tl_api))
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004158 {
Bram Moolenaard2842ea2019-09-26 23:08:54 +02004159 ch_log(channel, "Unpermitted function: %s", func);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004160 return;
4161 }
4162
4163 argvars[0].v_type = VAR_NUMBER;
4164 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
4165 argvars[1] = item->li_next->li_tv;
Bram Moolenaara80faa82020-04-12 19:37:17 +02004166 CLEAR_FIELD(funcexe);
Bram Moolenaarc6538bc2019-08-03 18:17:11 +02004167 funcexe.firstline = 1L;
4168 funcexe.lastline = 1L;
4169 funcexe.evaluate = TRUE;
4170 if (call_func(func, -1, &rettv, 2, argvars, &funcexe) == OK)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004171 {
4172 clear_tv(&rettv);
4173 ch_log(channel, "Function %s called", func);
4174 }
4175 else
4176 ch_log(channel, "Calling function %s failed", func);
4177}
4178
4179/*
4180 * Called by libvterm when it cannot recognize an OSC sequence.
4181 * We recognize a terminal API command.
4182 */
4183 static int
4184parse_osc(const char *command, size_t cmdlen, void *user)
4185{
4186 term_T *term = (term_T *)user;
4187 js_read_T reader;
4188 typval_T tv;
4189 channel_T *channel = term->tl_job == NULL ? NULL
4190 : term->tl_job->jv_channel;
4191
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004192 // We recognize only OSC 5 1 ; {command}
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004193 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004194 return 0; // not handled
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004195
Bram Moolenaar878c96d2018-04-04 23:00:06 +02004196 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004197 if (reader.js_buf == NULL)
4198 return 1;
4199 reader.js_fill = NULL;
4200 reader.js_used = 0;
4201 if (json_decode(&reader, &tv, 0) == OK
4202 && tv.v_type == VAR_LIST
4203 && tv.vval.v_list != NULL)
4204 {
4205 listitem_T *item = tv.vval.v_list->lv_first;
4206
4207 if (item == NULL)
4208 ch_log(channel, "Missing command");
4209 else
4210 {
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004211 char_u *cmd = tv_get_string(&item->li_tv);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004212
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004213 // Make sure an invoked command doesn't delete the buffer (and the
4214 // terminal) under our fingers.
Bram Moolenaara997b452018-04-17 23:24:06 +02004215 ++term->tl_buffer->b_locked;
4216
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004217 item = item->li_next;
4218 if (item == NULL)
4219 ch_log(channel, "Missing argument for %s", cmd);
4220 else if (STRCMP(cmd, "drop") == 0)
4221 handle_drop_command(item);
4222 else if (STRCMP(cmd, "call") == 0)
4223 handle_call_command(term, channel, item);
4224 else
4225 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02004226 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004227 }
4228 }
4229 else
4230 ch_log(channel, "Invalid JSON received");
4231
4232 vim_free(reader.js_buf);
4233 clear_tv(&tv);
4234 return 1;
4235}
4236
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004237/*
4238 * Called by libvterm when it cannot recognize a CSI sequence.
4239 * We recognize the window position report.
4240 */
4241 static int
4242parse_csi(
4243 const char *leader UNUSED,
4244 const long args[],
4245 int argcount,
4246 const char *intermed UNUSED,
4247 char command,
4248 void *user)
4249{
4250 term_T *term = (term_T *)user;
4251 char buf[100];
4252 int len;
4253 int x = 0;
4254 int y = 0;
4255 win_T *wp;
4256
4257 // We recognize only CSI 13 t
4258 if (command != 't' || argcount != 1 || args[0] != 13)
4259 return 0; // not handled
4260
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004261 // When getting the window position is not possible or it fails it results
4262 // in zero/zero.
Bram Moolenaar16c34c32019-04-06 22:01:24 +02004263#if defined(FEAT_GUI) \
4264 || (defined(HAVE_TGETENT) && defined(FEAT_TERMRESPONSE)) \
4265 || defined(MSWIN)
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004266 (void)ui_get_winpos(&x, &y, (varnumber_T)100);
Bram Moolenaar6bc93052019-04-06 20:00:19 +02004267#endif
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004268
4269 FOR_ALL_WINDOWS(wp)
4270 if (wp->w_buffer == term->tl_buffer)
4271 break;
4272 if (wp != NULL)
4273 {
4274#ifdef FEAT_GUI
4275 if (gui.in_use)
4276 {
4277 x += wp->w_wincol * gui.char_width;
4278 y += W_WINROW(wp) * gui.char_height;
4279 }
4280 else
4281#endif
4282 {
4283 // We roughly estimate the position of the terminal window inside
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004284 // the Vim window by assuming a 10 x 7 character cell.
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004285 x += wp->w_wincol * 7;
4286 y += W_WINROW(wp) * 10;
4287 }
4288 }
4289
4290 len = vim_snprintf(buf, 100, "\x1b[3;%d;%dt", x, y);
4291 channel_send(term->tl_job->jv_channel, get_tty_part(term),
4292 (char_u *)buf, len, NULL);
4293 return 1;
4294}
4295
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004296static VTermParserCallbacks parser_fallbacks = {
Bram Moolenaarfa1e90c2019-04-06 17:47:40 +02004297 NULL, // text
4298 NULL, // control
4299 NULL, // escape
4300 parse_csi, // csi
4301 parse_osc, // osc
4302 NULL, // dcs
4303 NULL // resize
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004304};
4305
4306/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02004307 * Use Vim's allocation functions for vterm so profiling works.
4308 */
4309 static void *
4310vterm_malloc(size_t size, void *data UNUSED)
4311{
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004312 return alloc_clear(size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02004313}
4314
4315 static void
4316vterm_memfree(void *ptr, void *data UNUSED)
4317{
4318 vim_free(ptr);
4319}
4320
4321static VTermAllocatorFunctions vterm_allocator = {
4322 &vterm_malloc,
4323 &vterm_memfree
4324};
4325
4326/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01004327 * Create a new vterm and initialize it.
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004328 * Return FAIL when out of memory.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004329 */
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004330 static int
Bram Moolenaar52acb112018-03-18 19:20:22 +01004331create_vterm(term_T *term, int rows, int cols)
4332{
4333 VTerm *vterm;
4334 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004335 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01004336 VTermValue value;
4337
Bram Moolenaar756ef112018-04-10 12:04:27 +02004338 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004339 term->tl_vterm = vterm;
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004340 if (vterm == NULL)
4341 return FAIL;
4342
4343 // Allocate screen and state here, so we can bail out if that fails.
4344 state = vterm_obtain_state(vterm);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004345 screen = vterm_obtain_screen(vterm);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004346 if (state == NULL || screen == NULL)
4347 {
4348 vterm_free(vterm);
4349 return FAIL;
4350 }
4351
Bram Moolenaar52acb112018-03-18 19:20:22 +01004352 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004353 // TODO: depends on 'encoding'.
Bram Moolenaar52acb112018-03-18 19:20:22 +01004354 vterm_set_utf8(vterm, 1);
4355
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004356 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01004357
4358 vterm_state_set_default_colors(
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004359 state,
Bram Moolenaar52acb112018-03-18 19:20:22 +01004360 &term->tl_default_color.fg,
4361 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004362
Bram Moolenaar9e587872019-05-13 20:27:23 +02004363 if (t_colors < 16)
4364 // Less than 16 colors: assume that bold means using a bright color for
4365 // the foreground color.
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02004366 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
4367
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004368 // Required to initialize most things.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004369 vterm_screen_reset(screen, 1 /* hard */);
4370
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004371 // Allow using alternate screen.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004372 vterm_screen_enable_altscreen(screen, 1);
4373
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004374 // For unix do not use a blinking cursor. In an xterm this causes the
4375 // cursor to blink if it's blinking in the xterm.
4376 // For Windows we respect the system wide setting.
Bram Moolenaar4f974752019-02-17 17:44:42 +01004377#ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004378 if (GetCaretBlinkTime() == INFINITE)
4379 value.boolean = 0;
4380 else
4381 value.boolean = 1;
4382#else
4383 value.boolean = 0;
4384#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02004385 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
4386 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaarcd929f72018-12-24 21:38:45 +01004387
4388 return OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004389}
4390
4391/*
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004392 * Called when 'wincolor' was set.
4393 */
4394 void
4395term_update_colors(void)
4396{
4397 term_T *term = curwin->w_buffer->b_term;
4398
Bram Moolenaar7ba3b912020-02-10 20:34:04 +01004399 if (term->tl_vterm == NULL)
4400 return;
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004401 init_default_colors(term, curwin);
4402 vterm_state_set_default_colors(
4403 vterm_obtain_state(term->tl_vterm),
4404 &term->tl_default_color.fg,
4405 &term->tl_default_color.bg);
Bram Moolenaard5bc32d2020-03-22 19:25:50 +01004406
4407 redraw_later(NOT_VALID);
Bram Moolenaar219c7d02020-02-01 21:57:29 +01004408}
4409
4410/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004411 * Return the text to show for the buffer name and status.
4412 */
4413 char_u *
4414term_get_status_text(term_T *term)
4415{
4416 if (term->tl_status_text == NULL)
4417 {
4418 char_u *txt;
4419 size_t len;
4420
4421 if (term->tl_normal_mode)
4422 {
4423 if (term_job_running(term))
4424 txt = (char_u *)_("Terminal");
4425 else
4426 txt = (char_u *)_("Terminal-finished");
4427 }
4428 else if (term->tl_title != NULL)
4429 txt = term->tl_title;
4430 else if (term_none_open(term))
4431 txt = (char_u *)_("active");
4432 else if (term_job_running(term))
4433 txt = (char_u *)_("running");
4434 else
4435 txt = (char_u *)_("finished");
4436 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
Bram Moolenaar51e14382019-05-25 20:21:28 +02004437 term->tl_status_text = alloc(len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004438 if (term->tl_status_text != NULL)
4439 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
4440 term->tl_buffer->b_fname, txt);
4441 }
4442 return term->tl_status_text;
4443}
4444
4445/*
4446 * Mark references in jobs of terminals.
4447 */
4448 int
4449set_ref_in_term(int copyID)
4450{
4451 int abort = FALSE;
4452 term_T *term;
4453 typval_T tv;
4454
Bram Moolenaar75a1a942019-06-20 03:45:36 +02004455 for (term = first_term; !abort && term != NULL; term = term->tl_next)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004456 if (term->tl_job != NULL)
4457 {
4458 tv.v_type = VAR_JOB;
4459 tv.vval.v_job = term->tl_job;
4460 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
4461 }
4462 return abort;
4463}
4464
4465/*
4466 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004467 * Returns NULL when the buffer is not for a terminal window and logs a message
4468 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004469 */
4470 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004471term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004472{
4473 buf_T *buf;
4474
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004475 (void)tv_get_number(&argvars[0]); // issue errmsg if type error
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004476 ++emsg_off;
Bram Moolenaarf2d79fa2019-01-03 22:19:27 +01004477 buf = tv_get_buf(&argvars[0], FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004478 --emsg_off;
4479 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004480 {
4481 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004482 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004483 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004484 return buf;
4485}
4486
Bram Moolenaard96ff162018-02-18 22:13:29 +01004487 static int
4488same_color(VTermColor *a, VTermColor *b)
4489{
4490 return a->red == b->red
4491 && a->green == b->green
4492 && a->blue == b->blue
4493 && a->ansi_index == b->ansi_index;
4494}
4495
4496 static void
4497dump_term_color(FILE *fd, VTermColor *color)
4498{
4499 fprintf(fd, "%02x%02x%02x%d",
4500 (int)color->red, (int)color->green, (int)color->blue,
4501 (int)color->ansi_index);
4502}
4503
4504/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004505 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01004506 *
4507 * Each screen cell in full is:
4508 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
4509 * {characters} is a space for an empty cell
4510 * For a double-width character "+" is changed to "*" and the next cell is
4511 * skipped.
4512 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
4513 * when "&" use the same as the previous cell.
4514 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
4515 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
4516 * {color-idx} is a number from 0 to 255
4517 *
4518 * Screen cell with same width, attributes and color as the previous one:
4519 * |{characters}
4520 *
4521 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
4522 *
4523 * Repeating the previous screen cell:
4524 * @{count}
4525 */
4526 void
4527f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
4528{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004529 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01004530 term_T *term;
4531 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004532 int max_height = 0;
4533 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004534 stat_T st;
4535 FILE *fd;
4536 VTermPos pos;
4537 VTermScreen *screen;
4538 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004539 VTermState *state;
4540 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004541
4542 if (check_restricted() || check_secure())
4543 return;
4544 if (buf == NULL)
4545 return;
4546 term = buf->b_term;
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004547 if (term->tl_vterm == NULL)
4548 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004549 emsg(_("E958: Job already finished"));
Bram Moolenaara5c48c22018-09-09 19:56:07 +02004550 return;
4551 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004552
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004553 if (argvars[2].v_type != VAR_UNKNOWN)
4554 {
4555 dict_T *d;
4556
4557 if (argvars[2].v_type != VAR_DICT)
4558 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004559 emsg(_(e_dictreq));
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004560 return;
4561 }
4562 d = argvars[2].vval.v_dict;
4563 if (d != NULL)
4564 {
Bram Moolenaar8f667172018-12-14 15:38:31 +01004565 max_height = dict_get_number(d, (char_u *)"rows");
4566 max_width = dict_get_number(d, (char_u *)"columns");
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004567 }
4568 }
4569
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004570 fname = tv_get_string_chk(&argvars[1]);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004571 if (fname == NULL)
4572 return;
4573 if (mch_stat((char *)fname, &st) >= 0)
4574 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004575 semsg(_("E953: File exists: %s"), fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004576 return;
4577 }
4578
Bram Moolenaard96ff162018-02-18 22:13:29 +01004579 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
4580 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004581 semsg(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004582 return;
4583 }
4584
Bram Moolenaara80faa82020-04-12 19:37:17 +02004585 CLEAR_FIELD(prev_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004586
4587 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004588 state = vterm_obtain_state(term->tl_vterm);
4589 vterm_state_get_cursorpos(state, &cursor_pos);
4590
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004591 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
4592 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004593 {
4594 int repeat = 0;
4595
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01004596 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
4597 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004598 {
4599 VTermScreenCell cell;
4600 int same_attr;
4601 int same_chars = TRUE;
4602 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004603 int is_cursor_pos = (pos.col == cursor_pos.col
4604 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004605
4606 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
Bram Moolenaara80faa82020-04-12 19:37:17 +02004607 CLEAR_FIELD(cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004608
4609 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4610 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01004611 int c = cell.chars[i];
4612 int pc = prev_cell.chars[i];
4613
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004614 // For the first character NUL is the same as space.
Bram Moolenaar47015b82018-03-23 22:10:34 +01004615 if (i == 0)
4616 {
4617 c = (c == NUL) ? ' ' : c;
4618 pc = (pc == NUL) ? ' ' : pc;
4619 }
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004620 if (c != pc)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004621 same_chars = FALSE;
Bram Moolenaar98fc8d72018-08-24 21:30:28 +02004622 if (c == NUL || pc == NUL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004623 break;
4624 }
4625 same_attr = vtermAttr2hl(cell.attrs)
4626 == vtermAttr2hl(prev_cell.attrs)
4627 && same_color(&cell.fg, &prev_cell.fg)
4628 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004629 if (same_chars && cell.width == prev_cell.width && same_attr
4630 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004631 {
4632 ++repeat;
4633 }
4634 else
4635 {
4636 if (repeat > 0)
4637 {
4638 fprintf(fd, "@%d", repeat);
4639 repeat = 0;
4640 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004641 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004642
4643 if (cell.chars[0] == NUL)
4644 fputs(" ", fd);
4645 else
4646 {
4647 char_u charbuf[10];
4648 int len;
4649
4650 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
4651 && cell.chars[i] != NUL; ++i)
4652 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02004653 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004654 fwrite(charbuf, len, 1, fd);
4655 }
4656 }
4657
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004658 // When only the characters differ we don't write anything, the
4659 // following "|", "@" or NL will indicate using the same
4660 // attributes.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004661 if (cell.width != prev_cell.width || !same_attr)
4662 {
4663 if (cell.width == 2)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004664 fputs("*", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004665 else
4666 fputs("+", fd);
4667
4668 if (same_attr)
4669 {
4670 fputs("&", fd);
4671 }
4672 else
4673 {
4674 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
4675 if (same_color(&cell.fg, &prev_cell.fg))
4676 fputs("&", fd);
4677 else
4678 {
4679 fputs("#", fd);
4680 dump_term_color(fd, &cell.fg);
4681 }
4682 if (same_color(&cell.bg, &prev_cell.bg))
4683 fputs("&", fd);
4684 else
4685 {
4686 fputs("#", fd);
4687 dump_term_color(fd, &cell.bg);
4688 }
4689 }
4690 }
4691
4692 prev_cell = cell;
4693 }
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004694
4695 if (cell.width == 2)
4696 ++pos.col;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004697 }
4698 if (repeat > 0)
4699 fprintf(fd, "@%d", repeat);
4700 fputs("\n", fd);
4701 }
4702
4703 fclose(fd);
4704}
4705
4706/*
4707 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4708 */
4709 static void
4710dump_is_corrupt(garray_T *gap)
4711{
4712 ga_concat(gap, (char_u *)"CORRUPT");
4713}
4714
4715 static void
4716append_cell(garray_T *gap, cellattr_T *cell)
4717{
4718 if (ga_grow(gap, 1) == OK)
4719 {
4720 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4721 ++gap->ga_len;
4722 }
4723}
4724
4725/*
4726 * Read the dump file from "fd" and append lines to the current buffer.
4727 * Return the cell width of the longest line.
4728 */
4729 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004730read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004731{
4732 int c;
4733 garray_T ga_text;
4734 garray_T ga_cell;
4735 char_u *prev_char = NULL;
4736 int attr = 0;
4737 cellattr_T cell;
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004738 cellattr_T empty_cell;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004739 term_T *term = curbuf->b_term;
4740 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004741 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004742
4743 ga_init2(&ga_text, 1, 90);
4744 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
Bram Moolenaara80faa82020-04-12 19:37:17 +02004745 CLEAR_FIELD(cell);
4746 CLEAR_FIELD(empty_cell);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004747 cursor_pos->row = -1;
4748 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004749
4750 c = fgetc(fd);
4751 for (;;)
4752 {
4753 if (c == EOF)
4754 break;
Bram Moolenaar0fd6be72018-10-23 21:42:59 +02004755 if (c == '\r')
4756 {
4757 // DOS line endings? Ignore.
4758 c = fgetc(fd);
4759 }
4760 else if (c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004761 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004762 // End of a line: append it to the buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01004763 if (ga_text.ga_data == NULL)
4764 dump_is_corrupt(&ga_text);
4765 if (ga_grow(&term->tl_scrollback, 1) == OK)
4766 {
4767 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4768 + term->tl_scrollback.ga_len;
4769
4770 if (max_cells < ga_cell.ga_len)
4771 max_cells = ga_cell.ga_len;
4772 line->sb_cols = ga_cell.ga_len;
4773 line->sb_cells = ga_cell.ga_data;
4774 line->sb_fill_attr = term->tl_default_color;
4775 ++term->tl_scrollback.ga_len;
4776 ga_init(&ga_cell);
4777
4778 ga_append(&ga_text, NUL);
4779 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4780 ga_text.ga_len, FALSE);
4781 }
4782 else
4783 ga_clear(&ga_cell);
4784 ga_text.ga_len = 0;
4785
4786 c = fgetc(fd);
4787 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004788 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004789 {
4790 int prev_len = ga_text.ga_len;
4791
Bram Moolenaar9271d052018-02-25 21:39:46 +01004792 if (c == '>')
4793 {
4794 if (cursor_pos->row != -1)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004795 dump_is_corrupt(&ga_text); // duplicate cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01004796 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4797 cursor_pos->col = ga_cell.ga_len;
4798 }
4799
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004800 // normal character(s) followed by "+", "*", "|", "@" or NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004801 c = fgetc(fd);
4802 if (c != EOF)
4803 ga_append(&ga_text, c);
4804 for (;;)
4805 {
4806 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004807 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004808 || c == EOF || c == '\n')
4809 break;
4810 ga_append(&ga_text, c);
4811 }
4812
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004813 // save the character for repeating it
Bram Moolenaard96ff162018-02-18 22:13:29 +01004814 vim_free(prev_char);
4815 if (ga_text.ga_data != NULL)
4816 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4817 ga_text.ga_len - prev_len);
4818
Bram Moolenaar9271d052018-02-25 21:39:46 +01004819 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004820 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004821 // use all attributes from previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004822 }
4823 else if (c == '+' || c == '*')
4824 {
4825 int is_bg;
4826
4827 cell.width = c == '+' ? 1 : 2;
4828
4829 c = fgetc(fd);
4830 if (c == '&')
4831 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004832 // use same attr as previous cell
Bram Moolenaard96ff162018-02-18 22:13:29 +01004833 c = fgetc(fd);
4834 }
4835 else if (isdigit(c))
4836 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004837 // get the decimal attribute
Bram Moolenaard96ff162018-02-18 22:13:29 +01004838 attr = 0;
4839 while (isdigit(c))
4840 {
4841 attr = attr * 10 + (c - '0');
4842 c = fgetc(fd);
4843 }
4844 hl2vtermAttr(attr, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004845
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004846 // is_bg == 0: fg, is_bg == 1: bg
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004847 for (is_bg = 0; is_bg <= 1; ++is_bg)
4848 {
4849 if (c == '&')
4850 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004851 // use same color as previous cell
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004852 c = fgetc(fd);
4853 }
4854 else if (c == '#')
4855 {
4856 int red, green, blue, index = 0;
4857
4858 c = fgetc(fd);
4859 red = hex2nr(c);
4860 c = fgetc(fd);
4861 red = (red << 4) + hex2nr(c);
4862 c = fgetc(fd);
4863 green = hex2nr(c);
4864 c = fgetc(fd);
4865 green = (green << 4) + hex2nr(c);
4866 c = fgetc(fd);
4867 blue = hex2nr(c);
4868 c = fgetc(fd);
4869 blue = (blue << 4) + hex2nr(c);
4870 c = fgetc(fd);
4871 if (!isdigit(c))
4872 dump_is_corrupt(&ga_text);
4873 while (isdigit(c))
4874 {
4875 index = index * 10 + (c - '0');
4876 c = fgetc(fd);
4877 }
4878
4879 if (is_bg)
4880 {
4881 cell.bg.red = red;
4882 cell.bg.green = green;
4883 cell.bg.blue = blue;
4884 cell.bg.ansi_index = index;
4885 }
4886 else
4887 {
4888 cell.fg.red = red;
4889 cell.fg.green = green;
4890 cell.fg.blue = blue;
4891 cell.fg.ansi_index = index;
4892 }
4893 }
4894 else
4895 dump_is_corrupt(&ga_text);
4896 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004897 }
4898 else
4899 dump_is_corrupt(&ga_text);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004900 }
4901 else
4902 dump_is_corrupt(&ga_text);
4903
4904 append_cell(&ga_cell, &cell);
Bram Moolenaar617d7ef2019-01-17 13:04:30 +01004905 if (cell.width == 2)
4906 append_cell(&ga_cell, &empty_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004907 }
4908 else if (c == '@')
4909 {
4910 if (prev_char == NULL)
4911 dump_is_corrupt(&ga_text);
4912 else
4913 {
4914 int count = 0;
4915
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004916 // repeat previous character, get the count
Bram Moolenaard96ff162018-02-18 22:13:29 +01004917 for (;;)
4918 {
4919 c = fgetc(fd);
4920 if (!isdigit(c))
4921 break;
4922 count = count * 10 + (c - '0');
4923 }
4924
4925 while (count-- > 0)
4926 {
4927 ga_concat(&ga_text, prev_char);
4928 append_cell(&ga_cell, &cell);
4929 }
4930 }
4931 }
4932 else
4933 {
4934 dump_is_corrupt(&ga_text);
4935 c = fgetc(fd);
4936 }
4937 }
4938
4939 if (ga_text.ga_len > 0)
4940 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004941 // trailing characters after last NL
Bram Moolenaard96ff162018-02-18 22:13:29 +01004942 dump_is_corrupt(&ga_text);
4943 ga_append(&ga_text, NUL);
4944 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4945 ga_text.ga_len, FALSE);
4946 }
4947
4948 ga_clear(&ga_text);
Bram Moolenaar86173482019-10-01 17:02:16 +02004949 ga_clear(&ga_cell);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004950 vim_free(prev_char);
4951
4952 return max_cells;
4953}
4954
4955/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004956 * Return an allocated string with at least "text_width" "=" characters and
4957 * "fname" inserted in the middle.
4958 */
4959 static char_u *
4960get_separator(int text_width, char_u *fname)
4961{
4962 int width = MAX(text_width, curwin->w_width);
4963 char_u *textline;
4964 int fname_size;
4965 char_u *p = fname;
4966 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004967 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004968
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004969 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004970 if (textline == NULL)
4971 return NULL;
4972
4973 fname_size = vim_strsize(fname);
4974 if (fname_size < width - 8)
4975 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004976 // enough room, don't use the full window width
Bram Moolenaar4a696342018-04-05 18:45:26 +02004977 width = MAX(text_width, fname_size + 8);
4978 }
4979 else if (fname_size > width - 8)
4980 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004981 // full name doesn't fit, use only the tail
Bram Moolenaar4a696342018-04-05 18:45:26 +02004982 p = gettail(fname);
4983 fname_size = vim_strsize(p);
4984 }
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01004985 // skip characters until the name fits
Bram Moolenaar4a696342018-04-05 18:45:26 +02004986 while (fname_size > width - 8)
4987 {
4988 p += (*mb_ptr2len)(p);
4989 fname_size = vim_strsize(p);
4990 }
4991
4992 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4993 textline[i] = '=';
4994 textline[i++] = ' ';
4995
4996 STRCPY(textline + i, p);
4997 off = STRLEN(textline);
4998 textline[off] = ' ';
4999 for (i = 1; i < (width - fname_size) / 2; ++i)
5000 textline[off + i] = '=';
5001 textline[off + i] = NUL;
5002
5003 return textline;
5004}
5005
5006/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01005007 * Common for "term_dumpdiff()" and "term_dumpload()".
5008 */
5009 static void
5010term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
5011{
5012 jobopt_T opt;
Bram Moolenaar87abab92019-06-03 21:14:59 +02005013 buf_T *buf = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005014 char_u buf1[NUMBUFLEN];
5015 char_u buf2[NUMBUFLEN];
5016 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005017 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005018 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005019 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005020 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005021 char_u *textline = NULL;
5022
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005023 // First open the files. If this fails bail out.
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005024 fname1 = tv_get_string_buf_chk(&argvars[0], buf1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005025 if (do_diff)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005026 fname2 = tv_get_string_buf_chk(&argvars[1], buf2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005027 if (fname1 == NULL || (do_diff && fname2 == NULL))
5028 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005029 emsg(_(e_invarg));
Bram Moolenaard96ff162018-02-18 22:13:29 +01005030 return;
5031 }
5032 fd1 = mch_fopen((char *)fname1, READBIN);
5033 if (fd1 == NULL)
5034 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005035 semsg(_(e_notread), fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005036 return;
5037 }
5038 if (do_diff)
5039 {
5040 fd2 = mch_fopen((char *)fname2, READBIN);
5041 if (fd2 == NULL)
5042 {
5043 fclose(fd1);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005044 semsg(_(e_notread), fname2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005045 return;
5046 }
5047 }
5048
5049 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005050 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
5051 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
5052 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
5053 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
5054 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005055
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005056 if (opt.jo_term_name == NULL)
5057 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01005058 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005059
Bram Moolenaar51e14382019-05-25 20:21:28 +02005060 fname_tofree = alloc(len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005061 if (fname_tofree != NULL)
5062 {
5063 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
5064 opt.jo_term_name = fname_tofree;
5065 }
5066 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005067
Bram Moolenaar87abab92019-06-03 21:14:59 +02005068 if (opt.jo_bufnr_buf != NULL)
5069 {
5070 win_T *wp = buf_jump_open_win(opt.jo_bufnr_buf);
5071
5072 // With "bufnr" argument: enter the window with this buffer and make it
5073 // empty.
5074 if (wp == NULL)
5075 semsg(_(e_invarg2), "bufnr");
5076 else
5077 {
5078 buf = curbuf;
5079 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
5080 ml_delete((linenr_T)1, FALSE);
Bram Moolenaar86173482019-10-01 17:02:16 +02005081 free_scrollback(curbuf->b_term);
Bram Moolenaar87abab92019-06-03 21:14:59 +02005082 redraw_later(NOT_VALID);
5083 }
5084 }
5085 else
5086 // Create a new terminal window.
5087 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
5088
Bram Moolenaard96ff162018-02-18 22:13:29 +01005089 if (buf != NULL && buf->b_term != NULL)
5090 {
5091 int i;
5092 linenr_T bot_lnum;
5093 linenr_T lnum;
5094 term_T *term = buf->b_term;
5095 int width;
5096 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005097 VTermPos cursor_pos1;
5098 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005099
Bram Moolenaar219c7d02020-02-01 21:57:29 +01005100 init_default_colors(term, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01005101
Bram Moolenaard96ff162018-02-18 22:13:29 +01005102 rettv->vval.v_number = buf->b_fnum;
5103
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005104 // read the files, fill the buffer with the diff
Bram Moolenaar9271d052018-02-25 21:39:46 +01005105 width = read_dump_file(fd1, &cursor_pos1);
5106
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005107 // position the cursor
Bram Moolenaar9271d052018-02-25 21:39:46 +01005108 if (cursor_pos1.row >= 0)
5109 {
5110 curwin->w_cursor.lnum = cursor_pos1.row + 1;
5111 coladvance(cursor_pos1.col);
5112 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005113
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005114 // Delete the empty line that was in the empty buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005115 ml_delete(1, FALSE);
5116
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005117 // For term_dumpload() we are done here.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005118 if (!do_diff)
5119 goto theend;
5120
5121 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
5122
Bram Moolenaar4a696342018-04-05 18:45:26 +02005123 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005124 if (textline == NULL)
5125 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005126 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5127 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
5128 vim_free(textline);
5129
5130 textline = get_separator(width, fname2);
5131 if (textline == NULL)
5132 goto theend;
5133 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
5134 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005135 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005136
5137 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01005138 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005139 if (width2 > width)
5140 {
5141 vim_free(textline);
5142 textline = alloc(width2 + 1);
5143 if (textline == NULL)
5144 goto theend;
5145 width = width2;
5146 textline[width] = NUL;
5147 }
5148 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
5149
5150 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
5151 {
5152 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
5153 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005154 // bottom part has fewer rows, fill with "-"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005155 for (i = 0; i < width; ++i)
5156 textline[i] = '-';
5157 }
5158 else
5159 {
5160 char_u *line1;
5161 char_u *line2;
5162 char_u *p1;
5163 char_u *p2;
5164 int col;
5165 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5166 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
5167 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
5168 ->sb_cells;
5169
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005170 // Make a copy, getting the second line will invalidate it.
Bram Moolenaard96ff162018-02-18 22:13:29 +01005171 line1 = vim_strsave(ml_get(lnum));
5172 if (line1 == NULL)
5173 break;
5174 p1 = line1;
5175
5176 line2 = ml_get(lnum + bot_lnum);
5177 p2 = line2;
5178 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
5179 {
5180 int len1 = utfc_ptr2len(p1);
5181 int len2 = utfc_ptr2len(p2);
5182
5183 textline[col] = ' ';
5184 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005185 // text differs
Bram Moolenaard96ff162018-02-18 22:13:29 +01005186 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01005187 else if (lnum == cursor_pos1.row + 1
5188 && col == cursor_pos1.col
5189 && (cursor_pos1.row != cursor_pos2.row
5190 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005191 // cursor in first but not in second
Bram Moolenaar9271d052018-02-25 21:39:46 +01005192 textline[col] = '>';
5193 else if (lnum == cursor_pos2.row + 1
5194 && col == cursor_pos2.col
5195 && (cursor_pos1.row != cursor_pos2.row
5196 || cursor_pos1.col != cursor_pos2.col))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005197 // cursor in second but not in first
Bram Moolenaar9271d052018-02-25 21:39:46 +01005198 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01005199 else if (cellattr1 != NULL && cellattr2 != NULL)
5200 {
5201 if ((cellattr1 + col)->width
5202 != (cellattr2 + col)->width)
5203 textline[col] = 'w';
5204 else if (!same_color(&(cellattr1 + col)->fg,
5205 &(cellattr2 + col)->fg))
5206 textline[col] = 'f';
5207 else if (!same_color(&(cellattr1 + col)->bg,
5208 &(cellattr2 + col)->bg))
5209 textline[col] = 'b';
5210 else if (vtermAttr2hl((cellattr1 + col)->attrs)
5211 != vtermAttr2hl(((cellattr2 + col)->attrs)))
5212 textline[col] = 'a';
5213 }
5214 p1 += len1;
5215 p2 += len2;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005216 // TODO: handle different width
Bram Moolenaard96ff162018-02-18 22:13:29 +01005217 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01005218
5219 while (col < width)
5220 {
5221 if (*p1 == NUL && *p2 == NUL)
5222 textline[col] = '?';
5223 else if (*p1 == NUL)
5224 {
5225 textline[col] = '+';
5226 p2 += utfc_ptr2len(p2);
5227 }
5228 else
5229 {
5230 textline[col] = '-';
5231 p1 += utfc_ptr2len(p1);
5232 }
5233 ++col;
5234 }
Bram Moolenaar81aa0f52019-02-14 23:23:19 +01005235
5236 vim_free(line1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005237 }
5238 if (add_empty_scrollback(term, &term->tl_default_color,
5239 term->tl_top_diff_rows) == OK)
5240 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5241 ++bot_lnum;
5242 }
5243
5244 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
5245 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005246 // bottom part has more rows, fill with "+"
Bram Moolenaard96ff162018-02-18 22:13:29 +01005247 for (i = 0; i < width; ++i)
5248 textline[i] = '+';
5249 if (add_empty_scrollback(term, &term->tl_default_color,
5250 term->tl_top_diff_rows) == OK)
5251 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
5252 ++lnum;
5253 ++bot_lnum;
5254 }
5255
5256 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02005257
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005258 // looks better without wrapping
Bram Moolenaar4a696342018-04-05 18:45:26 +02005259 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01005260 }
5261
5262theend:
5263 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01005264 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005265 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01005266 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01005267 fclose(fd2);
5268}
5269
5270/*
5271 * If the current buffer shows the output of term_dumpdiff(), swap the top and
5272 * bottom files.
5273 * Return FAIL when this is not possible.
5274 */
5275 int
5276term_swap_diff()
5277{
5278 term_T *term = curbuf->b_term;
5279 linenr_T line_count;
5280 linenr_T top_rows;
5281 linenr_T bot_rows;
5282 linenr_T bot_start;
5283 linenr_T lnum;
5284 char_u *p;
5285 sb_line_T *sb_line;
5286
5287 if (term == NULL
5288 || !term_is_finished(curbuf)
5289 || term->tl_top_diff_rows == 0
5290 || term->tl_scrollback.ga_len == 0)
5291 return FAIL;
5292
5293 line_count = curbuf->b_ml.ml_line_count;
5294 top_rows = term->tl_top_diff_rows;
5295 bot_rows = term->tl_bot_diff_rows;
5296 bot_start = line_count - bot_rows;
5297 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
5298
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005299 // move lines from top to above the bottom part
Bram Moolenaard96ff162018-02-18 22:13:29 +01005300 for (lnum = 1; lnum <= top_rows; ++lnum)
5301 {
5302 p = vim_strsave(ml_get(1));
5303 if (p == NULL)
5304 return OK;
5305 ml_append(bot_start, p, 0, FALSE);
5306 ml_delete(1, FALSE);
5307 vim_free(p);
5308 }
5309
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005310 // move lines from bottom to the top
Bram Moolenaard96ff162018-02-18 22:13:29 +01005311 for (lnum = 1; lnum <= bot_rows; ++lnum)
5312 {
5313 p = vim_strsave(ml_get(bot_start + lnum));
5314 if (p == NULL)
5315 return OK;
5316 ml_delete(bot_start + lnum, FALSE);
5317 ml_append(lnum - 1, p, 0, FALSE);
5318 vim_free(p);
5319 }
5320
Bram Moolenaarc3ef8962019-02-15 00:16:13 +01005321 // move top title to bottom
5322 p = vim_strsave(ml_get(bot_rows + 1));
5323 if (p == NULL)
5324 return OK;
5325 ml_append(line_count - top_rows - 1, p, 0, FALSE);
5326 ml_delete(bot_rows + 1, FALSE);
5327 vim_free(p);
5328
5329 // move bottom title to top
5330 p = vim_strsave(ml_get(line_count - top_rows));
5331 if (p == NULL)
5332 return OK;
5333 ml_delete(line_count - top_rows, FALSE);
5334 ml_append(bot_rows, p, 0, FALSE);
5335 vim_free(p);
5336
Bram Moolenaard96ff162018-02-18 22:13:29 +01005337 if (top_rows == bot_rows)
5338 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005339 // rows counts are equal, can swap cell properties
Bram Moolenaard96ff162018-02-18 22:13:29 +01005340 for (lnum = 0; lnum < top_rows; ++lnum)
5341 {
5342 sb_line_T temp;
5343
5344 temp = *(sb_line + lnum);
5345 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
5346 *(sb_line + bot_start + lnum) = temp;
5347 }
5348 }
5349 else
5350 {
5351 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02005352 sb_line_T *temp = alloc(size);
Bram Moolenaard96ff162018-02-18 22:13:29 +01005353
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005354 // need to copy cell properties into temp memory
Bram Moolenaard96ff162018-02-18 22:13:29 +01005355 if (temp != NULL)
5356 {
5357 mch_memmove(temp, term->tl_scrollback.ga_data, size);
5358 mch_memmove(term->tl_scrollback.ga_data,
5359 temp + bot_start,
5360 sizeof(sb_line_T) * bot_rows);
5361 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
5362 temp + top_rows,
5363 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
5364 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
5365 + line_count - top_rows,
5366 temp,
5367 sizeof(sb_line_T) * top_rows);
5368 vim_free(temp);
5369 }
5370 }
5371
5372 term->tl_top_diff_rows = bot_rows;
5373 term->tl_bot_diff_rows = top_rows;
5374
5375 update_screen(NOT_VALID);
5376 return OK;
5377}
5378
5379/*
5380 * "term_dumpdiff(filename, filename, options)" function
5381 */
5382 void
5383f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
5384{
5385 term_load_dump(argvars, rettv, TRUE);
5386}
5387
5388/*
5389 * "term_dumpload(filename, options)" function
5390 */
5391 void
5392f_term_dumpload(typval_T *argvars, typval_T *rettv)
5393{
5394 term_load_dump(argvars, rettv, FALSE);
5395}
5396
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005397/*
5398 * "term_getaltscreen(buf)" function
5399 */
5400 void
5401f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
5402{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005403 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005404
5405 if (buf == NULL)
5406 return;
5407 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
5408}
5409
5410/*
5411 * "term_getattr(attr, name)" function
5412 */
5413 void
5414f_term_getattr(typval_T *argvars, typval_T *rettv)
5415{
5416 int attr;
5417 size_t i;
5418 char_u *name;
5419
5420 static struct {
5421 char *name;
5422 int attr;
5423 } attrs[] = {
5424 {"bold", HL_BOLD},
5425 {"italic", HL_ITALIC},
5426 {"underline", HL_UNDERLINE},
5427 {"strike", HL_STRIKETHROUGH},
5428 {"reverse", HL_INVERSE},
5429 };
5430
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005431 attr = tv_get_number(&argvars[0]);
5432 name = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005433 if (name == NULL)
5434 return;
5435
Bram Moolenaar7ee80f72019-09-08 20:55:06 +02005436 if (attr > HL_ALL)
5437 attr = syn_attr2attr(attr);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005438 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
5439 if (STRCMP(name, attrs[i].name) == 0)
5440 {
5441 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
5442 break;
5443 }
5444}
5445
5446/*
5447 * "term_getcursor(buf)" function
5448 */
5449 void
5450f_term_getcursor(typval_T *argvars, typval_T *rettv)
5451{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005452 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005453 term_T *term;
5454 list_T *l;
5455 dict_T *d;
5456
5457 if (rettv_list_alloc(rettv) == FAIL)
5458 return;
5459 if (buf == NULL)
5460 return;
5461 term = buf->b_term;
5462
5463 l = rettv->vval.v_list;
5464 list_append_number(l, term->tl_cursor_pos.row + 1);
5465 list_append_number(l, term->tl_cursor_pos.col + 1);
5466
5467 d = dict_alloc();
5468 if (d != NULL)
5469 {
Bram Moolenaare0be1672018-07-08 16:50:37 +02005470 dict_add_number(d, "visible", term->tl_cursor_visible);
5471 dict_add_number(d, "blink", blink_state_is_inverted()
5472 ? !term->tl_cursor_blink : term->tl_cursor_blink);
5473 dict_add_number(d, "shape", term->tl_cursor_shape);
5474 dict_add_string(d, "color", cursor_color_get(term->tl_cursor_color));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005475 list_append_dict(l, d);
5476 }
5477}
5478
5479/*
5480 * "term_getjob(buf)" function
5481 */
5482 void
5483f_term_getjob(typval_T *argvars, typval_T *rettv)
5484{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005485 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005486
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005487 if (buf == NULL)
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005488 {
5489 rettv->v_type = VAR_SPECIAL;
5490 rettv->vval.v_number = VVAL_NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005491 return;
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005492 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005493
Bram Moolenaar528ccfb2018-12-21 20:55:22 +01005494 rettv->v_type = VAR_JOB;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005495 rettv->vval.v_job = buf->b_term->tl_job;
5496 if (rettv->vval.v_job != NULL)
5497 ++rettv->vval.v_job->jv_refcount;
5498}
5499
5500 static int
5501get_row_number(typval_T *tv, term_T *term)
5502{
5503 if (tv->v_type == VAR_STRING
5504 && tv->vval.v_string != NULL
5505 && STRCMP(tv->vval.v_string, ".") == 0)
5506 return term->tl_cursor_pos.row;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005507 return (int)tv_get_number(tv) - 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005508}
5509
5510/*
5511 * "term_getline(buf, row)" function
5512 */
5513 void
5514f_term_getline(typval_T *argvars, typval_T *rettv)
5515{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005516 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005517 term_T *term;
5518 int row;
5519
5520 rettv->v_type = VAR_STRING;
5521 if (buf == NULL)
5522 return;
5523 term = buf->b_term;
5524 row = get_row_number(&argvars[1], term);
5525
5526 if (term->tl_vterm == NULL)
5527 {
5528 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
5529
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005530 // vterm is finished, get the text from the buffer
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005531 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
5532 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
5533 }
5534 else
5535 {
5536 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
5537 VTermRect rect;
5538 int len;
5539 char_u *p;
5540
5541 if (row < 0 || row >= term->tl_rows)
5542 return;
5543 len = term->tl_cols * MB_MAXBYTES + 1;
5544 p = alloc(len);
5545 if (p == NULL)
5546 return;
5547 rettv->vval.v_string = p;
5548
5549 rect.start_col = 0;
5550 rect.end_col = term->tl_cols;
5551 rect.start_row = row;
5552 rect.end_row = row + 1;
5553 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
5554 }
5555}
5556
5557/*
5558 * "term_getscrolled(buf)" function
5559 */
5560 void
5561f_term_getscrolled(typval_T *argvars, typval_T *rettv)
5562{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005563 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005564
5565 if (buf == NULL)
5566 return;
5567 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
5568}
5569
5570/*
5571 * "term_getsize(buf)" function
5572 */
5573 void
5574f_term_getsize(typval_T *argvars, typval_T *rettv)
5575{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005576 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005577 list_T *l;
5578
5579 if (rettv_list_alloc(rettv) == FAIL)
5580 return;
5581 if (buf == NULL)
5582 return;
5583
5584 l = rettv->vval.v_list;
5585 list_append_number(l, buf->b_term->tl_rows);
5586 list_append_number(l, buf->b_term->tl_cols);
5587}
5588
5589/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005590 * "term_setsize(buf, rows, cols)" function
5591 */
5592 void
5593f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5594{
5595 buf_T *buf = term_get_buf(argvars, "term_setsize()");
5596 term_T *term;
5597 varnumber_T rows, cols;
5598
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005599 if (buf == NULL)
5600 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005601 emsg(_("E955: Not a terminal buffer"));
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02005602 return;
5603 }
5604 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02005605 return;
5606 term = buf->b_term;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005607 rows = tv_get_number(&argvars[1]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005608 rows = rows <= 0 ? term->tl_rows : rows;
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005609 cols = tv_get_number(&argvars[2]);
Bram Moolenaara42d3632018-04-14 17:05:38 +02005610 cols = cols <= 0 ? term->tl_cols : cols;
5611 vterm_set_size(term->tl_vterm, rows, cols);
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005612 // handle_resize() will resize the windows
Bram Moolenaara42d3632018-04-14 17:05:38 +02005613
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005614 // Get and remember the size we ended up with. Update the pty.
Bram Moolenaara42d3632018-04-14 17:05:38 +02005615 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
5616 term_report_winsize(term, term->tl_rows, term->tl_cols);
5617}
5618
5619/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005620 * "term_getstatus(buf)" function
5621 */
5622 void
5623f_term_getstatus(typval_T *argvars, typval_T *rettv)
5624{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005625 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005626 term_T *term;
5627 char_u val[100];
5628
5629 rettv->v_type = VAR_STRING;
5630 if (buf == NULL)
5631 return;
5632 term = buf->b_term;
5633
5634 if (term_job_running(term))
5635 STRCPY(val, "running");
5636 else
5637 STRCPY(val, "finished");
5638 if (term->tl_normal_mode)
5639 STRCAT(val, ",normal");
5640 rettv->vval.v_string = vim_strsave(val);
5641}
5642
5643/*
5644 * "term_gettitle(buf)" function
5645 */
5646 void
5647f_term_gettitle(typval_T *argvars, typval_T *rettv)
5648{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005649 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005650
5651 rettv->v_type = VAR_STRING;
5652 if (buf == NULL)
5653 return;
5654
5655 if (buf->b_term->tl_title != NULL)
5656 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
5657}
5658
5659/*
5660 * "term_gettty(buf)" function
5661 */
5662 void
5663f_term_gettty(typval_T *argvars, typval_T *rettv)
5664{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005665 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02005666 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005667 int num = 0;
5668
5669 rettv->v_type = VAR_STRING;
5670 if (buf == NULL)
5671 return;
5672 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005673 num = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005674
5675 switch (num)
5676 {
5677 case 0:
5678 if (buf->b_term->tl_job != NULL)
5679 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005680 break;
5681 case 1:
5682 if (buf->b_term->tl_job != NULL)
5683 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005684 break;
5685 default:
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005686 semsg(_(e_invarg2), tv_get_string(&argvars[1]));
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005687 return;
5688 }
5689 if (p != NULL)
5690 rettv->vval.v_string = vim_strsave(p);
5691}
5692
5693/*
5694 * "term_list()" function
5695 */
5696 void
5697f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
5698{
5699 term_T *tp;
5700 list_T *l;
5701
5702 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
5703 return;
5704
5705 l = rettv->vval.v_list;
Bram Moolenaaraeea7212020-04-02 18:50:46 +02005706 FOR_ALL_TERMS(tp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005707 if (tp != NULL && tp->tl_buffer != NULL)
5708 if (list_append_number(l,
5709 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
5710 return;
5711}
5712
5713/*
5714 * "term_scrape(buf, row)" function
5715 */
5716 void
5717f_term_scrape(typval_T *argvars, typval_T *rettv)
5718{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005719 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005720 VTermScreen *screen = NULL;
5721 VTermPos pos;
5722 list_T *l;
5723 term_T *term;
5724 char_u *p;
5725 sb_line_T *line;
5726
5727 if (rettv_list_alloc(rettv) == FAIL)
5728 return;
5729 if (buf == NULL)
5730 return;
5731 term = buf->b_term;
5732
5733 l = rettv->vval.v_list;
5734 pos.row = get_row_number(&argvars[1], term);
5735
5736 if (term->tl_vterm != NULL)
5737 {
5738 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar06d62602018-12-27 21:27:03 +01005739 if (screen == NULL) // can't really happen
5740 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005741 p = NULL;
5742 line = NULL;
5743 }
5744 else
5745 {
5746 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5747
5748 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5749 return;
5750 p = ml_get_buf(buf, lnum + 1, FALSE);
5751 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5752 }
5753
5754 for (pos.col = 0; pos.col < term->tl_cols; )
5755 {
5756 dict_T *dcell;
5757 int width;
5758 VTermScreenCellAttrs attrs;
5759 VTermColor fg, bg;
5760 char_u rgb[8];
5761 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5762 int off = 0;
5763 int i;
5764
5765 if (screen == NULL)
5766 {
5767 cellattr_T *cellattr;
5768 int len;
5769
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01005770 // vterm has finished, get the cell from scrollback
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005771 if (pos.col >= line->sb_cols)
5772 break;
5773 cellattr = line->sb_cells + pos.col;
5774 width = cellattr->width;
5775 attrs = cellattr->attrs;
5776 fg = cellattr->fg;
5777 bg = cellattr->bg;
Bram Moolenaar1614a142019-10-06 22:00:13 +02005778 len = mb_ptr2len(p);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005779 mch_memmove(mbs, p, len);
5780 mbs[len] = NUL;
5781 p += len;
5782 }
5783 else
5784 {
5785 VTermScreenCell cell;
5786 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5787 break;
5788 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5789 {
5790 if (cell.chars[i] == 0)
5791 break;
5792 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5793 }
5794 mbs[off] = NUL;
5795 width = cell.width;
5796 attrs = cell.attrs;
5797 fg = cell.fg;
5798 bg = cell.bg;
5799 }
5800 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005801 if (dcell == NULL)
5802 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005803 list_append_dict(l, dcell);
5804
Bram Moolenaare0be1672018-07-08 16:50:37 +02005805 dict_add_string(dcell, "chars", mbs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005806
5807 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5808 fg.red, fg.green, fg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005809 dict_add_string(dcell, "fg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005810 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5811 bg.red, bg.green, bg.blue);
Bram Moolenaare0be1672018-07-08 16:50:37 +02005812 dict_add_string(dcell, "bg", rgb);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005813
Bram Moolenaar83d47902020-03-26 20:34:00 +01005814 dict_add_number(dcell, "attr", cell2attr(term, NULL, attrs, fg, bg));
Bram Moolenaare0be1672018-07-08 16:50:37 +02005815 dict_add_number(dcell, "width", width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005816
5817 ++pos.col;
5818 if (width == 2)
5819 ++pos.col;
5820 }
5821}
5822
5823/*
5824 * "term_sendkeys(buf, keys)" function
5825 */
5826 void
Bram Moolenaar3a05ce62020-03-11 19:30:01 +01005827f_term_sendkeys(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005828{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005829 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005830 char_u *msg;
5831 term_T *term;
5832
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005833 if (buf == NULL)
5834 return;
5835
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005836 msg = tv_get_string_chk(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005837 if (msg == NULL)
5838 return;
5839 term = buf->b_term;
5840 if (term->tl_vterm == NULL)
5841 return;
5842
5843 while (*msg != NUL)
5844 {
Bram Moolenaar6b810d92018-06-04 17:28:44 +02005845 int c;
5846
5847 if (*msg == K_SPECIAL && msg[1] != NUL && msg[2] != NUL)
5848 {
5849 c = TO_SPECIAL(msg[1], msg[2]);
5850 msg += 3;
5851 }
5852 else
5853 {
5854 c = PTR2CHAR(msg);
5855 msg += MB_CPTR2LEN(msg);
5856 }
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01005857 send_keys_to_term(term, c, 0, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005858 }
5859}
5860
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005861#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5862/*
5863 * "term_getansicolors(buf)" function
5864 */
5865 void
5866f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5867{
5868 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5869 term_T *term;
5870 VTermState *state;
5871 VTermColor color;
5872 char_u hexbuf[10];
5873 int index;
5874 list_T *list;
5875
5876 if (rettv_list_alloc(rettv) == FAIL)
5877 return;
5878
5879 if (buf == NULL)
5880 return;
5881 term = buf->b_term;
5882 if (term->tl_vterm == NULL)
5883 return;
5884
5885 list = rettv->vval.v_list;
5886 state = vterm_obtain_state(term->tl_vterm);
5887 for (index = 0; index < 16; index++)
5888 {
5889 vterm_state_get_palette_color(state, index, &color);
5890 sprintf((char *)hexbuf, "#%02x%02x%02x",
5891 color.red, color.green, color.blue);
5892 if (list_append_string(list, hexbuf, 7) == FAIL)
5893 return;
5894 }
5895}
5896
5897/*
5898 * "term_setansicolors(buf, list)" function
5899 */
5900 void
5901f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5902{
5903 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5904 term_T *term;
5905
5906 if (buf == NULL)
5907 return;
5908 term = buf->b_term;
5909 if (term->tl_vterm == NULL)
5910 return;
5911
5912 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5913 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005914 emsg(_(e_listreq));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005915 return;
5916 }
5917
5918 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005919 emsg(_(e_invarg));
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005920}
5921#endif
5922
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005923/*
Bram Moolenaard2842ea2019-09-26 23:08:54 +02005924 * "term_setapi(buf, api)" function
5925 */
5926 void
5927f_term_setapi(typval_T *argvars, typval_T *rettv UNUSED)
5928{
5929 buf_T *buf = term_get_buf(argvars, "term_setapi()");
5930 term_T *term;
5931 char_u *api;
5932
5933 if (buf == NULL)
5934 return;
5935 term = buf->b_term;
5936 vim_free(term->tl_api);
5937 api = tv_get_string_chk(&argvars[1]);
5938 if (api != NULL)
5939 term->tl_api = vim_strsave(api);
5940 else
5941 term->tl_api = NULL;
5942}
5943
5944/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005945 * "term_setrestore(buf, command)" function
5946 */
5947 void
5948f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5949{
5950#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005951 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005952 term_T *term;
5953 char_u *cmd;
5954
5955 if (buf == NULL)
5956 return;
5957 term = buf->b_term;
5958 vim_free(term->tl_command);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005959 cmd = tv_get_string_chk(&argvars[1]);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005960 if (cmd != NULL)
5961 term->tl_command = vim_strsave(cmd);
5962 else
5963 term->tl_command = NULL;
5964#endif
5965}
5966
5967/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005968 * "term_setkill(buf, how)" function
5969 */
5970 void
5971f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5972{
5973 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5974 term_T *term;
5975 char_u *how;
5976
5977 if (buf == NULL)
5978 return;
5979 term = buf->b_term;
5980 vim_free(term->tl_kill);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005981 how = tv_get_string_chk(&argvars[1]);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005982 if (how != NULL)
5983 term->tl_kill = vim_strsave(how);
5984 else
5985 term->tl_kill = NULL;
5986}
5987
5988/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005989 * "term_start(command, options)" function
5990 */
5991 void
5992f_term_start(typval_T *argvars, typval_T *rettv)
5993{
5994 jobopt_T opt;
5995 buf_T *buf;
5996
5997 init_job_options(&opt);
5998 if (argvars[1].v_type != VAR_UNKNOWN
5999 && get_job_options(&argvars[1], &opt,
6000 JO_TIMEOUT_ALL + JO_STOPONEXIT
6001 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
6002 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
6003 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
6004 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01006005 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar83d47902020-03-26 20:34:00 +01006006 + JO2_NORESTORE + JO2_TERM_KILL + JO2_TERM_HIGHLIGHT
Bram Moolenaard2842ea2019-09-26 23:08:54 +02006007 + JO2_ANSI_COLORS + JO2_TTY_TYPE + JO2_TERM_API) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006008 return;
6009
Bram Moolenaar13568252018-03-16 20:46:58 +01006010 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006011
6012 if (buf != NULL && buf->b_term != NULL)
6013 rettv->vval.v_number = buf->b_fnum;
6014}
6015
6016/*
6017 * "term_wait" function
6018 */
6019 void
6020f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
6021{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01006022 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006023
6024 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006025 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006026 if (buf->b_term->tl_job == NULL)
6027 {
6028 ch_log(NULL, "term_wait(): no job to wait for");
6029 return;
6030 }
6031 if (buf->b_term->tl_job->jv_channel == NULL)
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006032 // channel is closed, nothing to do
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006033 return;
6034
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006035 // Get the job status, this will detect a job that finished.
Bram Moolenaara15ef452018-02-09 16:46:00 +01006036 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006037 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
6038 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006039 // The job is dead, keep reading channel I/O until the channel is
6040 // closed. buf->b_term may become NULL if the terminal was closed while
6041 // waiting.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006042 ch_log(NULL, "term_wait(): waiting for channel to close");
6043 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
6044 {
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006045 term_flush_messages();
6046
Bram Moolenaard45aa552018-05-21 22:50:29 +02006047 ui_delay(10L, FALSE);
Bram Moolenaare5182262017-11-19 15:05:44 +01006048 if (!buf_valid(buf))
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006049 // If the terminal is closed when the channel is closed the
6050 // buffer disappears.
Bram Moolenaare5182262017-11-19 15:05:44 +01006051 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006052 }
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006053
6054 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006055 }
6056 else
6057 {
6058 long wait = 10L;
6059
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006060 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006061
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006062 // Wait for some time for any channel I/O.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006063 if (argvars[1].v_type != VAR_UNKNOWN)
Bram Moolenaard155d7a2018-12-21 16:04:21 +01006064 wait = tv_get_number(&argvars[1]);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006065 ui_delay(wait, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006066
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006067 // Flushing messages on channels is hopefully sufficient.
6068 // TODO: is there a better way?
Bram Moolenaar5c381eb2019-06-25 06:50:31 +02006069 term_flush_messages();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006070 }
6071}
6072
6073/*
6074 * Called when a channel has sent all the lines to a terminal.
6075 * Send a CTRL-D to mark the end of the text.
6076 */
6077 void
6078term_send_eof(channel_T *ch)
6079{
6080 term_T *term;
6081
Bram Moolenaaraeea7212020-04-02 18:50:46 +02006082 FOR_ALL_TERMS(term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006083 if (term->tl_job == ch->ch_job)
6084 {
6085 if (term->tl_eof_chars != NULL)
6086 {
6087 channel_send(ch, PART_IN, term->tl_eof_chars,
6088 (int)STRLEN(term->tl_eof_chars), NULL);
6089 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
6090 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006091# ifdef MSWIN
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006092 else
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006093 // Default: CTRL-D
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006094 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
6095# endif
6096 }
6097}
6098
Bram Moolenaar113e1072019-01-20 15:30:40 +01006099#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006100 job_T *
6101term_getjob(term_T *term)
6102{
6103 return term != NULL ? term->tl_job : NULL;
6104}
Bram Moolenaar113e1072019-01-20 15:30:40 +01006105#endif
Bram Moolenaarf9c38832018-06-19 19:59:20 +02006106
Bram Moolenaar4f974752019-02-17 17:44:42 +01006107# if defined(MSWIN) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006108
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006109///////////////////////////////////////
6110// 2. MS-Windows implementation.
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006111#ifdef PROTO
6112typedef int COORD;
6113typedef int DWORD;
6114typedef int HANDLE;
6115typedef int *DWORD_PTR;
6116typedef int HPCON;
6117typedef int HRESULT;
6118typedef int LPPROC_THREAD_ATTRIBUTE_LIST;
Bram Moolenaarad3ec762019-04-21 00:00:13 +02006119typedef int SIZE_T;
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006120typedef int PSIZE_T;
6121typedef int PVOID;
Bram Moolenaar1e814bc2019-11-03 21:19:41 +01006122typedef int BOOL;
6123# define WINAPI
Bram Moolenaarb9cdb372019-04-17 18:24:35 +02006124#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006125
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006126HRESULT (WINAPI *pCreatePseudoConsole)(COORD, HANDLE, HANDLE, DWORD, HPCON*);
6127HRESULT (WINAPI *pResizePseudoConsole)(HPCON, COORD);
6128HRESULT (WINAPI *pClosePseudoConsole)(HPCON);
Bram Moolenaar48773f12019-02-12 21:46:46 +01006129BOOL (WINAPI *pInitializeProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD, PSIZE_T);
6130BOOL (WINAPI *pUpdateProcThreadAttribute)(LPPROC_THREAD_ATTRIBUTE_LIST, DWORD, DWORD_PTR, PVOID, SIZE_T, PVOID, PSIZE_T);
6131void (WINAPI *pDeleteProcThreadAttributeList)(LPPROC_THREAD_ATTRIBUTE_LIST);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006132
6133 static int
6134dyn_conpty_init(int verbose)
6135{
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006136 static HMODULE hKerneldll = NULL;
6137 int i;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006138 static struct
6139 {
6140 char *name;
6141 FARPROC *ptr;
6142 } conpty_entry[] =
6143 {
6144 {"CreatePseudoConsole", (FARPROC*)&pCreatePseudoConsole},
6145 {"ResizePseudoConsole", (FARPROC*)&pResizePseudoConsole},
6146 {"ClosePseudoConsole", (FARPROC*)&pClosePseudoConsole},
6147 {"InitializeProcThreadAttributeList",
6148 (FARPROC*)&pInitializeProcThreadAttributeList},
6149 {"UpdateProcThreadAttribute",
6150 (FARPROC*)&pUpdateProcThreadAttribute},
6151 {"DeleteProcThreadAttributeList",
6152 (FARPROC*)&pDeleteProcThreadAttributeList},
6153 {NULL, NULL}
6154 };
6155
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006156 if (!has_conpty_working())
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006157 {
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006158 if (verbose)
6159 emsg(_("E982: ConPTY is not available"));
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006160 return FAIL;
6161 }
6162
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006163 // No need to initialize twice.
6164 if (hKerneldll)
6165 return OK;
6166
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006167 hKerneldll = vimLoadLib("kernel32.dll");
6168 for (i = 0; conpty_entry[i].name != NULL
6169 && conpty_entry[i].ptr != NULL; ++i)
6170 {
6171 if ((*conpty_entry[i].ptr = (FARPROC)GetProcAddress(hKerneldll,
6172 conpty_entry[i].name)) == NULL)
6173 {
6174 if (verbose)
6175 semsg(_(e_loadfunc), conpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006176 hKerneldll = NULL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006177 return FAIL;
6178 }
6179 }
6180
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006181 return OK;
6182}
6183
6184 static int
6185conpty_term_and_job_init(
6186 term_T *term,
6187 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006188 char **argv UNUSED,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006189 jobopt_T *opt,
6190 jobopt_T *orig_opt)
6191{
6192 WCHAR *cmd_wchar = NULL;
6193 WCHAR *cmd_wchar_copy = NULL;
6194 WCHAR *cwd_wchar = NULL;
6195 WCHAR *env_wchar = NULL;
6196 channel_T *channel = NULL;
6197 job_T *job = NULL;
6198 HANDLE jo = NULL;
6199 garray_T ga_cmd, ga_env;
6200 char_u *cmd = NULL;
6201 HRESULT hr;
6202 COORD consize;
6203 SIZE_T breq;
6204 PROCESS_INFORMATION proc_info;
6205 HANDLE i_theirs = NULL;
6206 HANDLE o_theirs = NULL;
6207 HANDLE i_ours = NULL;
6208 HANDLE o_ours = NULL;
6209
6210 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6211 ga_init2(&ga_env, (int)sizeof(char*), 20);
6212
6213 if (argvar->v_type == VAR_STRING)
6214 {
6215 cmd = argvar->vval.v_string;
6216 }
6217 else if (argvar->v_type == VAR_LIST)
6218 {
6219 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
6220 goto failed;
6221 cmd = ga_cmd.ga_data;
6222 }
6223 if (cmd == NULL || *cmd == NUL)
6224 {
6225 emsg(_(e_invarg));
6226 goto failed;
6227 }
6228
6229 term->tl_arg0_cmd = vim_strsave(cmd);
6230
6231 cmd_wchar = enc_to_utf16(cmd, NULL);
6232
6233 if (cmd_wchar != NULL)
6234 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006235 // Request by CreateProcessW
6236 breq = wcslen(cmd_wchar) + 1 + 1; // Addition of NUL by API
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006237 cmd_wchar_copy = ALLOC_MULT(WCHAR, breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006238 wcsncpy(cmd_wchar_copy, cmd_wchar, breq - 1);
6239 }
6240
6241 ga_clear(&ga_cmd);
6242 if (cmd_wchar == NULL)
6243 goto failed;
6244 if (opt->jo_cwd != NULL)
6245 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
6246
6247 win32_build_env(opt->jo_env, &ga_env, TRUE);
6248 env_wchar = ga_env.ga_data;
6249
6250 if (!CreatePipe(&i_theirs, &i_ours, NULL, 0))
6251 goto failed;
6252 if (!CreatePipe(&o_ours, &o_theirs, NULL, 0))
6253 goto failed;
6254
6255 consize.X = term->tl_cols;
6256 consize.Y = term->tl_rows;
6257 hr = pCreatePseudoConsole(consize, i_theirs, o_theirs, 0,
6258 &term->tl_conpty);
6259 if (FAILED(hr))
6260 goto failed;
6261
6262 term->tl_siex.StartupInfo.cb = sizeof(term->tl_siex);
6263
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006264 // Set up pipe inheritance safely: Vista or later.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006265 pInitializeProcThreadAttributeList(NULL, 1, 0, &breq);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006266 term->tl_siex.lpAttributeList = alloc(breq);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006267 if (!term->tl_siex.lpAttributeList)
6268 goto failed;
6269 if (!pInitializeProcThreadAttributeList(term->tl_siex.lpAttributeList, 1,
6270 0, &breq))
6271 goto failed;
6272 if (!pUpdateProcThreadAttribute(
6273 term->tl_siex.lpAttributeList, 0,
6274 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, term->tl_conpty,
6275 sizeof(HPCON), NULL, NULL))
6276 goto failed;
6277
6278 channel = add_channel();
6279 if (channel == NULL)
6280 goto failed;
6281
6282 job = job_alloc();
6283 if (job == NULL)
6284 goto failed;
6285 if (argvar->v_type == VAR_STRING)
6286 {
6287 int argc;
6288
6289 build_argv_from_string(cmd, &job->jv_argv, &argc);
6290 }
6291 else
6292 {
6293 int argc;
6294
6295 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6296 }
6297
6298 if (opt->jo_set & JO_IN_BUF)
6299 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6300
6301 if (!CreateProcessW(NULL, cmd_wchar_copy, NULL, NULL, FALSE,
6302 EXTENDED_STARTUPINFO_PRESENT | CREATE_UNICODE_ENVIRONMENT
6303 | CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP
6304 | CREATE_DEFAULT_ERROR_MODE,
6305 env_wchar, cwd_wchar,
6306 &term->tl_siex.StartupInfo, &proc_info))
6307 goto failed;
6308
6309 CloseHandle(i_theirs);
6310 CloseHandle(o_theirs);
6311
6312 channel_set_pipes(channel,
6313 (sock_T)i_ours,
6314 (sock_T)o_ours,
6315 (sock_T)o_ours);
6316
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006317 // Write lines with CR instead of NL.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006318 channel->ch_write_text_mode = TRUE;
6319
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006320 // Use to explicitly delete anonymous pipe handle.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006321 channel->ch_anonymous_pipe = TRUE;
6322
6323 jo = CreateJobObject(NULL, NULL);
6324 if (jo == NULL)
6325 goto failed;
6326
6327 if (!AssignProcessToJobObject(jo, proc_info.hProcess))
6328 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006329 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006330 CloseHandle(jo);
6331 jo = NULL;
6332 }
6333
6334 ResumeThread(proc_info.hThread);
6335 CloseHandle(proc_info.hThread);
6336
6337 vim_free(cmd_wchar);
6338 vim_free(cmd_wchar_copy);
6339 vim_free(cwd_wchar);
6340 vim_free(env_wchar);
6341
6342 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6343 goto failed;
6344
6345#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6346 if (opt->jo_set2 & JO2_ANSI_COLORS)
6347 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6348 else
6349 init_vterm_ansi_colors(term->tl_vterm);
6350#endif
6351
6352 channel_set_job(channel, job, opt);
6353 job_set_options(job, opt);
6354
6355 job->jv_channel = channel;
6356 job->jv_proc_info = proc_info;
6357 job->jv_job_object = jo;
6358 job->jv_status = JOB_STARTED;
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006359 job->jv_tty_type = vim_strsave((char_u *)"conpty");
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006360 ++job->jv_refcount;
6361 term->tl_job = job;
6362
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006363 // Redirecting stdout and stderr doesn't work at the job level. Instead
6364 // open the file here and handle it in. opt->jo_io was changed in
6365 // setup_job_options(), use the original flags here.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006366 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6367 {
6368 char_u *fname = opt->jo_io_name[PART_OUT];
6369
6370 ch_log(channel, "Opening output file %s", fname);
6371 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6372 if (term->tl_out_fd == NULL)
6373 semsg(_(e_notopen), fname);
6374 }
6375
6376 return OK;
6377
6378failed:
6379 ga_clear(&ga_cmd);
6380 ga_clear(&ga_env);
6381 vim_free(cmd_wchar);
6382 vim_free(cmd_wchar_copy);
6383 vim_free(cwd_wchar);
6384 if (channel != NULL)
6385 channel_clear(channel);
6386 if (job != NULL)
6387 {
6388 job->jv_channel = NULL;
6389 job_cleanup(job);
6390 }
6391 term->tl_job = NULL;
6392 if (jo != NULL)
6393 CloseHandle(jo);
6394
6395 if (term->tl_siex.lpAttributeList != NULL)
6396 {
6397 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6398 vim_free(term->tl_siex.lpAttributeList);
6399 }
6400 term->tl_siex.lpAttributeList = NULL;
6401 if (o_theirs != NULL)
6402 CloseHandle(o_theirs);
6403 if (o_ours != NULL)
6404 CloseHandle(o_ours);
6405 if (i_ours != NULL)
6406 CloseHandle(i_ours);
6407 if (i_theirs != NULL)
6408 CloseHandle(i_theirs);
6409 if (term->tl_conpty != NULL)
6410 pClosePseudoConsole(term->tl_conpty);
6411 term->tl_conpty = NULL;
6412 return FAIL;
6413}
6414
6415 static void
6416conpty_term_report_winsize(term_T *term, int rows, int cols)
6417{
6418 COORD consize;
6419
6420 consize.X = cols;
6421 consize.Y = rows;
6422 pResizePseudoConsole(term->tl_conpty, consize);
6423}
6424
Bram Moolenaar840d16f2019-09-10 21:27:18 +02006425 static void
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006426term_free_conpty(term_T *term)
6427{
6428 if (term->tl_siex.lpAttributeList != NULL)
6429 {
6430 pDeleteProcThreadAttributeList(term->tl_siex.lpAttributeList);
6431 vim_free(term->tl_siex.lpAttributeList);
6432 }
6433 term->tl_siex.lpAttributeList = NULL;
6434 if (term->tl_conpty != NULL)
6435 pClosePseudoConsole(term->tl_conpty);
6436 term->tl_conpty = NULL;
6437}
6438
6439 int
6440use_conpty(void)
6441{
6442 return has_conpty;
6443}
6444
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006445# ifndef PROTO
6446
6447#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
6448#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01006449#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006450
6451void* (*winpty_config_new)(UINT64, void*);
6452void* (*winpty_open)(void*, void*);
6453void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
6454BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
6455void (*winpty_config_set_mouse_mode)(void*, int);
6456void (*winpty_config_set_initial_size)(void*, int, int);
6457LPCWSTR (*winpty_conin_name)(void*);
6458LPCWSTR (*winpty_conout_name)(void*);
6459LPCWSTR (*winpty_conerr_name)(void*);
6460void (*winpty_free)(void*);
6461void (*winpty_config_free)(void*);
6462void (*winpty_spawn_config_free)(void*);
6463void (*winpty_error_free)(void*);
6464LPCWSTR (*winpty_error_msg)(void*);
6465BOOL (*winpty_set_size)(void*, int, int, void*);
6466HANDLE (*winpty_agent_process)(void*);
6467
6468#define WINPTY_DLL "winpty.dll"
6469
6470static HINSTANCE hWinPtyDLL = NULL;
6471# endif
6472
6473 static int
6474dyn_winpty_init(int verbose)
6475{
6476 int i;
6477 static struct
6478 {
6479 char *name;
6480 FARPROC *ptr;
6481 } winpty_entry[] =
6482 {
6483 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
6484 {"winpty_config_free", (FARPROC*)&winpty_config_free},
6485 {"winpty_config_new", (FARPROC*)&winpty_config_new},
6486 {"winpty_config_set_mouse_mode",
6487 (FARPROC*)&winpty_config_set_mouse_mode},
6488 {"winpty_config_set_initial_size",
6489 (FARPROC*)&winpty_config_set_initial_size},
6490 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
6491 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
6492 {"winpty_error_free", (FARPROC*)&winpty_error_free},
6493 {"winpty_free", (FARPROC*)&winpty_free},
6494 {"winpty_open", (FARPROC*)&winpty_open},
6495 {"winpty_spawn", (FARPROC*)&winpty_spawn},
6496 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
6497 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
6498 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
6499 {"winpty_set_size", (FARPROC*)&winpty_set_size},
6500 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
6501 {NULL, NULL}
6502 };
6503
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006504 // No need to initialize twice.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006505 if (hWinPtyDLL)
6506 return OK;
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006507 // Load winpty.dll, prefer using the 'winptydll' option, fall back to just
6508 // winpty.dll.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006509 if (*p_winptydll != NUL)
6510 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
6511 if (!hWinPtyDLL)
6512 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
6513 if (!hWinPtyDLL)
6514 {
6515 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006516 semsg(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006517 : (char_u *)WINPTY_DLL);
6518 return FAIL;
6519 }
6520 for (i = 0; winpty_entry[i].name != NULL
6521 && winpty_entry[i].ptr != NULL; ++i)
6522 {
6523 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
6524 winpty_entry[i].name)) == NULL)
6525 {
6526 if (verbose)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006527 semsg(_(e_loadfunc), winpty_entry[i].name);
Bram Moolenaar5acd9872019-02-16 13:35:13 +01006528 hWinPtyDLL = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006529 return FAIL;
6530 }
6531 }
6532
6533 return OK;
6534}
6535
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006536 static int
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006537winpty_term_and_job_init(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006538 term_T *term,
6539 typval_T *argvar,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006540 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006541 jobopt_T *opt,
6542 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006543{
6544 WCHAR *cmd_wchar = NULL;
6545 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006546 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006547 channel_T *channel = NULL;
6548 job_T *job = NULL;
6549 DWORD error;
6550 HANDLE jo = NULL;
6551 HANDLE child_process_handle;
6552 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01006553 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006554 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006555 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006556 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006557
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006558 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
6559 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006560
6561 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006562 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006563 cmd = argvar->vval.v_string;
6564 }
6565 else if (argvar->v_type == VAR_LIST)
6566 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006567 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006568 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006569 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006570 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006571 if (cmd == NULL || *cmd == NUL)
6572 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006573 emsg(_(e_invarg));
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006574 goto failed;
6575 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006576
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006577 term->tl_arg0_cmd = vim_strsave(cmd);
6578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006579 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006580 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006581 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006582 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006583 if (opt->jo_cwd != NULL)
6584 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006585
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01006586 win32_build_env(opt->jo_env, &ga_env, TRUE);
6587 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006588
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006589 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
6590 if (term->tl_winpty_config == NULL)
6591 goto failed;
6592
6593 winpty_config_set_mouse_mode(term->tl_winpty_config,
6594 WINPTY_MOUSE_MODE_FORCE);
6595 winpty_config_set_initial_size(term->tl_winpty_config,
6596 term->tl_cols, term->tl_rows);
6597 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
6598 if (term->tl_winpty == NULL)
6599 goto failed;
6600
6601 spawn_config = winpty_spawn_config_new(
6602 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
6603 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
6604 NULL,
6605 cmd_wchar,
6606 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01006607 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006608 &winpty_err);
6609 if (spawn_config == NULL)
6610 goto failed;
6611
6612 channel = add_channel();
6613 if (channel == NULL)
6614 goto failed;
6615
6616 job = job_alloc();
6617 if (job == NULL)
6618 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02006619 if (argvar->v_type == VAR_STRING)
6620 {
6621 int argc;
6622
6623 build_argv_from_string(cmd, &job->jv_argv, &argc);
6624 }
6625 else
6626 {
6627 int argc;
6628
6629 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
6630 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006631
6632 if (opt->jo_set & JO_IN_BUF)
6633 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
6634
6635 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
6636 &child_thread_handle, &error, &winpty_err))
6637 goto failed;
6638
6639 channel_set_pipes(channel,
6640 (sock_T)CreateFileW(
6641 winpty_conin_name(term->tl_winpty),
6642 GENERIC_WRITE, 0, NULL,
6643 OPEN_EXISTING, 0, NULL),
6644 (sock_T)CreateFileW(
6645 winpty_conout_name(term->tl_winpty),
6646 GENERIC_READ, 0, NULL,
6647 OPEN_EXISTING, 0, NULL),
6648 (sock_T)CreateFileW(
6649 winpty_conerr_name(term->tl_winpty),
6650 GENERIC_READ, 0, NULL,
6651 OPEN_EXISTING, 0, NULL));
6652
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006653 // Write lines with CR instead of NL.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006654 channel->ch_write_text_mode = TRUE;
6655
6656 jo = CreateJobObject(NULL, NULL);
6657 if (jo == NULL)
6658 goto failed;
6659
6660 if (!AssignProcessToJobObject(jo, child_process_handle))
6661 {
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006662 // Failed, switch the way to terminate process with TerminateProcess.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006663 CloseHandle(jo);
6664 jo = NULL;
6665 }
6666
6667 winpty_spawn_config_free(spawn_config);
6668 vim_free(cmd_wchar);
6669 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006670 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006671
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006672 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6673 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006674
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006675#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6676 if (opt->jo_set2 & JO2_ANSI_COLORS)
6677 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6678 else
6679 init_vterm_ansi_colors(term->tl_vterm);
6680#endif
6681
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006682 channel_set_job(channel, job, opt);
6683 job_set_options(job, opt);
6684
6685 job->jv_channel = channel;
6686 job->jv_proc_info.hProcess = child_process_handle;
6687 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
6688 job->jv_job_object = jo;
6689 job->jv_status = JOB_STARTED;
6690 job->jv_tty_in = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006691 (short_u *)winpty_conin_name(term->tl_winpty), NULL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006692 job->jv_tty_out = utf16_to_enc(
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006693 (short_u *)winpty_conout_name(term->tl_winpty), NULL);
Bram Moolenaar18442cb2019-02-13 21:22:12 +01006694 job->jv_tty_type = vim_strsave((char_u *)"winpty");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006695 ++job->jv_refcount;
6696 term->tl_job = job;
6697
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006698 // Redirecting stdout and stderr doesn't work at the job level. Instead
6699 // open the file here and handle it in. opt->jo_io was changed in
6700 // setup_job_options(), use the original flags here.
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006701 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
6702 {
6703 char_u *fname = opt->jo_io_name[PART_OUT];
6704
6705 ch_log(channel, "Opening output file %s", fname);
6706 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
6707 if (term->tl_out_fd == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006708 semsg(_(e_notopen), fname);
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006709 }
6710
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006711 return OK;
6712
6713failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01006714 ga_clear(&ga_cmd);
6715 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006716 vim_free(cmd_wchar);
6717 vim_free(cwd_wchar);
6718 if (spawn_config != NULL)
6719 winpty_spawn_config_free(spawn_config);
6720 if (channel != NULL)
6721 channel_clear(channel);
6722 if (job != NULL)
6723 {
6724 job->jv_channel = NULL;
6725 job_cleanup(job);
6726 }
6727 term->tl_job = NULL;
6728 if (jo != NULL)
6729 CloseHandle(jo);
6730 if (term->tl_winpty != NULL)
6731 winpty_free(term->tl_winpty);
6732 term->tl_winpty = NULL;
6733 if (term->tl_winpty_config != NULL)
6734 winpty_config_free(term->tl_winpty_config);
6735 term->tl_winpty_config = NULL;
6736 if (winpty_err != NULL)
6737 {
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006738 char *msg = (char *)utf16_to_enc(
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006739 (short_u *)winpty_error_msg(winpty_err), NULL);
6740
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006741 emsg(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006742 winpty_error_free(winpty_err);
6743 }
6744 return FAIL;
6745}
6746
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006747/*
6748 * Create a new terminal of "rows" by "cols" cells.
6749 * Store a reference in "term".
6750 * Return OK or FAIL.
6751 */
6752 static int
6753term_and_job_init(
6754 term_T *term,
6755 typval_T *argvar,
Bram Moolenaar197c6b72019-11-03 23:37:12 +01006756 char **argv,
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006757 jobopt_T *opt,
6758 jobopt_T *orig_opt)
6759{
6760 int use_winpty = FALSE;
6761 int use_conpty = FALSE;
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006762 int tty_type = *p_twt;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006763
6764 has_winpty = dyn_winpty_init(FALSE) != FAIL ? TRUE : FALSE;
6765 has_conpty = dyn_conpty_init(FALSE) != FAIL ? TRUE : FALSE;
6766
6767 if (!has_winpty && !has_conpty)
6768 // If neither is available give the errors for winpty, since when
6769 // conpty is not available it can't be installed either.
6770 return dyn_winpty_init(TRUE);
6771
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006772 if (opt->jo_tty_type != NUL)
6773 tty_type = opt->jo_tty_type;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006774
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006775 if (tty_type == NUL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006776 {
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01006777 if (has_conpty && (is_conpty_stable() || !has_winpty))
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006778 use_conpty = TRUE;
6779 else if (has_winpty)
6780 use_winpty = TRUE;
6781 // else: error
6782 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006783 else if (tty_type == 'w') // winpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006784 {
6785 if (has_winpty)
6786 use_winpty = TRUE;
6787 }
Bram Moolenaarc6ddce32019-02-08 12:47:03 +01006788 else if (tty_type == 'c') // conpty
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006789 {
6790 if (has_conpty)
6791 use_conpty = TRUE;
6792 else
6793 return dyn_conpty_init(TRUE);
6794 }
6795
6796 if (use_conpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006797 return conpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006798
6799 if (use_winpty)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006800 return winpty_term_and_job_init(term, argvar, argv, opt, orig_opt);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006801
6802 // error
6803 return dyn_winpty_init(TRUE);
6804}
6805
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006806 static int
6807create_pty_only(term_T *term, jobopt_T *options)
6808{
6809 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
6810 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
6811 char in_name[80], out_name[80];
6812 channel_T *channel = NULL;
6813
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006814 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6815 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006816
6817 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
6818 GetCurrentProcessId(),
6819 curbuf->b_fnum);
6820 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
6821 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6822 PIPE_UNLIMITED_INSTANCES,
6823 0, 0, NMPWAIT_NOWAIT, NULL);
6824 if (hPipeIn == INVALID_HANDLE_VALUE)
6825 goto failed;
6826
6827 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
6828 GetCurrentProcessId(),
6829 curbuf->b_fnum);
6830 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
6831 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
6832 PIPE_UNLIMITED_INSTANCES,
6833 0, 0, 0, NULL);
6834 if (hPipeOut == INVALID_HANDLE_VALUE)
6835 goto failed;
6836
6837 ConnectNamedPipe(hPipeIn, NULL);
6838 ConnectNamedPipe(hPipeOut, NULL);
6839
6840 term->tl_job = job_alloc();
6841 if (term->tl_job == NULL)
6842 goto failed;
6843 ++term->tl_job->jv_refcount;
6844
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006845 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006846 term->tl_job->jv_status = JOB_FINISHED;
6847
6848 channel = add_channel();
6849 if (channel == NULL)
6850 goto failed;
6851 term->tl_job->jv_channel = channel;
6852 channel->ch_keep_open = TRUE;
6853 channel->ch_named_pipe = TRUE;
6854
6855 channel_set_pipes(channel,
6856 (sock_T)hPipeIn,
6857 (sock_T)hPipeOut,
6858 (sock_T)hPipeOut);
6859 channel_set_job(channel, term->tl_job, options);
6860 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
6861 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
6862
6863 return OK;
6864
6865failed:
6866 if (hPipeIn != NULL)
6867 CloseHandle(hPipeIn);
6868 if (hPipeOut != NULL)
6869 CloseHandle(hPipeOut);
6870 return FAIL;
6871}
6872
6873/*
6874 * Free the terminal emulator part of "term".
6875 */
6876 static void
6877term_free_vterm(term_T *term)
6878{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006879 term_free_conpty(term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006880 if (term->tl_winpty != NULL)
6881 winpty_free(term->tl_winpty);
6882 term->tl_winpty = NULL;
6883 if (term->tl_winpty_config != NULL)
6884 winpty_config_free(term->tl_winpty_config);
6885 term->tl_winpty_config = NULL;
6886 if (term->tl_vterm != NULL)
6887 vterm_free(term->tl_vterm);
6888 term->tl_vterm = NULL;
6889}
6890
6891/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006892 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006893 */
6894 static void
6895term_report_winsize(term_T *term, int rows, int cols)
6896{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006897 if (term->tl_conpty)
6898 conpty_term_report_winsize(term, rows, cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006899 if (term->tl_winpty)
6900 winpty_set_size(term->tl_winpty, cols, rows, NULL);
6901}
6902
6903 int
6904terminal_enabled(void)
6905{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006906 return dyn_winpty_init(FALSE) == OK || dyn_conpty_init(FALSE) == OK;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006907}
6908
6909# else
6910
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006911///////////////////////////////////////
6912// 3. Unix-like implementation.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006913
6914/*
6915 * Create a new terminal of "rows" by "cols" cells.
6916 * Start job for "cmd".
6917 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01006918 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006919 * Return OK or FAIL.
6920 */
6921 static int
6922term_and_job_init(
6923 term_T *term,
6924 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01006925 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02006926 jobopt_T *opt,
6927 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006928{
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01006929 term->tl_arg0_cmd = NULL;
6930
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006931 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6932 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006933
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02006934#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
6935 if (opt->jo_set2 & JO2_ANSI_COLORS)
6936 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
6937 else
6938 init_vterm_ansi_colors(term->tl_vterm);
6939#endif
6940
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006941 // This may change a string in "argvar".
Bram Moolenaar21109272020-01-30 16:27:20 +01006942 term->tl_job = job_start(argvar, argv, opt, &term->tl_job);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006943 if (term->tl_job != NULL)
6944 ++term->tl_job->jv_refcount;
6945
6946 return term->tl_job != NULL
6947 && term->tl_job->jv_channel != NULL
6948 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
6949}
6950
6951 static int
6952create_pty_only(term_T *term, jobopt_T *opt)
6953{
Bram Moolenaarcd929f72018-12-24 21:38:45 +01006954 if (create_vterm(term, term->tl_rows, term->tl_cols) == FAIL)
6955 return FAIL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006956
6957 term->tl_job = job_alloc();
6958 if (term->tl_job == NULL)
6959 return FAIL;
6960 ++term->tl_job->jv_refcount;
6961
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006962 // behave like the job is already finished
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006963 term->tl_job->jv_status = JOB_FINISHED;
6964
6965 return mch_create_pty_channel(term->tl_job, opt);
6966}
6967
6968/*
6969 * Free the terminal emulator part of "term".
6970 */
6971 static void
6972term_free_vterm(term_T *term)
6973{
6974 if (term->tl_vterm != NULL)
6975 vterm_free(term->tl_vterm);
6976 term->tl_vterm = NULL;
6977}
6978
6979/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02006980 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006981 */
6982 static void
6983term_report_winsize(term_T *term, int rows, int cols)
6984{
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01006985 // Use an ioctl() to report the new window size to the job.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006986 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
6987 {
6988 int fd = -1;
6989 int part;
6990
6991 for (part = PART_OUT; part < PART_COUNT; ++part)
6992 {
6993 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
Bram Moolenaar1ecc5e42019-01-26 15:12:55 +01006994 if (mch_isatty(fd))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02006995 break;
6996 }
6997 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
6998 mch_signal_job(term->tl_job, (char_u *)"winch");
6999 }
7000}
7001
7002# endif
7003
Bram Moolenaar0d6f5d92019-12-05 21:33:15 +01007004#endif // FEAT_TERMINAL