blob: 282f98102658f3ada5d2f0047e96080bb43d71c3 [file] [log] [blame]
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * Terminal window support, see ":help :terminal".
12 *
13 * There are three parts:
14 * 1. Generic code for all systems.
15 * Uses libvterm for the terminal emulator.
16 * 2. The MS-Windows implementation.
17 * Uses winpty.
18 * 3. The Unix-like implementation.
19 * Uses pseudo-tty's (pty's).
20 *
21 * For each terminal one VTerm is constructed. This uses libvterm. A copy of
22 * this library is in the libvterm directory.
23 *
24 * When a terminal window is opened, a job is started that will be connected to
25 * the terminal emulator.
26 *
27 * If the terminal window has keyboard focus, typed keys are converted to the
28 * terminal encoding and writing to the job over a channel.
29 *
30 * If the job produces output, it is written to the terminal emulator. The
31 * terminal emulator invokes callbacks when its screen content changes. The
32 * line range is stored in tl_dirty_row_start and tl_dirty_row_end. Once in a
33 * while, if the terminal window is visible, the screen contents is drawn.
34 *
35 * When the job ends the text is put in a buffer. Redrawing then happens from
36 * that buffer, attributes come from the scrollback buffer tl_scrollback.
37 * When the buffer is changed it is turned into a normal buffer, the attributes
38 * in tl_scrollback are no longer used.
39 *
40 * TODO:
Bram Moolenaara10ae5e2018-05-11 20:48:29 +020041 * - Win32: Termdebug doesn't work, because gdb does not support mi2. This
42 * plugin: https://github.com/cpiger/NeoDebug runs gdb as a job, redirecting
43 * input and output. Command I/O is in gdb window.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020044 * - Win32: Redirecting input does not work, half of Test_terminal_redir_file()
Bram Moolenaar802bfb12018-04-15 17:28:13 +020045 * is disabled.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020046 * - Win32: Redirecting output works but includes escape sequences.
47 * - Win32: Make terminal used for :!cmd in the GUI work better. Allow for
48 * redirection.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +020049 * - When the job only outputs lines, we could handle resizing the terminal
50 * better: store lines separated by line breaks, instead of screen lines,
51 * then when the window is resized redraw those lines.
Bram Moolenaarf25329c2018-05-06 21:49:32 +020052 * - Redrawing is slow with Athena and Motif. (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020053 * - For the GUI fill termios with default values, perhaps like pangoterm:
54 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar802bfb12018-04-15 17:28:13 +020055 * - When 'encoding' is not utf-8, or the job is using another encoding, setup
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * conversions.
Bram Moolenaar498c2562018-04-15 23:45:15 +020057 * - Termdebug does not work when Vim build with mzscheme: gdb hangs just after
58 * "run". Everything else works, including communication channel. Not
59 * initializing mzscheme avoid the problem, thus it's not some #ifdef.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 */
61
62#include "vim.h"
63
64#if defined(FEAT_TERMINAL) || defined(PROTO)
65
66#ifndef MIN
67# define MIN(x,y) ((x) < (y) ? (x) : (y))
68#endif
69#ifndef MAX
70# define MAX(x,y) ((x) > (y) ? (x) : (y))
71#endif
72
73#include "libvterm/include/vterm.h"
74
75/* This is VTermScreenCell without the characters, thus much smaller. */
76typedef struct {
77 VTermScreenCellAttrs attrs;
78 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010079 VTermColor fg;
80 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020081} cellattr_T;
82
83typedef struct sb_line_S {
84 int sb_cols; /* can differ per line */
85 cellattr_T *sb_cells; /* allocated */
86 cellattr_T sb_fill_attr; /* for short line */
87} sb_line_T;
88
89/* typedef term_T in structs.h */
90struct terminal_S {
91 term_T *tl_next;
92
93 VTerm *tl_vterm;
94 job_T *tl_job;
95 buf_T *tl_buffer;
Bram Moolenaar13568252018-03-16 20:46:58 +010096#if defined(FEAT_GUI)
97 int tl_system; /* when non-zero used for :!cmd output */
98 int tl_toprow; /* row with first line of system terminal */
99#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200100
101 /* Set when setting the size of a vterm, reset after redrawing. */
102 int tl_vterm_size_changed;
103
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200104 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
105 int tl_channel_closed;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +0200106 int tl_channel_recently_closed; // still need to handle tl_finish
107
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100108 int tl_finish;
109#define TL_FINISH_UNSET NUL
110#define TL_FINISH_CLOSE 'c' /* ++close or :terminal without argument */
111#define TL_FINISH_NOCLOSE 'n' /* ++noclose */
112#define TL_FINISH_OPEN 'o' /* ++open */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200113 char_u *tl_opencmd;
114 char_u *tl_eof_chars;
115
116#ifdef WIN3264
117 void *tl_winpty_config;
118 void *tl_winpty;
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200119
120 FILE *tl_out_fd;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200121#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100122#if defined(FEAT_SESSION)
123 char_u *tl_command;
124#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100125 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200126
127 /* last known vterm size */
128 int tl_rows;
129 int tl_cols;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
131 char_u *tl_title; /* NULL or allocated */
132 char_u *tl_status_text; /* NULL or allocated */
133
134 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200135 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200136 int tl_dirty_row_end; /* row below last one to update */
Bram Moolenaar56bc8e22018-05-10 18:05:56 +0200137 int tl_dirty_snapshot; /* text updated after making snapshot */
138#ifdef FEAT_TIMERS
139 int tl_timer_set;
140 proftime_T tl_timer_due;
141#endif
Bram Moolenaar6eddadf2018-05-06 16:40:16 +0200142 int tl_postponed_scroll; /* to be scrolled up */
143
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200144 garray_T tl_scrollback;
145 int tl_scrollback_scrolled;
146 cellattr_T tl_default_color;
147
Bram Moolenaard96ff162018-02-18 22:13:29 +0100148 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
149 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
150
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 VTermPos tl_cursor_pos;
152 int tl_cursor_visible;
153 int tl_cursor_blink;
154 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
155 char_u *tl_cursor_color; /* NULL or allocated */
156
157 int tl_using_altscreen;
158};
159
160#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
161#define TMODE_LOOP 2 /* CTRL-W N used */
162
163/*
164 * List of all active terminals.
165 */
166static term_T *first_term = NULL;
167
168/* Terminal active in terminal_loop(). */
169static term_T *in_terminal_loop = NULL;
170
171#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
172#define KEY_BUF_LEN 200
173
174/*
175 * Functions with separate implementation for MS-Windows and Unix-like systems.
176 */
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200177static 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 +0200178static int create_pty_only(term_T *term, jobopt_T *opt);
179static void term_report_winsize(term_T *term, int rows, int cols);
180static void term_free_vterm(term_T *term);
Bram Moolenaar13568252018-03-16 20:46:58 +0100181#ifdef FEAT_GUI
182static void update_system_term(term_T *term);
183#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200184
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100185/* The character that we know (or assume) that the terminal expects for the
186 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200187static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200188
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100189/* "Terminal" highlight group colors. */
190static int term_default_cterm_fg = -1;
191static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200192
Bram Moolenaard317b382018-02-08 22:33:31 +0100193/* Store the last set and the desired cursor properties, so that we only update
194 * them when needed. Doing it unnecessary may result in flicker. */
195static char_u *last_set_cursor_color = (char_u *)"";
196static char_u *desired_cursor_color = (char_u *)"";
197static int last_set_cursor_shape = -1;
198static int desired_cursor_shape = -1;
199static int last_set_cursor_blink = -1;
200static int desired_cursor_blink = -1;
201
202
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200203/**************************************
204 * 1. Generic code for all systems.
205 */
206
207/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200208 * Parse 'termwinsize' and set "rows" and "cols" for the terminal size in the
Bram Moolenaar498c2562018-04-15 23:45:15 +0200209 * current window.
210 * Sets "rows" and/or "cols" to zero when it should follow the window size.
211 * Return TRUE if the size is the minimum size: "24*80".
212 */
213 static int
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200214parse_termwinsize(win_T *wp, int *rows, int *cols)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200215{
216 int minsize = FALSE;
217
218 *rows = 0;
219 *cols = 0;
220
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200221 if (*wp->w_p_tws != NUL)
Bram Moolenaar498c2562018-04-15 23:45:15 +0200222 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200223 char_u *p = vim_strchr(wp->w_p_tws, 'x');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200224
225 /* Syntax of value was already checked when it's set. */
226 if (p == NULL)
227 {
228 minsize = TRUE;
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200229 p = vim_strchr(wp->w_p_tws, '*');
Bram Moolenaar498c2562018-04-15 23:45:15 +0200230 }
Bram Moolenaar6d150f72018-04-21 20:03:20 +0200231 *rows = atoi((char *)wp->w_p_tws);
Bram Moolenaar498c2562018-04-15 23:45:15 +0200232 *cols = atoi((char *)p + 1);
233 }
234 return minsize;
235}
236
237/*
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200238 * Determine the terminal size from 'termwinsize' and the current window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200239 */
240 static void
241set_term_and_win_size(term_T *term)
242{
Bram Moolenaar13568252018-03-16 20:46:58 +0100243#ifdef FEAT_GUI
244 if (term->tl_system)
245 {
246 /* Use the whole screen for the system command. However, it will start
247 * at the command line and scroll up as needed, using tl_toprow. */
248 term->tl_rows = Rows;
249 term->tl_cols = Columns;
Bram Moolenaar07b46af2018-04-10 14:56:18 +0200250 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100251 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100252#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +0200253 if (parse_termwinsize(curwin, &term->tl_rows, &term->tl_cols))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200254 {
Bram Moolenaar498c2562018-04-15 23:45:15 +0200255 if (term->tl_rows != 0)
256 term->tl_rows = MAX(term->tl_rows, curwin->w_height);
257 if (term->tl_cols != 0)
258 term->tl_cols = MAX(term->tl_cols, curwin->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200259 }
260 if (term->tl_rows == 0)
261 term->tl_rows = curwin->w_height;
262 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200263 win_setheight_win(term->tl_rows, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200264 if (term->tl_cols == 0)
265 term->tl_cols = curwin->w_width;
266 else
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200267 win_setwidth_win(term->tl_cols, curwin);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200268}
269
270/*
271 * Initialize job options for a terminal job.
272 * Caller may overrule some of them.
273 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100274 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200275init_job_options(jobopt_T *opt)
276{
277 clear_job_options(opt);
278
279 opt->jo_mode = MODE_RAW;
280 opt->jo_out_mode = MODE_RAW;
281 opt->jo_err_mode = MODE_RAW;
282 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
283}
284
285/*
286 * Set job options mandatory for a terminal job.
287 */
288 static void
289setup_job_options(jobopt_T *opt, int rows, int cols)
290{
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200291#ifndef WIN3264
292 /* Win32: Redirecting the job output won't work, thus always connect stdout
293 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200294 if (!(opt->jo_set & JO_OUT_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200295#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200296 {
297 /* Connect stdout to the terminal. */
298 opt->jo_io[PART_OUT] = JIO_BUFFER;
299 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
300 opt->jo_modifiable[PART_OUT] = 0;
301 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
302 }
303
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200304#ifndef WIN3264
305 /* Win32: Redirecting the job output won't work, thus always connect stderr
306 * here. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200307 if (!(opt->jo_set & JO_ERR_IO))
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200308#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200309 {
310 /* Connect stderr to the terminal. */
311 opt->jo_io[PART_ERR] = JIO_BUFFER;
312 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
313 opt->jo_modifiable[PART_ERR] = 0;
314 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
315 }
316
317 opt->jo_pty = TRUE;
318 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
319 opt->jo_term_rows = rows;
320 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
321 opt->jo_term_cols = cols;
322}
323
324/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100325 * Close a terminal buffer (and its window). Used when creating the terminal
326 * fails.
327 */
328 static void
329term_close_buffer(buf_T *buf, buf_T *old_curbuf)
330{
331 free_terminal(buf);
332 if (old_curbuf != NULL)
333 {
334 --curbuf->b_nwindows;
335 curbuf = old_curbuf;
336 curwin->w_buffer = curbuf;
337 ++curbuf->b_nwindows;
338 }
339
340 /* Wiping out the buffer will also close the window and call
341 * free_terminal(). */
342 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
343}
344
345/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200346 * Start a terminal window and return its buffer.
Bram Moolenaar13568252018-03-16 20:46:58 +0100347 * Use either "argvar" or "argv", the other must be NULL.
348 * When "flags" has TERM_START_NOJOB only create the buffer, b_term and open
349 * the window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200350 * Returns NULL when failed.
351 */
Bram Moolenaar13568252018-03-16 20:46:58 +0100352 buf_T *
353term_start(
354 typval_T *argvar,
355 char **argv,
356 jobopt_T *opt,
357 int flags)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200358{
359 exarg_T split_ea;
360 win_T *old_curwin = curwin;
361 term_T *term;
362 buf_T *old_curbuf = NULL;
363 int res;
364 buf_T *newbuf;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100365 int vertical = opt->jo_vertical || (cmdmod.split & WSP_VERT);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200366 jobopt_T orig_opt; // only partly filled
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200367
368 if (check_restricted() || check_secure())
369 return NULL;
370
371 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
372 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
373 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
374 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
375 {
376 EMSG(_(e_invarg));
377 return NULL;
378 }
379
380 term = (term_T *)alloc_clear(sizeof(term_T));
381 if (term == NULL)
382 return NULL;
383 term->tl_dirty_row_end = MAX_ROW;
384 term->tl_cursor_visible = TRUE;
385 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
386 term->tl_finish = opt->jo_term_finish;
Bram Moolenaar13568252018-03-16 20:46:58 +0100387#ifdef FEAT_GUI
388 term->tl_system = (flags & TERM_START_SYSTEM);
389#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200390 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
391
392 vim_memset(&split_ea, 0, sizeof(split_ea));
393 if (opt->jo_curwin)
394 {
395 /* Create a new buffer in the current window. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100396 if (!can_abandon(curbuf, flags & TERM_START_FORCEIT))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200397 {
398 no_write_message();
399 vim_free(term);
400 return NULL;
401 }
402 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
Bram Moolenaar13568252018-03-16 20:46:58 +0100403 ECMD_HIDE
404 + ((flags & TERM_START_FORCEIT) ? ECMD_FORCEIT : 0),
405 curwin) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200406 {
407 vim_free(term);
408 return NULL;
409 }
410 }
Bram Moolenaar13568252018-03-16 20:46:58 +0100411 else if (opt->jo_hidden || (flags & TERM_START_SYSTEM))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200412 {
413 buf_T *buf;
414
415 /* Create a new buffer without a window. Make it the current buffer for
416 * a moment to be able to do the initialisations. */
417 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
418 BLN_NEW | BLN_LISTED);
419 if (buf == NULL || ml_open(buf) == FAIL)
420 {
421 vim_free(term);
422 return NULL;
423 }
424 old_curbuf = curbuf;
425 --curbuf->b_nwindows;
426 curbuf = buf;
427 curwin->w_buffer = buf;
428 ++curbuf->b_nwindows;
429 }
430 else
431 {
432 /* Open a new window or tab. */
433 split_ea.cmdidx = CMD_new;
434 split_ea.cmd = (char_u *)"new";
435 split_ea.arg = (char_u *)"";
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100436 if (opt->jo_term_rows > 0 && !vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200437 {
438 split_ea.line2 = opt->jo_term_rows;
439 split_ea.addr_count = 1;
440 }
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100441 if (opt->jo_term_cols > 0 && vertical)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200442 {
443 split_ea.line2 = opt->jo_term_cols;
444 split_ea.addr_count = 1;
445 }
446
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100447 if (vertical)
448 cmdmod.split |= WSP_VERT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200449 ex_splitview(&split_ea);
450 if (curwin == old_curwin)
451 {
452 /* split failed */
453 vim_free(term);
454 return NULL;
455 }
456 }
457 term->tl_buffer = curbuf;
458 curbuf->b_term = term;
459
460 if (!opt->jo_hidden)
461 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100462 /* Only one size was taken care of with :new, do the other one. With
463 * "curwin" both need to be done. */
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100464 if (opt->jo_term_rows > 0 && (opt->jo_curwin || vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200465 win_setheight(opt->jo_term_rows);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +0100466 if (opt->jo_term_cols > 0 && (opt->jo_curwin || !vertical))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200467 win_setwidth(opt->jo_term_cols);
468 }
469
470 /* Link the new terminal in the list of active terminals. */
471 term->tl_next = first_term;
472 first_term = term;
473
474 if (opt->jo_term_name != NULL)
475 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
Bram Moolenaar13568252018-03-16 20:46:58 +0100476 else if (argv != NULL)
477 curbuf->b_ffname = vim_strsave((char_u *)"!system");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200478 else
479 {
480 int i;
481 size_t len;
482 char_u *cmd, *p;
483
484 if (argvar->v_type == VAR_STRING)
485 {
486 cmd = argvar->vval.v_string;
487 if (cmd == NULL)
488 cmd = (char_u *)"";
489 else if (STRCMP(cmd, "NONE") == 0)
490 cmd = (char_u *)"pty";
491 }
492 else if (argvar->v_type != VAR_LIST
493 || argvar->vval.v_list == NULL
494 || argvar->vval.v_list->lv_len < 1
495 || (cmd = get_tv_string_chk(
496 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
497 cmd = (char_u*)"";
498
499 len = STRLEN(cmd) + 10;
500 p = alloc((int)len);
501
502 for (i = 0; p != NULL; ++i)
503 {
504 /* Prepend a ! to the command name to avoid the buffer name equals
505 * the executable, otherwise ":w!" would overwrite it. */
506 if (i == 0)
507 vim_snprintf((char *)p, len, "!%s", cmd);
508 else
509 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
510 if (buflist_findname(p) == NULL)
511 {
512 vim_free(curbuf->b_ffname);
513 curbuf->b_ffname = p;
514 break;
515 }
516 }
517 }
518 curbuf->b_fname = curbuf->b_ffname;
519
520 if (opt->jo_term_opencmd != NULL)
521 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
522
523 if (opt->jo_eof_chars != NULL)
524 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
525
526 set_string_option_direct((char_u *)"buftype", -1,
527 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
528
529 /* Mark the buffer as not modifiable. It can only be made modifiable after
530 * the job finished. */
531 curbuf->b_p_ma = FALSE;
532
533 set_term_and_win_size(term);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200534#ifdef WIN3264
535 mch_memmove(orig_opt.jo_io, opt->jo_io, sizeof(orig_opt.jo_io));
536#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200537 setup_job_options(opt, term->tl_rows, term->tl_cols);
538
Bram Moolenaar13568252018-03-16 20:46:58 +0100539 if (flags & TERM_START_NOJOB)
Bram Moolenaard96ff162018-02-18 22:13:29 +0100540 return curbuf;
541
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100542#if defined(FEAT_SESSION)
543 /* Remember the command for the session file. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100544 if (opt->jo_term_norestore || argv != NULL)
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100545 {
546 term->tl_command = vim_strsave((char_u *)"NONE");
547 }
548 else if (argvar->v_type == VAR_STRING)
549 {
550 char_u *cmd = argvar->vval.v_string;
551
552 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
553 term->tl_command = vim_strsave(cmd);
554 }
555 else if (argvar->v_type == VAR_LIST
556 && argvar->vval.v_list != NULL
557 && argvar->vval.v_list->lv_len > 0)
558 {
559 garray_T ga;
560 listitem_T *item;
561
562 ga_init2(&ga, 1, 100);
563 for (item = argvar->vval.v_list->lv_first;
564 item != NULL; item = item->li_next)
565 {
566 char_u *s = get_tv_string_chk(&item->li_tv);
567 char_u *p;
568
569 if (s == NULL)
570 break;
571 p = vim_strsave_fnameescape(s, FALSE);
572 if (p == NULL)
573 break;
574 ga_concat(&ga, p);
575 vim_free(p);
576 ga_append(&ga, ' ');
577 }
578 if (item == NULL)
579 {
580 ga_append(&ga, NUL);
581 term->tl_command = ga.ga_data;
582 }
583 else
584 ga_clear(&ga);
585 }
586#endif
587
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100588 if (opt->jo_term_kill != NULL)
589 {
590 char_u *p = skiptowhite(opt->jo_term_kill);
591
592 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
593 }
594
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200595 /* System dependent: setup the vterm and maybe start the job in it. */
Bram Moolenaar13568252018-03-16 20:46:58 +0100596 if (argv == NULL
597 && argvar->v_type == VAR_STRING
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200598 && argvar->vval.v_string != NULL
599 && STRCMP(argvar->vval.v_string, "NONE") == 0)
600 res = create_pty_only(term, opt);
601 else
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200602 res = term_and_job_init(term, argvar, argv, opt, &orig_opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200603
604 newbuf = curbuf;
605 if (res == OK)
606 {
607 /* Get and remember the size we ended up with. Update the pty. */
608 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
609 term_report_winsize(term, term->tl_rows, term->tl_cols);
Bram Moolenaar13568252018-03-16 20:46:58 +0100610#ifdef FEAT_GUI
611 if (term->tl_system)
612 {
613 /* display first line below typed command */
614 term->tl_toprow = msg_row + 1;
615 term->tl_dirty_row_end = 0;
616 }
617#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200618
619 /* Make sure we don't get stuck on sending keys to the job, it leads to
620 * a deadlock if the job is waiting for Vim to read. */
621 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
622
Bram Moolenaar606cb8b2018-05-03 20:40:20 +0200623 if (old_curbuf != NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200624 {
625 --curbuf->b_nwindows;
626 curbuf = old_curbuf;
627 curwin->w_buffer = curbuf;
628 ++curbuf->b_nwindows;
629 }
630 }
631 else
632 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100633 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200634 return NULL;
635 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100636
Bram Moolenaar13568252018-03-16 20:46:58 +0100637 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, newbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200638 return newbuf;
639}
640
641/*
642 * ":terminal": open a terminal window and execute a job in it.
643 */
644 void
645ex_terminal(exarg_T *eap)
646{
647 typval_T argvar[2];
648 jobopt_T opt;
649 char_u *cmd;
650 char_u *tofree = NULL;
651
652 init_job_options(&opt);
653
654 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100655 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200656 {
657 char_u *p, *ep;
658
659 cmd += 2;
660 p = skiptowhite(cmd);
661 ep = vim_strchr(cmd, '=');
662 if (ep != NULL && ep < p)
663 p = ep;
664
665 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
666 opt.jo_term_finish = 'c';
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100667 else if ((int)(p - cmd) == 7 && STRNICMP(cmd, "noclose", 7) == 0)
668 opt.jo_term_finish = 'n';
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200669 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
670 opt.jo_term_finish = 'o';
671 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
672 opt.jo_curwin = 1;
673 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
674 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100675 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
676 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100677 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
678 && ep != NULL)
679 {
680 opt.jo_set2 |= JO2_TERM_KILL;
681 opt.jo_term_kill = ep + 1;
682 p = skiptowhite(cmd);
683 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200684 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
685 && ep != NULL && isdigit(ep[1]))
686 {
687 opt.jo_set2 |= JO2_TERM_ROWS;
688 opt.jo_term_rows = atoi((char *)ep + 1);
689 p = skiptowhite(cmd);
690 }
691 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
692 && ep != NULL && isdigit(ep[1]))
693 {
694 opt.jo_set2 |= JO2_TERM_COLS;
695 opt.jo_term_cols = atoi((char *)ep + 1);
696 p = skiptowhite(cmd);
697 }
698 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
699 && ep != NULL)
700 {
701 char_u *buf = NULL;
702 char_u *keys;
703
704 p = skiptowhite(cmd);
705 *p = NUL;
706 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
707 opt.jo_set2 |= JO2_EOF_CHARS;
708 opt.jo_eof_chars = vim_strsave(keys);
709 vim_free(buf);
710 *p = ' ';
711 }
712 else
713 {
714 if (*p)
715 *p = NUL;
716 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100717 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200718 }
719 cmd = skipwhite(p);
720 }
721 if (*cmd == NUL)
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100722 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200723 /* Make a copy of 'shell', an autocommand may change the option. */
724 tofree = cmd = vim_strsave(p_sh);
725
Bram Moolenaar1dd98332018-03-16 22:54:53 +0100726 /* default to close when the shell exits */
727 if (opt.jo_term_finish == NUL)
728 opt.jo_term_finish = 'c';
729 }
730
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200731 if (eap->addr_count > 0)
732 {
733 /* Write lines from current buffer to the job. */
734 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
735 opt.jo_io[PART_IN] = JIO_BUFFER;
736 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
737 opt.jo_in_top = eap->line1;
738 opt.jo_in_bot = eap->line2;
739 }
740
741 argvar[0].v_type = VAR_STRING;
742 argvar[0].vval.v_string = cmd;
743 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaar13568252018-03-16 20:46:58 +0100744 term_start(argvar, NULL, &opt, eap->forceit ? TERM_START_FORCEIT : 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100746
747theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200748 vim_free(opt.jo_eof_chars);
749}
750
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100751#if defined(FEAT_SESSION) || defined(PROTO)
752/*
753 * Write a :terminal command to the session file to restore the terminal in
754 * window "wp".
755 * Return FAIL if writing fails.
756 */
757 int
758term_write_session(FILE *fd, win_T *wp)
759{
760 term_T *term = wp->w_buffer->b_term;
761
762 /* Create the terminal and run the command. This is not without
763 * risk, but let's assume the user only creates a session when this
764 * will be OK. */
765 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
766 term->tl_cols, term->tl_rows) < 0)
767 return FAIL;
768 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
769 return FAIL;
770
771 return put_eol(fd);
772}
773
774/*
775 * Return TRUE if "buf" has a terminal that should be restored.
776 */
777 int
778term_should_restore(buf_T *buf)
779{
780 term_T *term = buf->b_term;
781
782 return term != NULL && (term->tl_command == NULL
783 || STRCMP(term->tl_command, "NONE") != 0);
784}
785#endif
786
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200787/*
788 * Free the scrollback buffer for "term".
789 */
790 static void
791free_scrollback(term_T *term)
792{
793 int i;
794
795 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
796 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
797 ga_clear(&term->tl_scrollback);
798}
799
800/*
801 * Free a terminal and everything it refers to.
802 * Kills the job if there is one.
803 * Called when wiping out a buffer.
804 */
805 void
806free_terminal(buf_T *buf)
807{
808 term_T *term = buf->b_term;
809 term_T *tp;
810
811 if (term == NULL)
812 return;
813 if (first_term == term)
814 first_term = term->tl_next;
815 else
816 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
817 if (tp->tl_next == term)
818 {
819 tp->tl_next = term->tl_next;
820 break;
821 }
822
823 if (term->tl_job != NULL)
824 {
825 if (term->tl_job->jv_status != JOB_ENDED
826 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100827 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200828 job_stop(term->tl_job, NULL, "kill");
829 job_unref(term->tl_job);
830 }
831
832 free_scrollback(term);
833
834 term_free_vterm(term);
835 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100836#ifdef FEAT_SESSION
837 vim_free(term->tl_command);
838#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100839 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 vim_free(term->tl_status_text);
841 vim_free(term->tl_opencmd);
842 vim_free(term->tl_eof_chars);
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200843#ifdef WIN3264
844 if (term->tl_out_fd != NULL)
845 fclose(term->tl_out_fd);
846#endif
Bram Moolenaard317b382018-02-08 22:33:31 +0100847 if (desired_cursor_color == term->tl_cursor_color)
848 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200849 vim_free(term->tl_cursor_color);
850 vim_free(term);
851 buf->b_term = NULL;
852 if (in_terminal_loop == term)
853 in_terminal_loop = NULL;
854}
855
856/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100857 * Get the part that is connected to the tty. Normally this is PART_IN, but
858 * when writing buffer lines to the job it can be another. This makes it
859 * possible to do "1,5term vim -".
860 */
861 static ch_part_T
862get_tty_part(term_T *term)
863{
864#ifdef UNIX
865 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
866 int i;
867
868 for (i = 0; i < 3; ++i)
869 {
870 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
871
872 if (isatty(fd))
873 return parts[i];
874 }
875#endif
876 return PART_IN;
877}
878
879/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200880 * Write job output "msg[len]" to the vterm.
881 */
882 static void
883term_write_job_output(term_T *term, char_u *msg, size_t len)
884{
885 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100886 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200887
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100888 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200889
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100890 /* flush vterm buffer when vterm responded to control sequence */
891 if (prevlen != vterm_output_get_buffer_current(vterm))
892 {
893 char buf[KEY_BUF_LEN];
894 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
895
896 if (curlen > 0)
897 channel_send(term->tl_job->jv_channel, get_tty_part(term),
898 (char_u *)buf, (int)curlen, NULL);
899 }
900
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200901 /* this invokes the damage callbacks */
902 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
903}
904
905 static void
906update_cursor(term_T *term, int redraw)
907{
908 if (term->tl_normal_mode)
909 return;
Bram Moolenaar13568252018-03-16 20:46:58 +0100910#ifdef FEAT_GUI
911 if (term->tl_system)
912 windgoto(term->tl_cursor_pos.row + term->tl_toprow,
913 term->tl_cursor_pos.col);
914 else
915#endif
916 setcursor();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200917 if (redraw)
918 {
919 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
920 cursor_on();
921 out_flush();
922#ifdef FEAT_GUI
923 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100924 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200925 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100926 gui_mch_flush();
927 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200928#endif
929 }
930}
931
932/*
933 * Invoked when "msg" output from a job was received. Write it to the terminal
934 * of "buffer".
935 */
936 void
937write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
938{
939 size_t len = STRLEN(msg);
940 term_T *term = buffer->b_term;
941
Bram Moolenaarf25329c2018-05-06 21:49:32 +0200942#ifdef WIN3264
943 /* Win32: Cannot redirect output of the job, intercept it here and write to
944 * the file. */
945 if (term->tl_out_fd != NULL)
946 {
947 ch_log(channel, "Writing %d bytes to output file", (int)len);
948 fwrite(msg, len, 1, term->tl_out_fd);
949 return;
950 }
951#endif
952
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200953 if (term->tl_vterm == NULL)
954 {
955 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
956 return;
957 }
958 ch_log(channel, "writing %d bytes to terminal", (int)len);
959 term_write_job_output(term, msg, len);
960
Bram Moolenaar13568252018-03-16 20:46:58 +0100961#ifdef FEAT_GUI
962 if (term->tl_system)
963 {
964 /* show system output, scrolling up the screen as needed */
965 update_system_term(term);
966 update_cursor(term, TRUE);
967 }
968 else
969#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200970 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
971 * contents, thus no screen update is needed. */
972 if (!term->tl_normal_mode)
973 {
974 /* TODO: only update once in a while. */
975 ch_log(term->tl_job->jv_channel, "updating screen");
976 if (buffer == curbuf)
977 {
978 update_screen(0);
Bram Moolenaara10ae5e2018-05-11 20:48:29 +0200979 /* update_screen() can be slow, check the terminal wasn't closed
980 * already */
981 if (buffer == curbuf && curbuf->b_term != NULL)
982 update_cursor(curbuf->b_term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200983 }
984 else
985 redraw_after_callback(TRUE);
986 }
987}
988
989/*
990 * Send a mouse position and click to the vterm
991 */
992 static int
993term_send_mouse(VTerm *vterm, int button, int pressed)
994{
995 VTermModifier mod = VTERM_MOD_NONE;
996
997 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200998 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100999 if (button != 0)
1000 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001001 return TRUE;
1002}
1003
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001004static int enter_mouse_col = -1;
1005static int enter_mouse_row = -1;
1006
1007/*
1008 * Handle a mouse click, drag or release.
1009 * Return TRUE when a mouse event is sent to the terminal.
1010 */
1011 static int
1012term_mouse_click(VTerm *vterm, int key)
1013{
1014#if defined(FEAT_CLIPBOARD)
1015 /* For modeless selection mouse drag and release events are ignored, unless
1016 * they are preceded with a mouse down event */
1017 static int ignore_drag_release = TRUE;
1018 VTermMouseState mouse_state;
1019
1020 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
1021 if (mouse_state.flags == 0)
1022 {
1023 /* Terminal is not using the mouse, use modeless selection. */
1024 switch (key)
1025 {
1026 case K_LEFTDRAG:
1027 case K_LEFTRELEASE:
1028 case K_RIGHTDRAG:
1029 case K_RIGHTRELEASE:
1030 /* Ignore drag and release events when the button-down wasn't
1031 * seen before. */
1032 if (ignore_drag_release)
1033 {
1034 int save_mouse_col, save_mouse_row;
1035
1036 if (enter_mouse_col < 0)
1037 break;
1038
1039 /* mouse click in the window gave us focus, handle that
1040 * click now */
1041 save_mouse_col = mouse_col;
1042 save_mouse_row = mouse_row;
1043 mouse_col = enter_mouse_col;
1044 mouse_row = enter_mouse_row;
1045 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
1046 mouse_col = save_mouse_col;
1047 mouse_row = save_mouse_row;
1048 }
1049 /* FALLTHROUGH */
1050 case K_LEFTMOUSE:
1051 case K_RIGHTMOUSE:
1052 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
1053 ignore_drag_release = TRUE;
1054 else
1055 ignore_drag_release = FALSE;
1056 /* Should we call mouse_has() here? */
1057 if (clip_star.available)
1058 {
1059 int button, is_click, is_drag;
1060
1061 button = get_mouse_button(KEY2TERMCAP1(key),
1062 &is_click, &is_drag);
1063 if (mouse_model_popup() && button == MOUSE_LEFT
1064 && (mod_mask & MOD_MASK_SHIFT))
1065 {
1066 /* Translate shift-left to right button. */
1067 button = MOUSE_RIGHT;
1068 mod_mask &= ~MOD_MASK_SHIFT;
1069 }
1070 clip_modeless(button, is_click, is_drag);
1071 }
1072 break;
1073
1074 case K_MIDDLEMOUSE:
1075 if (clip_star.available)
1076 insert_reg('*', TRUE);
1077 break;
1078 }
1079 enter_mouse_col = -1;
1080 return FALSE;
1081 }
1082#endif
1083 enter_mouse_col = -1;
1084
1085 switch (key)
1086 {
1087 case K_LEFTMOUSE:
1088 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
1089 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
1090 case K_LEFTRELEASE:
1091 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
1092 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
1093 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
1094 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
1095 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
1096 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
1097 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
1098 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
1099 }
1100 return TRUE;
1101}
1102
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001103/*
1104 * Convert typed key "c" into bytes to send to the job.
1105 * Return the number of bytes in "buf".
1106 */
1107 static int
1108term_convert_key(term_T *term, int c, char *buf)
1109{
1110 VTerm *vterm = term->tl_vterm;
1111 VTermKey key = VTERM_KEY_NONE;
1112 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001113 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001114
1115 switch (c)
1116 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001117 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1118
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001119 /* don't use VTERM_KEY_BACKSPACE, it always
1120 * becomes 0x7f DEL */
1121 case K_BS: c = term_backspace_char; break;
1122
1123 case ESC: key = VTERM_KEY_ESCAPE; break;
1124 case K_DEL: key = VTERM_KEY_DEL; break;
1125 case K_DOWN: key = VTERM_KEY_DOWN; break;
1126 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1127 key = VTERM_KEY_DOWN; break;
1128 case K_END: key = VTERM_KEY_END; break;
1129 case K_S_END: mod = VTERM_MOD_SHIFT;
1130 key = VTERM_KEY_END; break;
1131 case K_C_END: mod = VTERM_MOD_CTRL;
1132 key = VTERM_KEY_END; break;
1133 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1134 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1135 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1136 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1137 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1138 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1139 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1140 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1141 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1142 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1143 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1144 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1145 case K_HOME: key = VTERM_KEY_HOME; break;
1146 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1147 key = VTERM_KEY_HOME; break;
1148 case K_C_HOME: mod = VTERM_MOD_CTRL;
1149 key = VTERM_KEY_HOME; break;
1150 case K_INS: key = VTERM_KEY_INS; break;
1151 case K_K0: key = VTERM_KEY_KP_0; break;
1152 case K_K1: key = VTERM_KEY_KP_1; break;
1153 case K_K2: key = VTERM_KEY_KP_2; break;
1154 case K_K3: key = VTERM_KEY_KP_3; break;
1155 case K_K4: key = VTERM_KEY_KP_4; break;
1156 case K_K5: key = VTERM_KEY_KP_5; break;
1157 case K_K6: key = VTERM_KEY_KP_6; break;
1158 case K_K7: key = VTERM_KEY_KP_7; break;
1159 case K_K8: key = VTERM_KEY_KP_8; break;
1160 case K_K9: key = VTERM_KEY_KP_9; break;
1161 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1162 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1163 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1164 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1165 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1166 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1167 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1168 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1169 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1170 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1171 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1172 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1173 case K_LEFT: key = VTERM_KEY_LEFT; break;
1174 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1175 key = VTERM_KEY_LEFT; break;
1176 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1177 key = VTERM_KEY_LEFT; break;
1178 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1179 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1180 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1181 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1182 key = VTERM_KEY_RIGHT; break;
1183 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1184 key = VTERM_KEY_RIGHT; break;
1185 case K_UP: key = VTERM_KEY_UP; break;
1186 case K_S_UP: mod = VTERM_MOD_SHIFT;
1187 key = VTERM_KEY_UP; break;
1188 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001189 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1190 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001191
Bram Moolenaara42ad572017-11-16 13:08:04 +01001192 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1193 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001194 case K_MOUSELEFT: /* TODO */ return 0;
1195 case K_MOUSERIGHT: /* TODO */ return 0;
1196
1197 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001198 case K_LEFTMOUSE_NM:
1199 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001200 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001201 case K_LEFTRELEASE_NM:
1202 case K_MOUSEMOVE:
1203 case K_MIDDLEMOUSE:
1204 case K_MIDDLEDRAG:
1205 case K_MIDDLERELEASE:
1206 case K_RIGHTMOUSE:
1207 case K_RIGHTDRAG:
1208 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1209 return 0;
1210 other = TRUE;
1211 break;
1212
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001213 case K_X1MOUSE: /* TODO */ return 0;
1214 case K_X1DRAG: /* TODO */ return 0;
1215 case K_X1RELEASE: /* TODO */ return 0;
1216 case K_X2MOUSE: /* TODO */ return 0;
1217 case K_X2DRAG: /* TODO */ return 0;
1218 case K_X2RELEASE: /* TODO */ return 0;
1219
1220 case K_IGNORE: return 0;
1221 case K_NOP: return 0;
1222 case K_UNDO: return 0;
1223 case K_HELP: return 0;
1224 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1225 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1226 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1227 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1228 case K_SELECT: return 0;
1229#ifdef FEAT_GUI
1230 case K_VER_SCROLLBAR: return 0;
1231 case K_HOR_SCROLLBAR: return 0;
1232#endif
1233#ifdef FEAT_GUI_TABLINE
1234 case K_TABLINE: return 0;
1235 case K_TABMENU: return 0;
1236#endif
1237#ifdef FEAT_NETBEANS_INTG
1238 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1239#endif
1240#ifdef FEAT_DND
1241 case K_DROP: return 0;
1242#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001243 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001244 case K_PS: vterm_keyboard_start_paste(vterm);
1245 other = TRUE;
1246 break;
1247 case K_PE: vterm_keyboard_end_paste(vterm);
1248 other = TRUE;
1249 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001250 }
1251
1252 /*
1253 * Convert special keys to vterm keys:
1254 * - Write keys to vterm: vterm_keyboard_key()
1255 * - Write output to channel.
1256 * TODO: use mod_mask
1257 */
1258 if (key != VTERM_KEY_NONE)
1259 /* Special key, let vterm convert it. */
1260 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001261 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001262 /* Normal character, let vterm convert it. */
1263 vterm_keyboard_unichar(vterm, c, mod);
1264
1265 /* Read back the converted escape sequence. */
1266 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1267}
1268
1269/*
1270 * Return TRUE if the job for "term" is still running.
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001271 * If "check_job_status" is TRUE update the job status.
1272 */
1273 static int
1274term_job_running_check(term_T *term, int check_job_status)
1275{
1276 /* Also consider the job finished when the channel is closed, to avoid a
1277 * race condition when updating the title. */
1278 if (term != NULL
1279 && term->tl_job != NULL
1280 && channel_is_open(term->tl_job->jv_channel))
1281 {
1282 if (check_job_status)
1283 job_status(term->tl_job);
1284 return (term->tl_job->jv_status == JOB_STARTED
1285 || term->tl_job->jv_channel->ch_keep_open);
1286 }
1287 return FALSE;
1288}
1289
1290/*
1291 * Return TRUE if the job for "term" is still running.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001292 */
1293 int
1294term_job_running(term_T *term)
1295{
Bram Moolenaar802bfb12018-04-15 17:28:13 +02001296 return term_job_running_check(term, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001297}
1298
1299/*
1300 * Return TRUE if "term" has an active channel and used ":term NONE".
1301 */
1302 int
1303term_none_open(term_T *term)
1304{
1305 /* Also consider the job finished when the channel is closed, to avoid a
1306 * race condition when updating the title. */
1307 return term != NULL
1308 && term->tl_job != NULL
1309 && channel_is_open(term->tl_job->jv_channel)
1310 && term->tl_job->jv_channel->ch_keep_open;
1311}
1312
1313/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001314 * Used when exiting: kill the job in "buf" if so desired.
1315 * Return OK when the job finished.
1316 * Return FAIL when the job is still running.
1317 */
1318 int
1319term_try_stop_job(buf_T *buf)
1320{
1321 int count;
1322 char *how = (char *)buf->b_term->tl_kill;
1323
1324#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1325 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1326 {
1327 char_u buff[DIALOG_MSG_SIZE];
1328 int ret;
1329
1330 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1331 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1332 if (ret == VIM_YES)
1333 how = "kill";
1334 else if (ret == VIM_CANCEL)
1335 return FAIL;
1336 }
1337#endif
1338 if (how == NULL || *how == NUL)
1339 return FAIL;
1340
1341 job_stop(buf->b_term->tl_job, NULL, how);
1342
1343 /* wait for up to a second for the job to die */
1344 for (count = 0; count < 100; ++count)
1345 {
1346 /* buffer, terminal and job may be cleaned up while waiting */
1347 if (!buf_valid(buf)
1348 || buf->b_term == NULL
1349 || buf->b_term->tl_job == NULL)
1350 return OK;
1351
1352 /* call job_status() to update jv_status */
1353 job_status(buf->b_term->tl_job);
1354 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1355 return OK;
1356 ui_delay(10L, FALSE);
1357 mch_check_messages();
1358 parse_queued_messages();
1359 }
1360 return FAIL;
1361}
1362
1363/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001364 * Add the last line of the scrollback buffer to the buffer in the window.
1365 */
1366 static void
1367add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1368{
1369 buf_T *buf = term->tl_buffer;
1370 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1371 linenr_T lnum = buf->b_ml.ml_line_count;
1372
1373#ifdef WIN3264
1374 if (!enc_utf8 && enc_codepage > 0)
1375 {
1376 WCHAR *ret = NULL;
1377 int length = 0;
1378
1379 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1380 &ret, &length);
1381 if (ret != NULL)
1382 {
1383 WideCharToMultiByte_alloc(enc_codepage, 0,
1384 ret, length, (char **)&text, &len, 0, 0);
1385 vim_free(ret);
1386 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1387 vim_free(text);
1388 }
1389 }
1390 else
1391#endif
1392 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1393 if (empty)
1394 {
1395 /* Delete the empty line that was in the empty buffer. */
1396 curbuf = buf;
1397 ml_delete(1, FALSE);
1398 curbuf = curwin->w_buffer;
1399 }
1400}
1401
1402 static void
1403cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1404{
1405 attr->width = cell->width;
1406 attr->attrs = cell->attrs;
1407 attr->fg = cell->fg;
1408 attr->bg = cell->bg;
1409}
1410
1411 static int
1412equal_celattr(cellattr_T *a, cellattr_T *b)
1413{
1414 /* Comparing the colors should be sufficient. */
1415 return a->fg.red == b->fg.red
1416 && a->fg.green == b->fg.green
1417 && a->fg.blue == b->fg.blue
1418 && a->bg.red == b->bg.red
1419 && a->bg.green == b->bg.green
1420 && a->bg.blue == b->bg.blue;
1421}
1422
Bram Moolenaard96ff162018-02-18 22:13:29 +01001423/*
1424 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1425 * line at this position. Otherwise at the end.
1426 */
1427 static int
1428add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1429{
1430 if (ga_grow(&term->tl_scrollback, 1) == OK)
1431 {
1432 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1433 + term->tl_scrollback.ga_len;
1434
1435 if (lnum > 0)
1436 {
1437 int i;
1438
1439 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1440 {
1441 *line = *(line - 1);
1442 --line;
1443 }
1444 }
1445 line->sb_cols = 0;
1446 line->sb_cells = NULL;
1447 line->sb_fill_attr = *fill_attr;
1448 ++term->tl_scrollback.ga_len;
1449 return OK;
1450 }
1451 return FALSE;
1452}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001453
1454/*
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001455 * Remove the terminal contents from the scrollback and the buffer.
1456 * Used before adding a new scrollback line or updating the buffer for lines
1457 * displayed in the terminal.
1458 */
1459 static void
1460cleanup_scrollback(term_T *term)
1461{
1462 sb_line_T *line;
1463 garray_T *gap;
1464
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001465 curbuf = term->tl_buffer;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001466 gap = &term->tl_scrollback;
1467 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1468 && gap->ga_len > 0)
1469 {
1470 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1471 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1472 vim_free(line->sb_cells);
1473 --gap->ga_len;
1474 }
Bram Moolenaar3f1a53c2018-05-12 16:55:14 +02001475 curbuf = curwin->w_buffer;
1476 if (curbuf == term->tl_buffer)
1477 check_cursor();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001478}
1479
1480/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001481 * Add the current lines of the terminal to scrollback and to the buffer.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001482 */
1483 static void
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001484update_snapshot(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001485{
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001486 VTermScreen *screen;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001487 int len;
1488 int lines_skipped = 0;
1489 VTermPos pos;
1490 VTermScreenCell cell;
1491 cellattr_T fill_attr, new_fill_attr;
1492 cellattr_T *p;
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001493
1494 ch_log(term->tl_job == NULL ? NULL : term->tl_job->jv_channel,
1495 "Adding terminal window snapshot to buffer");
1496
1497 /* First remove the lines that were appended before, they might be
1498 * outdated. */
1499 cleanup_scrollback(term);
1500
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001501 screen = vterm_obtain_screen(term->tl_vterm);
1502 fill_attr = new_fill_attr = term->tl_default_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001503 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1504 {
1505 len = 0;
1506 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1507 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1508 && cell.chars[0] != NUL)
1509 {
1510 len = pos.col + 1;
1511 new_fill_attr = term->tl_default_color;
1512 }
1513 else
1514 /* Assume the last attr is the filler attr. */
1515 cell2cellattr(&cell, &new_fill_attr);
1516
1517 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1518 ++lines_skipped;
1519 else
1520 {
1521 while (lines_skipped > 0)
1522 {
1523 /* Line was skipped, add an empty line. */
1524 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001525 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001526 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001527 }
1528
1529 if (len == 0)
1530 p = NULL;
1531 else
1532 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1533 if ((p != NULL || len == 0)
1534 && ga_grow(&term->tl_scrollback, 1) == OK)
1535 {
1536 garray_T ga;
1537 int width;
1538 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1539 + term->tl_scrollback.ga_len;
1540
1541 ga_init2(&ga, 1, 100);
1542 for (pos.col = 0; pos.col < len; pos.col += width)
1543 {
1544 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1545 {
1546 width = 1;
1547 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1548 if (ga_grow(&ga, 1) == OK)
1549 ga.ga_len += utf_char2bytes(' ',
1550 (char_u *)ga.ga_data + ga.ga_len);
1551 }
1552 else
1553 {
1554 width = cell.width;
1555
1556 cell2cellattr(&cell, &p[pos.col]);
1557
1558 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1559 {
1560 int i;
1561 int c;
1562
1563 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1564 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1565 (char_u *)ga.ga_data + ga.ga_len);
1566 }
1567 }
1568 }
1569 line->sb_cols = len;
1570 line->sb_cells = p;
1571 line->sb_fill_attr = new_fill_attr;
1572 fill_attr = new_fill_attr;
1573 ++term->tl_scrollback.ga_len;
1574
1575 if (ga_grow(&ga, 1) == FAIL)
1576 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1577 else
1578 {
1579 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1580 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1581 }
1582 ga_clear(&ga);
1583 }
1584 else
1585 vim_free(p);
1586 }
1587 }
1588
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001589 term->tl_dirty_snapshot = FALSE;
1590#ifdef FEAT_TIMERS
1591 term->tl_timer_set = FALSE;
1592#endif
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001593}
1594
1595/*
1596 * If needed, add the current lines of the terminal to scrollback and to the
1597 * buffer. Called after the job has ended and when switching to
1598 * Terminal-Normal mode.
1599 * When "redraw" is TRUE redraw the windows that show the terminal.
1600 */
1601 static void
1602may_move_terminal_to_buffer(term_T *term, int redraw)
1603{
1604 win_T *wp;
1605
1606 if (term->tl_vterm == NULL)
1607 return;
1608
1609 /* Update the snapshot only if something changes or the buffer does not
1610 * have all the lines. */
1611 if (term->tl_dirty_snapshot || term->tl_buffer->b_ml.ml_line_count
1612 <= term->tl_scrollback_scrolled)
1613 update_snapshot(term);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001614
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 /* Obtain the current background color. */
1616 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1617 &term->tl_default_color.fg, &term->tl_default_color.bg);
1618
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001619 if (redraw)
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001620 FOR_ALL_WINDOWS(wp)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001621 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001622 if (wp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001623 {
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001624 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1625 wp->w_cursor.col = 0;
1626 wp->w_valid = 0;
1627 if (wp->w_cursor.lnum >= wp->w_height)
1628 {
1629 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001630
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001631 if (wp->w_topline < min_topline)
1632 wp->w_topline = min_topline;
1633 }
1634 redraw_win_later(wp, NOT_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001635 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001637}
1638
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001639#if defined(FEAT_TIMERS) || defined(PROTO)
1640/*
1641 * Check if any terminal timer expired. If so, copy text from the terminal to
1642 * the buffer.
1643 * Return the time until the next timer will expire.
1644 */
1645 int
1646term_check_timers(int next_due_arg, proftime_T *now)
1647{
1648 term_T *term;
1649 int next_due = next_due_arg;
1650
1651 for (term = first_term; term != NULL; term = term->tl_next)
1652 {
1653 if (term->tl_timer_set && !term->tl_normal_mode)
1654 {
1655 long this_due = proftime_time_left(&term->tl_timer_due, now);
1656
1657 if (this_due <= 1)
1658 {
1659 term->tl_timer_set = FALSE;
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001660 may_move_terminal_to_buffer(term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02001661 }
1662 else if (next_due == -1 || next_due > this_due)
1663 next_due = this_due;
1664 }
1665 }
1666
1667 return next_due;
1668}
1669#endif
1670
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001671 static void
1672set_terminal_mode(term_T *term, int normal_mode)
1673{
1674 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001675 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001676 if (term->tl_buffer == curbuf)
1677 maketitle();
1678}
1679
1680/*
1681 * Called after the job if finished and Terminal mode is not active:
1682 * Move the vterm contents into the scrollback buffer and free the vterm.
1683 */
1684 static void
1685cleanup_vterm(term_T *term)
1686{
Bram Moolenaar1dd98332018-03-16 22:54:53 +01001687 if (term->tl_finish != TL_FINISH_CLOSE)
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001688 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001689 term_free_vterm(term);
1690 set_terminal_mode(term, FALSE);
1691}
1692
1693/*
1694 * Switch from Terminal-Job mode to Terminal-Normal mode.
1695 * Suspends updating the terminal window.
1696 */
1697 static void
1698term_enter_normal_mode(void)
1699{
1700 term_T *term = curbuf->b_term;
1701
Bram Moolenaar2bc79952018-05-12 20:36:24 +02001702 set_terminal_mode(term, TRUE);
1703
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001704 /* Append the current terminal contents to the buffer. */
Bram Moolenaar05c4a472018-05-13 15:15:43 +02001705 may_move_terminal_to_buffer(term, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001706
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001707 /* Move the window cursor to the position of the cursor in the
1708 * terminal. */
1709 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1710 + term->tl_cursor_pos.row + 1;
1711 check_cursor();
Bram Moolenaar620020e2018-05-13 19:06:12 +02001712 if (coladvance(term->tl_cursor_pos.col) == FAIL)
1713 coladvance(MAXCOL);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001714
1715 /* Display the same lines as in the terminal. */
1716 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1717}
1718
1719/*
1720 * Returns TRUE if the current window contains a terminal and we are in
1721 * Terminal-Normal mode.
1722 */
1723 int
1724term_in_normal_mode(void)
1725{
1726 term_T *term = curbuf->b_term;
1727
1728 return term != NULL && term->tl_normal_mode;
1729}
1730
1731/*
1732 * Switch from Terminal-Normal mode to Terminal-Job mode.
1733 * Restores updating the terminal window.
1734 */
1735 void
1736term_enter_job_mode()
1737{
1738 term_T *term = curbuf->b_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001739
1740 set_terminal_mode(term, FALSE);
1741
1742 if (term->tl_channel_closed)
1743 cleanup_vterm(term);
1744 redraw_buf_and_status_later(curbuf, NOT_VALID);
1745}
1746
1747/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001748 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001749 * Note: while waiting a terminal may be closed and freed if the channel is
1750 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001751 */
1752 static int
1753term_vgetc()
1754{
1755 int c;
1756 int save_State = State;
1757
1758 State = TERMINAL;
1759 got_int = FALSE;
1760#ifdef WIN3264
1761 ctrl_break_was_pressed = FALSE;
1762#endif
1763 c = vgetc();
1764 got_int = FALSE;
1765 State = save_State;
1766 return c;
1767}
1768
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001769static int mouse_was_outside = FALSE;
1770
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001771/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772 * Send keys to terminal.
1773 * Return FAIL when the key needs to be handled in Normal mode.
1774 * Return OK when the key was dropped or sent to the terminal.
1775 */
1776 int
1777send_keys_to_term(term_T *term, int c, int typed)
1778{
1779 char msg[KEY_BUF_LEN];
1780 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001781 int dragging_outside = FALSE;
1782
1783 /* Catch keys that need to be handled as in Normal mode. */
1784 switch (c)
1785 {
1786 case NUL:
1787 case K_ZERO:
1788 if (typed)
1789 stuffcharReadbuff(c);
1790 return FAIL;
1791
Bram Moolenaar231a2db2018-05-06 13:53:50 +02001792 case K_TABLINE:
1793 stuffcharReadbuff(c);
1794 return FAIL;
1795
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001796 case K_IGNORE:
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001797 case K_CANCEL: // used for :normal when running out of chars
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001798 return FAIL;
1799
1800 case K_LEFTDRAG:
1801 case K_MIDDLEDRAG:
1802 case K_RIGHTDRAG:
1803 case K_X1DRAG:
1804 case K_X2DRAG:
1805 dragging_outside = mouse_was_outside;
1806 /* FALLTHROUGH */
1807 case K_LEFTMOUSE:
1808 case K_LEFTMOUSE_NM:
1809 case K_LEFTRELEASE:
1810 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001811 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 case K_MIDDLEMOUSE:
1813 case K_MIDDLERELEASE:
1814 case K_RIGHTMOUSE:
1815 case K_RIGHTRELEASE:
1816 case K_X1MOUSE:
1817 case K_X1RELEASE:
1818 case K_X2MOUSE:
1819 case K_X2RELEASE:
1820
1821 case K_MOUSEUP:
1822 case K_MOUSEDOWN:
1823 case K_MOUSELEFT:
1824 case K_MOUSERIGHT:
1825 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001826 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001827 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001828 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001829 || dragging_outside)
1830 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001831 /* click or scroll outside the current window or on status line
1832 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001833 if (typed)
1834 {
1835 stuffcharReadbuff(c);
1836 mouse_was_outside = TRUE;
1837 }
1838 return FAIL;
1839 }
1840 }
1841 if (typed)
1842 mouse_was_outside = FALSE;
1843
1844 /* Convert the typed key to a sequence of bytes for the job. */
1845 len = term_convert_key(term, c, msg);
1846 if (len > 0)
1847 /* TODO: if FAIL is returned, stop? */
1848 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1849 (char_u *)msg, (int)len, NULL);
1850
1851 return OK;
1852}
1853
1854 static void
1855position_cursor(win_T *wp, VTermPos *pos)
1856{
1857 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1858 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1859 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1860}
1861
1862/*
1863 * Handle CTRL-W "": send register contents to the job.
1864 */
1865 static void
1866term_paste_register(int prev_c UNUSED)
1867{
1868 int c;
1869 list_T *l;
1870 listitem_T *item;
1871 long reglen = 0;
1872 int type;
1873
1874#ifdef FEAT_CMDL_INFO
1875 if (add_to_showcmd(prev_c))
1876 if (add_to_showcmd('"'))
1877 out_flush();
1878#endif
1879 c = term_vgetc();
1880#ifdef FEAT_CMDL_INFO
1881 clear_showcmd();
1882#endif
1883 if (!term_use_loop())
1884 /* job finished while waiting for a character */
1885 return;
1886
1887 /* CTRL-W "= prompt for expression to evaluate. */
1888 if (c == '=' && get_expr_register() != '=')
1889 return;
1890 if (!term_use_loop())
1891 /* job finished while waiting for a character */
1892 return;
1893
1894 l = (list_T *)get_reg_contents(c, GREG_LIST);
1895 if (l != NULL)
1896 {
1897 type = get_reg_type(c, &reglen);
1898 for (item = l->lv_first; item != NULL; item = item->li_next)
1899 {
1900 char_u *s = get_tv_string(&item->li_tv);
1901#ifdef WIN3264
1902 char_u *tmp = s;
1903
1904 if (!enc_utf8 && enc_codepage > 0)
1905 {
1906 WCHAR *ret = NULL;
1907 int length = 0;
1908
1909 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1910 (int)STRLEN(s), &ret, &length);
1911 if (ret != NULL)
1912 {
1913 WideCharToMultiByte_alloc(CP_UTF8, 0,
1914 ret, length, (char **)&s, &length, 0, 0);
1915 vim_free(ret);
1916 }
1917 }
1918#endif
1919 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1920 s, (int)STRLEN(s), NULL);
1921#ifdef WIN3264
1922 if (tmp != s)
1923 vim_free(s);
1924#endif
1925
1926 if (item->li_next != NULL || type == MLINE)
1927 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1928 (char_u *)"\r", 1, NULL);
1929 }
1930 list_free(l);
1931 }
1932}
1933
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001934/*
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001935 * Return TRUE when waiting for a character in the terminal, the cursor of the
1936 * terminal should be displayed.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001937 */
1938 int
1939terminal_is_active()
1940{
1941 return in_terminal_loop != NULL;
1942}
1943
Bram Moolenaarb2ac14c2018-05-01 18:47:59 +02001944#if defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001945 cursorentry_T *
1946term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1947{
1948 term_T *term = in_terminal_loop;
1949 static cursorentry_T entry;
1950
1951 vim_memset(&entry, 0, sizeof(entry));
1952 entry.shape = entry.mshape =
1953 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1954 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1955 SHAPE_BLOCK;
1956 entry.percentage = 20;
1957 if (term->tl_cursor_blink)
1958 {
1959 entry.blinkwait = 700;
1960 entry.blinkon = 400;
1961 entry.blinkoff = 250;
1962 }
1963 *fg = gui.back_pixel;
1964 if (term->tl_cursor_color == NULL)
1965 *bg = gui.norm_pixel;
1966 else
1967 *bg = color_name2handle(term->tl_cursor_color);
1968 entry.name = "n";
1969 entry.used_for = SHAPE_CURSOR;
1970
1971 return &entry;
1972}
1973#endif
1974
Bram Moolenaard317b382018-02-08 22:33:31 +01001975 static void
1976may_output_cursor_props(void)
1977{
1978 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1979 || last_set_cursor_shape != desired_cursor_shape
1980 || last_set_cursor_blink != desired_cursor_blink)
1981 {
1982 last_set_cursor_color = desired_cursor_color;
1983 last_set_cursor_shape = desired_cursor_shape;
1984 last_set_cursor_blink = desired_cursor_blink;
1985 term_cursor_color(desired_cursor_color);
1986 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1987 /* this will restore the initial cursor style, if possible */
1988 ui_cursor_shape_forced(TRUE);
1989 else
1990 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1991 }
1992}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001993
Bram Moolenaard317b382018-02-08 22:33:31 +01001994/*
1995 * Set the cursor color and shape, if not last set to these.
1996 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001997 static void
1998may_set_cursor_props(term_T *term)
1999{
2000#ifdef FEAT_GUI
2001 /* For the GUI the cursor properties are obtained with
2002 * term_get_cursor_shape(). */
2003 if (gui.in_use)
2004 return;
2005#endif
2006 if (in_terminal_loop == term)
2007 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002008 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01002009 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002010 else
Bram Moolenaard317b382018-02-08 22:33:31 +01002011 desired_cursor_color = (char_u *)"";
2012 desired_cursor_shape = term->tl_cursor_shape;
2013 desired_cursor_blink = term->tl_cursor_blink;
2014 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002015 }
2016}
2017
Bram Moolenaard317b382018-02-08 22:33:31 +01002018/*
2019 * Reset the desired cursor properties and restore them when needed.
2020 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002021 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01002022prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002023{
2024#ifdef FEAT_GUI
2025 if (gui.in_use)
2026 return;
2027#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01002028 desired_cursor_color = (char_u *)"";
2029 desired_cursor_shape = -1;
2030 desired_cursor_blink = -1;
2031 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002032}
2033
2034/*
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002035 * Returns TRUE if the current window contains a terminal and we are sending
2036 * keys to the job.
2037 * If "check_job_status" is TRUE update the job status.
2038 */
2039 static int
2040term_use_loop_check(int check_job_status)
2041{
2042 term_T *term = curbuf->b_term;
2043
2044 return term != NULL
2045 && !term->tl_normal_mode
2046 && term->tl_vterm != NULL
2047 && term_job_running_check(term, check_job_status);
2048}
2049
2050/*
2051 * Returns TRUE if the current window contains a terminal and we are sending
2052 * keys to the job.
2053 */
2054 int
2055term_use_loop(void)
2056{
2057 return term_use_loop_check(FALSE);
2058}
2059
2060/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002061 * Called when entering a window with the mouse. If this is a terminal window
2062 * we may want to change state.
2063 */
2064 void
2065term_win_entered()
2066{
2067 term_T *term = curbuf->b_term;
2068
2069 if (term != NULL)
2070 {
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002071 if (term_use_loop_check(TRUE))
Bram Moolenaarc48369c2018-03-11 19:30:45 +01002072 {
2073 reset_VIsual_and_resel();
2074 if (State & INSERT)
2075 stop_insert_mode = TRUE;
2076 }
2077 mouse_was_outside = FALSE;
2078 enter_mouse_col = mouse_col;
2079 enter_mouse_row = mouse_row;
2080 }
2081}
2082
2083/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002084 * Wait for input and send it to the job.
2085 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
2086 * when there is no more typahead.
2087 * Return when the start of a CTRL-W command is typed or anything else that
2088 * should be handled as a Normal mode command.
2089 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
2090 * the terminal was closed.
2091 */
2092 int
2093terminal_loop(int blocking)
2094{
2095 int c;
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002096 int termwinkey = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002097 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01002098#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002099 int tty_fd = curbuf->b_term->tl_job->jv_channel
2100 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01002101#endif
Bram Moolenaar73dd1bd2018-05-12 21:16:25 +02002102 int restore_cursor = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002103
2104 /* Remember the terminal we are sending keys to. However, the terminal
2105 * might be closed while waiting for a character, e.g. typing "exit" in a
2106 * shell and ++close was used. Therefore use curbuf->b_term instead of a
2107 * stored reference. */
2108 in_terminal_loop = curbuf->b_term;
2109
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002110 if (*curwin->w_p_twk != NUL)
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002111 termwinkey = string_to_key(curwin->w_p_twk, TRUE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002112 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
2113 may_set_cursor_props(curbuf->b_term);
2114
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01002115 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002116 {
Bram Moolenaar13568252018-03-16 20:46:58 +01002117#ifdef FEAT_GUI
2118 if (!curbuf->b_term->tl_system)
2119#endif
2120 /* TODO: skip screen update when handling a sequence of keys. */
2121 /* Repeat redrawing in case a message is received while redrawing.
2122 */
2123 while (must_redraw != 0)
2124 if (update_screen(0) == FAIL)
2125 break;
Bram Moolenaara10ae5e2018-05-11 20:48:29 +02002126 if (!term_use_loop_check(TRUE))
2127 /* job finished while redrawing */
2128 break;
2129
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002130 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01002131 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002132
2133 c = term_vgetc();
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002134 if (!term_use_loop_check(TRUE))
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002135 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002136 /* Job finished while waiting for a character. Push back the
2137 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002138 if (c != K_IGNORE)
2139 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002140 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01002141 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002142 if (c == K_IGNORE)
2143 continue;
2144
Bram Moolenaar26d205d2017-11-09 17:33:11 +01002145#ifdef UNIX
2146 /*
2147 * The shell or another program may change the tty settings. Getting
2148 * them for every typed character is a bit of overhead, but it's needed
2149 * for the first character typed, e.g. when Vim starts in a shell.
2150 */
2151 if (isatty(tty_fd))
2152 {
2153 ttyinfo_T info;
2154
2155 /* Get the current backspace character of the pty. */
2156 if (get_tty_info(tty_fd, &info) == OK)
2157 term_backspace_char = info.backspace;
2158 }
2159#endif
2160
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002161#ifdef WIN3264
2162 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
2163 * Use CTRL-BREAK to kill the job. */
2164 if (ctrl_break_was_pressed)
2165 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2166#endif
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002167 /* Was either CTRL-W (termwinkey) or CTRL-\ pressed?
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002168 * Not in a system terminal. */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002169 if ((c == (termwinkey == 0 ? Ctrl_W : termwinkey) || c == Ctrl_BSL)
Bram Moolenaaraf23bad2018-03-16 22:20:49 +01002170#ifdef FEAT_GUI
2171 && !curbuf->b_term->tl_system
2172#endif
2173 )
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002174 {
2175 int prev_c = c;
2176
2177#ifdef FEAT_CMDL_INFO
2178 if (add_to_showcmd(c))
2179 out_flush();
2180#endif
2181 c = term_vgetc();
2182#ifdef FEAT_CMDL_INFO
2183 clear_showcmd();
2184#endif
Bram Moolenaar802bfb12018-04-15 17:28:13 +02002185 if (!term_use_loop_check(TRUE))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002186 /* job finished while waiting for a character */
2187 break;
2188
2189 if (prev_c == Ctrl_BSL)
2190 {
2191 if (c == Ctrl_N)
2192 {
2193 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
2194 term_enter_normal_mode();
2195 ret = FAIL;
2196 goto theend;
2197 }
2198 /* Send both keys to the terminal. */
2199 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
2200 }
2201 else if (c == Ctrl_C)
2202 {
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002203 /* "CTRL-W CTRL-C" or 'termwinkey' CTRL-C: end the job */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002204 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
2205 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002206 else if (termwinkey == 0 && c == '.')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002207 {
2208 /* "CTRL-W .": send CTRL-W to the job */
2209 c = Ctrl_W;
2210 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002211 else if (termwinkey == 0 && c == Ctrl_BSL)
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002212 {
2213 /* "CTRL-W CTRL-\": send CTRL-\ to the job */
2214 c = Ctrl_BSL;
2215 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002216 else if (c == 'N')
2217 {
2218 /* CTRL-W N : go to Terminal-Normal mode. */
2219 term_enter_normal_mode();
2220 ret = FAIL;
2221 goto theend;
2222 }
2223 else if (c == '"')
2224 {
2225 term_paste_register(prev_c);
2226 continue;
2227 }
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02002228 else if (termwinkey == 0 || c != termwinkey)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002229 {
2230 stuffcharReadbuff(Ctrl_W);
2231 stuffcharReadbuff(c);
2232 ret = OK;
2233 goto theend;
2234 }
2235 }
2236# ifdef WIN3264
2237 if (!enc_utf8 && has_mbyte && c >= 0x80)
2238 {
2239 WCHAR wc;
2240 char_u mb[3];
2241
2242 mb[0] = (unsigned)c >> 8;
2243 mb[1] = c;
2244 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2245 c = wc;
2246 }
2247# endif
2248 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2249 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002250 if (c == K_MOUSEMOVE)
2251 /* We are sure to come back here, don't reset the cursor color
2252 * and shape to avoid flickering. */
2253 restore_cursor = FALSE;
2254
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002255 ret = OK;
2256 goto theend;
2257 }
2258 }
2259 ret = FAIL;
2260
2261theend:
2262 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002263 if (restore_cursor)
2264 prepare_restore_cursor_props();
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002265
2266 /* Move a snapshot of the screen contents to the buffer, so that completion
2267 * works in other buffers. */
Bram Moolenaar620020e2018-05-13 19:06:12 +02002268 if (curbuf->b_term != NULL && !curbuf->b_term->tl_normal_mode)
2269 may_move_terminal_to_buffer(curbuf->b_term, FALSE);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002270
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002271 return ret;
2272}
2273
2274/*
2275 * Called when a job has finished.
2276 * This updates the title and status, but does not close the vterm, because
2277 * there might still be pending output in the channel.
2278 */
2279 void
2280term_job_ended(job_T *job)
2281{
2282 term_T *term;
2283 int did_one = FALSE;
2284
2285 for (term = first_term; term != NULL; term = term->tl_next)
2286 if (term->tl_job == job)
2287 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002288 VIM_CLEAR(term->tl_title);
2289 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002290 redraw_buf_and_status_later(term->tl_buffer, VALID);
2291 did_one = TRUE;
2292 }
2293 if (did_one)
2294 redraw_statuslines();
2295 if (curbuf->b_term != NULL)
2296 {
2297 if (curbuf->b_term->tl_job == job)
2298 maketitle();
2299 update_cursor(curbuf->b_term, TRUE);
2300 }
2301}
2302
2303 static void
2304may_toggle_cursor(term_T *term)
2305{
2306 if (in_terminal_loop == term)
2307 {
2308 if (term->tl_cursor_visible)
2309 cursor_on();
2310 else
2311 cursor_off();
2312 }
2313}
2314
2315/*
2316 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002317 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002318 */
2319 static int
2320color2index(VTermColor *color, int fg, int *boldp)
2321{
2322 int red = color->red;
2323 int blue = color->blue;
2324 int green = color->green;
2325
Bram Moolenaar46359e12017-11-29 22:33:38 +01002326 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002327 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002328 /* First 16 colors and default: use the ANSI index, because these
2329 * colors can be redefined. */
2330 if (t_colors >= 16)
2331 return color->ansi_index;
2332 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002333 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002334 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002335 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002336 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2337 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2338 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
Bram Moolenaarb59118d2018-04-13 22:11:56 +02002339 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002340 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2341 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2342 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2343 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2344 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2345 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2346 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2347 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2348 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2349 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2350 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002351 }
2352 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002353
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354 if (t_colors >= 256)
2355 {
2356 if (red == blue && red == green)
2357 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002358 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002359 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002360 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2361 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2362 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002363 int i;
2364
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002365 if (red < 5)
2366 return 17; /* 00/00/00 */
2367 if (red > 245) /* ff/ff/ff */
2368 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002369 for (i = 0; i < 23; ++i)
2370 if (red < cutoff[i])
2371 return i + 233;
2372 return 256;
2373 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002374 {
2375 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2376 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002377
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002378 /* 216-color cube */
2379 for (ri = 0; ri < 5; ++ri)
2380 if (red < cutoff[ri])
2381 break;
2382 for (gi = 0; gi < 5; ++gi)
2383 if (green < cutoff[gi])
2384 break;
2385 for (bi = 0; bi < 5; ++bi)
2386 if (blue < cutoff[bi])
2387 break;
2388 return 17 + ri * 36 + gi * 6 + bi;
2389 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390 }
2391 return 0;
2392}
2393
2394/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002395 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 */
2397 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002398vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002399{
2400 int attr = 0;
2401
2402 if (cellattrs.bold)
2403 attr |= HL_BOLD;
2404 if (cellattrs.underline)
2405 attr |= HL_UNDERLINE;
2406 if (cellattrs.italic)
2407 attr |= HL_ITALIC;
2408 if (cellattrs.strike)
2409 attr |= HL_STRIKETHROUGH;
2410 if (cellattrs.reverse)
2411 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002412 return attr;
2413}
2414
2415/*
2416 * Store Vterm attributes in "cell" from highlight flags.
2417 */
2418 static void
2419hl2vtermAttr(int attr, cellattr_T *cell)
2420{
2421 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2422 if (attr & HL_BOLD)
2423 cell->attrs.bold = 1;
2424 if (attr & HL_UNDERLINE)
2425 cell->attrs.underline = 1;
2426 if (attr & HL_ITALIC)
2427 cell->attrs.italic = 1;
2428 if (attr & HL_STRIKETHROUGH)
2429 cell->attrs.strike = 1;
2430 if (attr & HL_INVERSE)
2431 cell->attrs.reverse = 1;
2432}
2433
2434/*
2435 * Convert the attributes of a vterm cell into an attribute index.
2436 */
2437 static int
2438cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2439{
2440 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002441
2442#ifdef FEAT_GUI
2443 if (gui.in_use)
2444 {
2445 guicolor_T fg, bg;
2446
2447 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2448 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2449 return get_gui_attr_idx(attr, fg, bg);
2450 }
2451 else
2452#endif
2453#ifdef FEAT_TERMGUICOLORS
2454 if (p_tgc)
2455 {
2456 guicolor_T fg, bg;
2457
2458 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2459 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2460
2461 return get_tgc_attr_idx(attr, fg, bg);
2462 }
2463 else
2464#endif
2465 {
2466 int bold = MAYBE;
2467 int fg = color2index(&cellfg, TRUE, &bold);
2468 int bg = color2index(&cellbg, FALSE, &bold);
2469
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002470 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002471 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002472 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002473 if (fg == 0 && term_default_cterm_fg >= 0)
2474 fg = term_default_cterm_fg + 1;
2475 if (bg == 0 && term_default_cterm_bg >= 0)
2476 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002477 }
2478
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 /* with 8 colors set the bold attribute to get a bright foreground */
2480 if (bold == TRUE)
2481 attr |= HL_BOLD;
2482 return get_cterm_attr_idx(attr, fg, bg);
2483 }
2484 return 0;
2485}
2486
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002487 static void
2488set_dirty_snapshot(term_T *term)
2489{
2490 term->tl_dirty_snapshot = TRUE;
2491#ifdef FEAT_TIMERS
2492 if (!term->tl_normal_mode)
2493 {
2494 /* Update the snapshot after 100 msec of not getting updates. */
2495 profile_setlimit(100L, &term->tl_timer_due);
2496 term->tl_timer_set = TRUE;
2497 }
2498#endif
2499}
2500
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002501 static int
2502handle_damage(VTermRect rect, void *user)
2503{
2504 term_T *term = (term_T *)user;
2505
2506 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2507 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002508 set_dirty_snapshot(term);
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002509 redraw_buf_later(term->tl_buffer, SOME_VALID);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002510 return 1;
2511}
2512
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002513 static void
2514term_scroll_up(term_T *term, int start_row, int count)
2515{
2516 win_T *wp;
2517 VTermColor fg, bg;
2518 VTermScreenCellAttrs attr;
2519 int clear_attr;
2520
2521 /* Set the color to clear lines with. */
2522 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2523 &fg, &bg);
2524 vim_memset(&attr, 0, sizeof(attr));
2525 clear_attr = cell2attr(attr, fg, bg);
2526
2527 FOR_ALL_WINDOWS(wp)
2528 {
2529 if (wp->w_buffer == term->tl_buffer)
2530 win_del_lines(wp, start_row, count, FALSE, FALSE, clear_attr);
2531 }
2532}
2533
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002534 static int
2535handle_moverect(VTermRect dest, VTermRect src, void *user)
2536{
2537 term_T *term = (term_T *)user;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002538 int count = src.start_row - dest.start_row;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002539
2540 /* Scrolling up is done much more efficiently by deleting lines instead of
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002541 * redrawing the text. But avoid doing this multiple times, postpone until
2542 * the redraw happens. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002543 if (dest.start_col == src.start_col
2544 && dest.end_col == src.end_col
2545 && dest.start_row < src.start_row)
2546 {
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002547 if (dest.start_row == 0)
2548 term->tl_postponed_scroll += count;
2549 else
2550 term_scroll_up(term, dest.start_row, count);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002551 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002552
2553 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2554 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002555 set_dirty_snapshot(term);
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002556
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02002557 /* Note sure if the scrolling will work correctly, let's do a complete
2558 * redraw later. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002559 redraw_buf_later(term->tl_buffer, NOT_VALID);
2560 return 1;
2561}
2562
2563 static int
2564handle_movecursor(
2565 VTermPos pos,
2566 VTermPos oldpos UNUSED,
2567 int visible,
2568 void *user)
2569{
2570 term_T *term = (term_T *)user;
2571 win_T *wp;
2572
2573 term->tl_cursor_pos = pos;
2574 term->tl_cursor_visible = visible;
2575
2576 FOR_ALL_WINDOWS(wp)
2577 {
2578 if (wp->w_buffer == term->tl_buffer)
2579 position_cursor(wp, &pos);
2580 }
2581 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2582 {
2583 may_toggle_cursor(term);
2584 update_cursor(term, term->tl_cursor_visible);
2585 }
2586
2587 return 1;
2588}
2589
2590 static int
2591handle_settermprop(
2592 VTermProp prop,
2593 VTermValue *value,
2594 void *user)
2595{
2596 term_T *term = (term_T *)user;
2597
2598 switch (prop)
2599 {
2600 case VTERM_PROP_TITLE:
2601 vim_free(term->tl_title);
2602 /* a blank title isn't useful, make it empty, so that "running" is
2603 * displayed */
2604 if (*skipwhite((char_u *)value->string) == NUL)
2605 term->tl_title = NULL;
2606#ifdef WIN3264
2607 else if (!enc_utf8 && enc_codepage > 0)
2608 {
2609 WCHAR *ret = NULL;
2610 int length = 0;
2611
2612 MultiByteToWideChar_alloc(CP_UTF8, 0,
2613 (char*)value->string, (int)STRLEN(value->string),
2614 &ret, &length);
2615 if (ret != NULL)
2616 {
2617 WideCharToMultiByte_alloc(enc_codepage, 0,
2618 ret, length, (char**)&term->tl_title,
2619 &length, 0, 0);
2620 vim_free(ret);
2621 }
2622 }
2623#endif
2624 else
2625 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002626 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 if (term == curbuf->b_term)
2628 maketitle();
2629 break;
2630
2631 case VTERM_PROP_CURSORVISIBLE:
2632 term->tl_cursor_visible = value->boolean;
2633 may_toggle_cursor(term);
2634 out_flush();
2635 break;
2636
2637 case VTERM_PROP_CURSORBLINK:
2638 term->tl_cursor_blink = value->boolean;
2639 may_set_cursor_props(term);
2640 break;
2641
2642 case VTERM_PROP_CURSORSHAPE:
2643 term->tl_cursor_shape = value->number;
2644 may_set_cursor_props(term);
2645 break;
2646
2647 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002648 if (desired_cursor_color == term->tl_cursor_color)
2649 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650 vim_free(term->tl_cursor_color);
2651 if (*value->string == NUL)
2652 term->tl_cursor_color = NULL;
2653 else
2654 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2655 may_set_cursor_props(term);
2656 break;
2657
2658 case VTERM_PROP_ALTSCREEN:
2659 /* TODO: do anything else? */
2660 term->tl_using_altscreen = value->boolean;
2661 break;
2662
2663 default:
2664 break;
2665 }
2666 /* Always return 1, otherwise vterm doesn't store the value internally. */
2667 return 1;
2668}
2669
2670/*
2671 * The job running in the terminal resized the terminal.
2672 */
2673 static int
2674handle_resize(int rows, int cols, void *user)
2675{
2676 term_T *term = (term_T *)user;
2677 win_T *wp;
2678
2679 term->tl_rows = rows;
2680 term->tl_cols = cols;
2681 if (term->tl_vterm_size_changed)
2682 /* Size was set by vterm_set_size(), don't set the window size. */
2683 term->tl_vterm_size_changed = FALSE;
2684 else
2685 {
2686 FOR_ALL_WINDOWS(wp)
2687 {
2688 if (wp->w_buffer == term->tl_buffer)
2689 {
2690 win_setheight_win(rows, wp);
2691 win_setwidth_win(cols, wp);
2692 }
2693 }
2694 redraw_buf_later(term->tl_buffer, NOT_VALID);
2695 }
2696 return 1;
2697}
2698
2699/*
2700 * Handle a line that is pushed off the top of the screen.
2701 */
2702 static int
2703handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2704{
2705 term_T *term = (term_T *)user;
2706
Bram Moolenaar56bc8e22018-05-10 18:05:56 +02002707 /* First remove the lines that were appended before, the pushed line goes
2708 * above it. */
2709 cleanup_scrollback(term);
2710
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002711 /* If the number of lines that are stored goes over 'termscrollback' then
2712 * delete the first 10%. */
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002713 if (term->tl_scrollback.ga_len >= term->tl_buffer->b_p_twsl)
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002714 {
Bram Moolenaar6d150f72018-04-21 20:03:20 +02002715 int todo = term->tl_buffer->b_p_twsl / 10;
Bram Moolenaar8c041b62018-04-14 18:14:06 +02002716 int i;
2717
2718 curbuf = term->tl_buffer;
2719 for (i = 0; i < todo; ++i)
2720 {
2721 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
2722 ml_delete(1, FALSE);
2723 }
2724 curbuf = curwin->w_buffer;
2725
2726 term->tl_scrollback.ga_len -= todo;
2727 mch_memmove(term->tl_scrollback.ga_data,
2728 (sb_line_T *)term->tl_scrollback.ga_data + todo,
2729 sizeof(sb_line_T) * term->tl_scrollback.ga_len);
2730 }
2731
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002732 if (ga_grow(&term->tl_scrollback, 1) == OK)
2733 {
2734 cellattr_T *p = NULL;
2735 int len = 0;
2736 int i;
2737 int c;
2738 int col;
2739 sb_line_T *line;
2740 garray_T ga;
2741 cellattr_T fill_attr = term->tl_default_color;
2742
2743 /* do not store empty cells at the end */
2744 for (i = 0; i < cols; ++i)
2745 if (cells[i].chars[0] != 0)
2746 len = i + 1;
2747 else
2748 cell2cellattr(&cells[i], &fill_attr);
2749
2750 ga_init2(&ga, 1, 100);
2751 if (len > 0)
2752 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2753 if (p != NULL)
2754 {
2755 for (col = 0; col < len; col += cells[col].width)
2756 {
2757 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2758 {
2759 ga.ga_len = 0;
2760 break;
2761 }
2762 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2763 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2764 (char_u *)ga.ga_data + ga.ga_len);
2765 cell2cellattr(&cells[col], &p[col]);
2766 }
2767 }
2768 if (ga_grow(&ga, 1) == FAIL)
2769 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2770 else
2771 {
2772 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2773 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2774 }
2775 ga_clear(&ga);
2776
2777 line = (sb_line_T *)term->tl_scrollback.ga_data
2778 + term->tl_scrollback.ga_len;
2779 line->sb_cols = len;
2780 line->sb_cells = p;
2781 line->sb_fill_attr = fill_attr;
2782 ++term->tl_scrollback.ga_len;
2783 ++term->tl_scrollback_scrolled;
2784 }
2785 return 0; /* ignored */
2786}
2787
2788static VTermScreenCallbacks screen_callbacks = {
2789 handle_damage, /* damage */
2790 handle_moverect, /* moverect */
2791 handle_movecursor, /* movecursor */
2792 handle_settermprop, /* settermprop */
2793 NULL, /* bell */
2794 handle_resize, /* resize */
2795 handle_pushline, /* sb_pushline */
2796 NULL /* sb_popline */
2797};
2798
2799/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002800 * Do the work after the channel of a terminal was closed.
2801 * Must be called only when updating_screen is FALSE.
2802 * Returns TRUE when a buffer was closed (list of terminals may have changed).
2803 */
2804 static int
2805term_after_channel_closed(term_T *term)
2806{
2807 /* Unless in Terminal-Normal mode: clear the vterm. */
2808 if (!term->tl_normal_mode)
2809 {
2810 int fnum = term->tl_buffer->b_fnum;
2811
2812 cleanup_vterm(term);
2813
2814 if (term->tl_finish == TL_FINISH_CLOSE)
2815 {
2816 aco_save_T aco;
2817
2818 /* ++close or term_finish == "close" */
2819 ch_log(NULL, "terminal job finished, closing window");
2820 aucmd_prepbuf(&aco, term->tl_buffer);
2821 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
2822 aucmd_restbuf(&aco);
2823 return TRUE;
2824 }
2825 if (term->tl_finish == TL_FINISH_OPEN
2826 && term->tl_buffer->b_nwindows == 0)
2827 {
2828 char buf[50];
2829
2830 /* TODO: use term_opencmd */
2831 ch_log(NULL, "terminal job finished, opening window");
2832 vim_snprintf(buf, sizeof(buf),
2833 term->tl_opencmd == NULL
2834 ? "botright sbuf %d"
2835 : (char *)term->tl_opencmd, fnum);
2836 do_cmdline_cmd((char_u *)buf);
2837 }
2838 else
2839 ch_log(NULL, "terminal job finished");
2840 }
2841
2842 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2843 return FALSE;
2844}
2845
2846/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002847 * Called when a channel has been closed.
2848 * If this was a channel for a terminal window then finish it up.
2849 */
2850 void
2851term_channel_closed(channel_T *ch)
2852{
2853 term_T *term;
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002854 term_T *next_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002855 int did_one = FALSE;
2856
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002857 for (term = first_term; term != NULL; term = next_term)
2858 {
2859 next_term = term->tl_next;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002860 if (term->tl_job == ch->ch_job)
2861 {
2862 term->tl_channel_closed = TRUE;
2863 did_one = TRUE;
2864
Bram Moolenaard23a8232018-02-10 18:45:26 +01002865 VIM_CLEAR(term->tl_title);
2866 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar402c8392018-05-06 22:01:42 +02002867#ifdef WIN3264
2868 if (term->tl_out_fd != NULL)
2869 {
2870 fclose(term->tl_out_fd);
2871 term->tl_out_fd = NULL;
2872 }
2873#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002874
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002875 if (updating_screen)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002876 {
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002877 /* Cannot open or close windows now. Can happen when
2878 * 'lazyredraw' is set. */
2879 term->tl_channel_recently_closed = TRUE;
2880 continue;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002881 }
2882
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002883 if (term_after_channel_closed(term))
2884 next_term = first_term;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002885 }
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002886 }
2887
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002888 if (did_one)
2889 {
2890 redraw_statuslines();
2891
2892 /* Need to break out of vgetc(). */
2893 ins_char_typebuf(K_IGNORE);
2894 typebuf_was_filled = TRUE;
2895
2896 term = curbuf->b_term;
2897 if (term != NULL)
2898 {
2899 if (term->tl_job == ch->ch_job)
2900 maketitle();
2901 update_cursor(term, term->tl_cursor_visible);
2902 }
2903 }
2904}
2905
2906/*
Bram Moolenaar0cb8ac72018-05-11 22:01:51 +02002907 * To be called after resetting updating_screen: handle any terminal where the
2908 * channel was closed.
2909 */
2910 void
2911term_check_channel_closed_recently()
2912{
2913 term_T *term;
2914 term_T *next_term;
2915
2916 for (term = first_term; term != NULL; term = next_term)
2917 {
2918 next_term = term->tl_next;
2919 if (term->tl_channel_recently_closed)
2920 {
2921 term->tl_channel_recently_closed = FALSE;
2922 if (term_after_channel_closed(term))
2923 // start over, the list may have changed
2924 next_term = first_term;
2925 }
2926 }
2927}
2928
2929/*
Bram Moolenaar13568252018-03-16 20:46:58 +01002930 * Fill one screen line from a line of the terminal.
2931 * Advances "pos" to past the last column.
2932 */
2933 static void
2934term_line2screenline(VTermScreen *screen, VTermPos *pos, int max_col)
2935{
2936 int off = screen_get_current_line_off();
2937
2938 for (pos->col = 0; pos->col < max_col; )
2939 {
2940 VTermScreenCell cell;
2941 int c;
2942
2943 if (vterm_screen_get_cell(screen, *pos, &cell) == 0)
2944 vim_memset(&cell, 0, sizeof(cell));
2945
2946 c = cell.chars[0];
2947 if (c == NUL)
2948 {
2949 ScreenLines[off] = ' ';
2950 if (enc_utf8)
2951 ScreenLinesUC[off] = NUL;
2952 }
2953 else
2954 {
2955 if (enc_utf8)
2956 {
2957 int i;
2958
2959 /* composing chars */
2960 for (i = 0; i < Screen_mco
2961 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2962 {
2963 ScreenLinesC[i][off] = cell.chars[i + 1];
2964 if (cell.chars[i + 1] == 0)
2965 break;
2966 }
2967 if (c >= 0x80 || (Screen_mco > 0
2968 && ScreenLinesC[0][off] != 0))
2969 {
2970 ScreenLines[off] = ' ';
2971 ScreenLinesUC[off] = c;
2972 }
2973 else
2974 {
2975 ScreenLines[off] = c;
2976 ScreenLinesUC[off] = NUL;
2977 }
2978 }
2979#ifdef WIN3264
2980 else if (has_mbyte && c >= 0x80)
2981 {
2982 char_u mb[MB_MAXBYTES+1];
2983 WCHAR wc = c;
2984
2985 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2986 (char*)mb, 2, 0, 0) > 1)
2987 {
2988 ScreenLines[off] = mb[0];
2989 ScreenLines[off + 1] = mb[1];
2990 cell.width = mb_ptr2cells(mb);
2991 }
2992 else
2993 ScreenLines[off] = c;
2994 }
2995#endif
2996 else
2997 ScreenLines[off] = c;
2998 }
2999 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
3000
3001 ++pos->col;
3002 ++off;
3003 if (cell.width == 2)
3004 {
3005 if (enc_utf8)
3006 ScreenLinesUC[off] = NUL;
3007
3008 /* don't set the second byte to NUL for a DBCS encoding, it
3009 * has been set above */
3010 if (enc_utf8 || !has_mbyte)
3011 ScreenLines[off] = NUL;
3012
3013 ++pos->col;
3014 ++off;
3015 }
3016 }
3017}
3018
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003019#if defined(FEAT_GUI)
Bram Moolenaar13568252018-03-16 20:46:58 +01003020 static void
3021update_system_term(term_T *term)
3022{
3023 VTermPos pos;
3024 VTermScreen *screen;
3025
3026 if (term->tl_vterm == NULL)
3027 return;
3028 screen = vterm_obtain_screen(term->tl_vterm);
3029
3030 /* Scroll up to make more room for terminal lines if needed. */
3031 while (term->tl_toprow > 0
3032 && (Rows - term->tl_toprow) < term->tl_dirty_row_end)
3033 {
3034 int save_p_more = p_more;
3035
3036 p_more = FALSE;
3037 msg_row = Rows - 1;
3038 msg_puts((char_u *)"\n");
3039 p_more = save_p_more;
3040 --term->tl_toprow;
3041 }
3042
3043 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3044 && pos.row < Rows; ++pos.row)
3045 {
3046 if (pos.row < term->tl_rows)
3047 {
3048 int max_col = MIN(Columns, term->tl_cols);
3049
3050 term_line2screenline(screen, &pos, max_col);
3051 }
3052 else
3053 pos.col = 0;
3054
3055 screen_line(term->tl_toprow + pos.row, 0, pos.col, Columns, FALSE);
3056 }
3057
3058 term->tl_dirty_row_start = MAX_ROW;
3059 term->tl_dirty_row_end = 0;
3060 update_cursor(term, TRUE);
3061}
Bram Moolenaar4ac31ee2018-03-16 21:34:25 +01003062#endif
Bram Moolenaar13568252018-03-16 20:46:58 +01003063
3064/*
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003065 * Return TRUE if window "wp" is to be redrawn with term_update_window().
3066 * Returns FALSE when there is no terminal running in this window or it is in
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003067 * Terminal-Normal mode.
3068 */
3069 int
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003070term_do_update_window(win_T *wp)
3071{
3072 term_T *term = wp->w_buffer->b_term;
3073
3074 return term != NULL && term->tl_vterm != NULL && !term->tl_normal_mode;
3075}
3076
3077/*
3078 * Called to update a window that contains an active terminal.
3079 */
3080 void
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003081term_update_window(win_T *wp)
3082{
3083 term_T *term = wp->w_buffer->b_term;
3084 VTerm *vterm;
3085 VTermScreen *screen;
3086 VTermState *state;
3087 VTermPos pos;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003088 int rows, cols;
3089 int newrows, newcols;
3090 int minsize;
3091 win_T *twp;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003092
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003093 vterm = term->tl_vterm;
3094 screen = vterm_obtain_screen(vterm);
3095 state = vterm_obtain_state(vterm);
3096
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003097 /* We use NOT_VALID on a resize or scroll, redraw everything then. With
3098 * SOME_VALID only redraw what was marked dirty. */
3099 if (wp->w_redr_type > SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003100 {
3101 term->tl_dirty_row_start = 0;
3102 term->tl_dirty_row_end = MAX_ROW;
Bram Moolenaar6eddadf2018-05-06 16:40:16 +02003103
3104 if (term->tl_postponed_scroll > 0
3105 && term->tl_postponed_scroll < term->tl_rows / 3)
3106 /* Scrolling is usually faster than redrawing, when there are only
3107 * a few lines to scroll. */
3108 term_scroll_up(term, 0, term->tl_postponed_scroll);
3109 term->tl_postponed_scroll = 0;
Bram Moolenaar19a3d682017-10-02 21:54:59 +02003110 }
3111
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003112 /*
3113 * If the window was resized a redraw will be triggered and we get here.
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003114 * Adjust the size of the vterm unless 'termwinsize' specifies a fixed size.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003115 */
Bram Moolenaarb833c1e2018-05-05 16:36:06 +02003116 minsize = parse_termwinsize(wp, &rows, &cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003117
Bram Moolenaar498c2562018-04-15 23:45:15 +02003118 newrows = 99999;
3119 newcols = 99999;
3120 FOR_ALL_WINDOWS(twp)
3121 {
3122 /* When more than one window shows the same terminal, use the
3123 * smallest size. */
3124 if (twp->w_buffer == term->tl_buffer)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003125 {
Bram Moolenaar498c2562018-04-15 23:45:15 +02003126 newrows = MIN(newrows, twp->w_height);
3127 newcols = MIN(newcols, twp->w_width);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003128 }
Bram Moolenaar498c2562018-04-15 23:45:15 +02003129 }
3130 newrows = rows == 0 ? newrows : minsize ? MAX(rows, newrows) : rows;
3131 newcols = cols == 0 ? newcols : minsize ? MAX(cols, newcols) : cols;
3132
3133 if (term->tl_rows != newrows || term->tl_cols != newcols)
3134 {
3135
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003136
3137 term->tl_vterm_size_changed = TRUE;
Bram Moolenaar498c2562018-04-15 23:45:15 +02003138 vterm_set_size(vterm, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003139 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
Bram Moolenaar498c2562018-04-15 23:45:15 +02003140 newrows);
3141 term_report_winsize(term, newrows, newcols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003142 }
3143
3144 /* The cursor may have been moved when resizing. */
3145 vterm_state_get_cursorpos(state, &pos);
3146 position_cursor(wp, &pos);
3147
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003148 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
3149 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003150 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003151 if (pos.row < term->tl_rows)
3152 {
Bram Moolenaar13568252018-03-16 20:46:58 +01003153 int max_col = MIN(wp->w_width, term->tl_cols);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003154
Bram Moolenaar13568252018-03-16 20:46:58 +01003155 term_line2screenline(screen, &pos, max_col);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003156 }
3157 else
3158 pos.col = 0;
3159
Bram Moolenaarf118d482018-03-13 13:14:00 +01003160 screen_line(wp->w_winrow + pos.row
3161#ifdef FEAT_MENU
3162 + winbar_height(wp)
3163#endif
3164 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003165 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02003166 term->tl_dirty_row_start = MAX_ROW;
3167 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003168}
3169
3170/*
3171 * Return TRUE if "wp" is a terminal window where the job has finished.
3172 */
3173 int
3174term_is_finished(buf_T *buf)
3175{
3176 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
3177}
3178
3179/*
3180 * Return TRUE if "wp" is a terminal window where the job has finished or we
3181 * are in Terminal-Normal mode, thus we show the buffer contents.
3182 */
3183 int
3184term_show_buffer(buf_T *buf)
3185{
3186 term_T *term = buf->b_term;
3187
3188 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
3189}
3190
3191/*
3192 * The current buffer is going to be changed. If there is terminal
3193 * highlighting remove it now.
3194 */
3195 void
3196term_change_in_curbuf(void)
3197{
3198 term_T *term = curbuf->b_term;
3199
3200 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
3201 {
3202 free_scrollback(term);
3203 redraw_buf_later(term->tl_buffer, NOT_VALID);
3204
3205 /* The buffer is now like a normal buffer, it cannot be easily
3206 * abandoned when changed. */
3207 set_string_option_direct((char_u *)"buftype", -1,
3208 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
3209 }
3210}
3211
3212/*
3213 * Get the screen attribute for a position in the buffer.
3214 * Use a negative "col" to get the filler background color.
3215 */
3216 int
3217term_get_attr(buf_T *buf, linenr_T lnum, int col)
3218{
3219 term_T *term = buf->b_term;
3220 sb_line_T *line;
3221 cellattr_T *cellattr;
3222
3223 if (lnum > term->tl_scrollback.ga_len)
3224 cellattr = &term->tl_default_color;
3225 else
3226 {
3227 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
3228 if (col < 0 || col >= line->sb_cols)
3229 cellattr = &line->sb_fill_attr;
3230 else
3231 cellattr = line->sb_cells + col;
3232 }
3233 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
3234}
3235
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003236/*
3237 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02003238 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003239 */
3240 static void
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003241cterm_color2vterm(int nr, VTermColor *rgb)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003242{
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003243 cterm_color2rgb(nr, &rgb->red, &rgb->green, &rgb->blue, &rgb->ansi_index);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003244}
3245
3246/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003247 * Initialize term->tl_default_color from the environment.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003248 */
3249 static void
Bram Moolenaar52acb112018-03-18 19:20:22 +01003250init_default_colors(term_T *term)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003251{
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003252 VTermColor *fg, *bg;
3253 int fgval, bgval;
3254 int id;
3255
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003256 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
3257 term->tl_default_color.width = 1;
3258 fg = &term->tl_default_color.fg;
3259 bg = &term->tl_default_color.bg;
3260
3261 /* Vterm uses a default black background. Set it to white when
3262 * 'background' is "light". */
3263 if (*p_bg == 'l')
3264 {
3265 fgval = 0;
3266 bgval = 255;
3267 }
3268 else
3269 {
3270 fgval = 255;
3271 bgval = 0;
3272 }
3273 fg->red = fg->green = fg->blue = fgval;
3274 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003275 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003276
3277 /* The "Terminal" highlight group overrules the defaults. */
3278 id = syn_name2id((char_u *)"Terminal");
3279
Bram Moolenaar46359e12017-11-29 22:33:38 +01003280 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003281#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3282 if (0
3283# ifdef FEAT_GUI
3284 || gui.in_use
3285# endif
3286# ifdef FEAT_TERMGUICOLORS
3287 || p_tgc
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003288# ifdef FEAT_VTP
3289 /* Finally get INVALCOLOR on this execution path */
3290 || (!p_tgc && t_colors >= 256)
3291# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003292# endif
3293 )
3294 {
3295 guicolor_T fg_rgb = INVALCOLOR;
3296 guicolor_T bg_rgb = INVALCOLOR;
3297
3298 if (id != 0)
3299 syn_id2colors(id, &fg_rgb, &bg_rgb);
3300
3301# ifdef FEAT_GUI
3302 if (gui.in_use)
3303 {
3304 if (fg_rgb == INVALCOLOR)
3305 fg_rgb = gui.norm_pixel;
3306 if (bg_rgb == INVALCOLOR)
3307 bg_rgb = gui.back_pixel;
3308 }
3309# ifdef FEAT_TERMGUICOLORS
3310 else
3311# endif
3312# endif
3313# ifdef FEAT_TERMGUICOLORS
3314 {
3315 if (fg_rgb == INVALCOLOR)
3316 fg_rgb = cterm_normal_fg_gui_color;
3317 if (bg_rgb == INVALCOLOR)
3318 bg_rgb = cterm_normal_bg_gui_color;
3319 }
3320# endif
3321 if (fg_rgb != INVALCOLOR)
3322 {
3323 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
3324
3325 fg->red = (unsigned)(rgb >> 16);
3326 fg->green = (unsigned)(rgb >> 8) & 255;
3327 fg->blue = (unsigned)rgb & 255;
3328 }
3329 if (bg_rgb != INVALCOLOR)
3330 {
3331 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
3332
3333 bg->red = (unsigned)(rgb >> 16);
3334 bg->green = (unsigned)(rgb >> 8) & 255;
3335 bg->blue = (unsigned)rgb & 255;
3336 }
3337 }
3338 else
3339#endif
3340 if (id != 0 && t_colors >= 16)
3341 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003342 if (term_default_cterm_fg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003343 cterm_color2vterm(term_default_cterm_fg, fg);
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003344 if (term_default_cterm_bg >= 0)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003345 cterm_color2vterm(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003346 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003347 else
3348 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003349#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003350 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003351#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003352
3353 /* In an MS-Windows console we know the normal colors. */
3354 if (cterm_normal_fg_color > 0)
3355 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003356 cterm_color2vterm(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003357# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003358 tmp = fg->red;
3359 fg->red = fg->blue;
3360 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003361# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003362 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003363# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003364 else
3365 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003366# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003367
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003368 if (cterm_normal_bg_color > 0)
3369 {
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02003370 cterm_color2vterm(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003371# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003372 tmp = bg->red;
3373 bg->red = bg->blue;
3374 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003375# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003376 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003377# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003378 else
3379 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003380# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003381 }
Bram Moolenaar52acb112018-03-18 19:20:22 +01003382}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003384#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
3385/*
3386 * Set the 16 ANSI colors from array of RGB values
3387 */
3388 static void
3389set_vterm_palette(VTerm *vterm, long_u *rgb)
3390{
3391 int index = 0;
3392 VTermState *state = vterm_obtain_state(vterm);
3393 for (; index < 16; index++)
3394 {
3395 VTermColor color;
3396 color.red = (unsigned)(rgb[index] >> 16);
3397 color.green = (unsigned)(rgb[index] >> 8) & 255;
3398 color.blue = (unsigned)rgb[index] & 255;
3399 vterm_state_set_palette_color(state, index, &color);
3400 }
3401}
3402
3403/*
3404 * Set the ANSI color palette from a list of colors
3405 */
3406 static int
3407set_ansi_colors_list(VTerm *vterm, list_T *list)
3408{
3409 int n = 0;
3410 long_u rgb[16];
3411 listitem_T *li = list->lv_first;
3412
3413 for (; li != NULL && n < 16; li = li->li_next, n++)
3414 {
3415 char_u *color_name;
3416 guicolor_T guicolor;
3417
3418 color_name = get_tv_string_chk(&li->li_tv);
3419 if (color_name == NULL)
3420 return FAIL;
3421
3422 guicolor = GUI_GET_COLOR(color_name);
3423 if (guicolor == INVALCOLOR)
3424 return FAIL;
3425
3426 rgb[n] = GUI_MCH_GET_RGB(guicolor);
3427 }
3428
3429 if (n != 16 || li != NULL)
3430 return FAIL;
3431
3432 set_vterm_palette(vterm, rgb);
3433
3434 return OK;
3435}
3436
3437/*
3438 * Initialize the ANSI color palette from g:terminal_ansi_colors[0:15]
3439 */
3440 static void
3441init_vterm_ansi_colors(VTerm *vterm)
3442{
3443 dictitem_T *var = find_var((char_u *)"g:terminal_ansi_colors", NULL, TRUE);
3444
3445 if (var != NULL
3446 && (var->di_tv.v_type != VAR_LIST
3447 || var->di_tv.vval.v_list == NULL
3448 || set_ansi_colors_list(vterm, var->di_tv.vval.v_list) == FAIL))
3449 EMSG2(_(e_invarg2), "g:terminal_ansi_colors");
3450}
3451#endif
3452
Bram Moolenaar52acb112018-03-18 19:20:22 +01003453/*
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003454 * Handles a "drop" command from the job in the terminal.
3455 * "item" is the file name, "item->li_next" may have options.
3456 */
3457 static void
3458handle_drop_command(listitem_T *item)
3459{
3460 char_u *fname = get_tv_string(&item->li_tv);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003461 listitem_T *opt_item = item->li_next;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003462 int bufnr;
3463 win_T *wp;
3464 tabpage_T *tp;
3465 exarg_T ea;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003466 char_u *tofree = NULL;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003467
3468 bufnr = buflist_add(fname, BLN_LISTED | BLN_NOOPT);
3469 FOR_ALL_TAB_WINDOWS(tp, wp)
3470 {
3471 if (wp->w_buffer->b_fnum == bufnr)
3472 {
3473 /* buffer is in a window already, go there */
3474 goto_tabpage_win(tp, wp);
3475 return;
3476 }
3477 }
3478
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003479 vim_memset(&ea, 0, sizeof(ea));
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003480
3481 if (opt_item != NULL && opt_item->li_tv.v_type == VAR_DICT
3482 && opt_item->li_tv.vval.v_dict != NULL)
3483 {
3484 dict_T *dict = opt_item->li_tv.vval.v_dict;
3485 char_u *p;
3486
3487 p = get_dict_string(dict, (char_u *)"ff", FALSE);
3488 if (p == NULL)
3489 p = get_dict_string(dict, (char_u *)"fileformat", FALSE);
3490 if (p != NULL)
3491 {
3492 if (check_ff_value(p) == FAIL)
3493 ch_log(NULL, "Invalid ff argument to drop: %s", p);
3494 else
3495 ea.force_ff = *p;
3496 }
3497 p = get_dict_string(dict, (char_u *)"enc", FALSE);
3498 if (p == NULL)
3499 p = get_dict_string(dict, (char_u *)"encoding", FALSE);
3500 if (p != NULL)
3501 {
Bram Moolenaar3aa67fb2018-04-05 21:04:15 +02003502 ea.cmd = alloc((int)STRLEN(p) + 12);
Bram Moolenaar333b80a2018-04-04 22:57:29 +02003503 if (ea.cmd != NULL)
3504 {
3505 sprintf((char *)ea.cmd, "sbuf ++enc=%s", p);
3506 ea.force_enc = 11;
3507 tofree = ea.cmd;
3508 }
3509 }
3510
3511 p = get_dict_string(dict, (char_u *)"bad", FALSE);
3512 if (p != NULL)
3513 get_bad_opt(p, &ea);
3514
3515 if (dict_find(dict, (char_u *)"bin", -1) != NULL)
3516 ea.force_bin = FORCE_BIN;
3517 if (dict_find(dict, (char_u *)"binary", -1) != NULL)
3518 ea.force_bin = FORCE_BIN;
3519 if (dict_find(dict, (char_u *)"nobin", -1) != NULL)
3520 ea.force_bin = FORCE_NOBIN;
3521 if (dict_find(dict, (char_u *)"nobinary", -1) != NULL)
3522 ea.force_bin = FORCE_NOBIN;
3523 }
3524
3525 /* open in new window, like ":split fname" */
3526 if (ea.cmd == NULL)
3527 ea.cmd = (char_u *)"split";
3528 ea.arg = fname;
3529 ea.cmdidx = CMD_split;
3530 ex_splitview(&ea);
3531
3532 vim_free(tofree);
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003533}
3534
3535/*
3536 * Handles a function call from the job running in a terminal.
3537 * "item" is the function name, "item->li_next" has the arguments.
3538 */
3539 static void
3540handle_call_command(term_T *term, channel_T *channel, listitem_T *item)
3541{
3542 char_u *func;
3543 typval_T argvars[2];
3544 typval_T rettv;
3545 int doesrange;
3546
3547 if (item->li_next == NULL)
3548 {
3549 ch_log(channel, "Missing function arguments for call");
3550 return;
3551 }
3552 func = get_tv_string(&item->li_tv);
3553
Bram Moolenaar2a77d212018-03-26 21:38:52 +02003554 if (STRNCMP(func, "Tapi_", 5) != 0)
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003555 {
3556 ch_log(channel, "Invalid function name: %s", func);
3557 return;
3558 }
3559
3560 argvars[0].v_type = VAR_NUMBER;
3561 argvars[0].vval.v_number = term->tl_buffer->b_fnum;
3562 argvars[1] = item->li_next->li_tv;
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003563 if (call_func(func, (int)STRLEN(func), &rettv,
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003564 2, argvars, /* argv_func */ NULL,
3565 /* firstline */ 1, /* lastline */ 1,
3566 &doesrange, /* evaluate */ TRUE,
3567 /* partial */ NULL, /* selfdict */ NULL) == OK)
3568 {
3569 clear_tv(&rettv);
3570 ch_log(channel, "Function %s called", func);
3571 }
3572 else
3573 ch_log(channel, "Calling function %s failed", func);
3574}
3575
3576/*
3577 * Called by libvterm when it cannot recognize an OSC sequence.
3578 * We recognize a terminal API command.
3579 */
3580 static int
3581parse_osc(const char *command, size_t cmdlen, void *user)
3582{
3583 term_T *term = (term_T *)user;
3584 js_read_T reader;
3585 typval_T tv;
3586 channel_T *channel = term->tl_job == NULL ? NULL
3587 : term->tl_job->jv_channel;
3588
3589 /* We recognize only OSC 5 1 ; {command} */
3590 if (cmdlen < 3 || STRNCMP(command, "51;", 3) != 0)
3591 return 0; /* not handled */
3592
Bram Moolenaar878c96d2018-04-04 23:00:06 +02003593 reader.js_buf = vim_strnsave((char_u *)command + 3, (int)(cmdlen - 3));
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003594 if (reader.js_buf == NULL)
3595 return 1;
3596 reader.js_fill = NULL;
3597 reader.js_used = 0;
3598 if (json_decode(&reader, &tv, 0) == OK
3599 && tv.v_type == VAR_LIST
3600 && tv.vval.v_list != NULL)
3601 {
3602 listitem_T *item = tv.vval.v_list->lv_first;
3603
3604 if (item == NULL)
3605 ch_log(channel, "Missing command");
3606 else
3607 {
3608 char_u *cmd = get_tv_string(&item->li_tv);
3609
Bram Moolenaara997b452018-04-17 23:24:06 +02003610 /* Make sure an invoked command doesn't delete the buffer (and the
3611 * terminal) under our fingers. */
3612 ++term->tl_buffer->b_locked;
3613
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003614 item = item->li_next;
3615 if (item == NULL)
3616 ch_log(channel, "Missing argument for %s", cmd);
3617 else if (STRCMP(cmd, "drop") == 0)
3618 handle_drop_command(item);
3619 else if (STRCMP(cmd, "call") == 0)
3620 handle_call_command(term, channel, item);
3621 else
3622 ch_log(channel, "Invalid command received: %s", cmd);
Bram Moolenaara997b452018-04-17 23:24:06 +02003623 --term->tl_buffer->b_locked;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003624 }
3625 }
3626 else
3627 ch_log(channel, "Invalid JSON received");
3628
3629 vim_free(reader.js_buf);
3630 clear_tv(&tv);
3631 return 1;
3632}
3633
3634static VTermParserCallbacks parser_fallbacks = {
3635 NULL, /* text */
3636 NULL, /* control */
3637 NULL, /* escape */
3638 NULL, /* csi */
3639 parse_osc, /* osc */
3640 NULL, /* dcs */
3641 NULL /* resize */
3642};
3643
3644/*
Bram Moolenaar756ef112018-04-10 12:04:27 +02003645 * Use Vim's allocation functions for vterm so profiling works.
3646 */
3647 static void *
3648vterm_malloc(size_t size, void *data UNUSED)
3649{
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02003650 return alloc_clear((unsigned) size);
Bram Moolenaar756ef112018-04-10 12:04:27 +02003651}
3652
3653 static void
3654vterm_memfree(void *ptr, void *data UNUSED)
3655{
3656 vim_free(ptr);
3657}
3658
3659static VTermAllocatorFunctions vterm_allocator = {
3660 &vterm_malloc,
3661 &vterm_memfree
3662};
3663
3664/*
Bram Moolenaar52acb112018-03-18 19:20:22 +01003665 * Create a new vterm and initialize it.
3666 */
3667 static void
3668create_vterm(term_T *term, int rows, int cols)
3669{
3670 VTerm *vterm;
3671 VTermScreen *screen;
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003672 VTermState *state;
Bram Moolenaar52acb112018-03-18 19:20:22 +01003673 VTermValue value;
3674
Bram Moolenaar756ef112018-04-10 12:04:27 +02003675 vterm = vterm_new_with_allocator(rows, cols, &vterm_allocator, NULL);
Bram Moolenaar52acb112018-03-18 19:20:22 +01003676 term->tl_vterm = vterm;
3677 screen = vterm_obtain_screen(vterm);
3678 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
3679 /* TODO: depends on 'encoding'. */
3680 vterm_set_utf8(vterm, 1);
3681
3682 init_default_colors(term);
3683
3684 vterm_state_set_default_colors(
3685 vterm_obtain_state(vterm),
3686 &term->tl_default_color.fg,
3687 &term->tl_default_color.bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003688
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02003689 if (t_colors >= 16)
3690 vterm_state_set_bold_highbright(vterm_obtain_state(vterm), 1);
3691
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003692 /* Required to initialize most things. */
3693 vterm_screen_reset(screen, 1 /* hard */);
3694
3695 /* Allow using alternate screen. */
3696 vterm_screen_enable_altscreen(screen, 1);
3697
3698 /* For unix do not use a blinking cursor. In an xterm this causes the
3699 * cursor to blink if it's blinking in the xterm.
3700 * For Windows we respect the system wide setting. */
3701#ifdef WIN3264
3702 if (GetCaretBlinkTime() == INFINITE)
3703 value.boolean = 0;
3704 else
3705 value.boolean = 1;
3706#else
3707 value.boolean = 0;
3708#endif
Bram Moolenaar8fbaeb12018-03-25 18:20:17 +02003709 state = vterm_obtain_state(vterm);
3710 vterm_state_set_termprop(state, VTERM_PROP_CURSORBLINK, &value);
3711 vterm_state_set_unrecognised_fallbacks(state, &parser_fallbacks, term);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003712}
3713
3714/*
3715 * Return the text to show for the buffer name and status.
3716 */
3717 char_u *
3718term_get_status_text(term_T *term)
3719{
3720 if (term->tl_status_text == NULL)
3721 {
3722 char_u *txt;
3723 size_t len;
3724
3725 if (term->tl_normal_mode)
3726 {
3727 if (term_job_running(term))
3728 txt = (char_u *)_("Terminal");
3729 else
3730 txt = (char_u *)_("Terminal-finished");
3731 }
3732 else if (term->tl_title != NULL)
3733 txt = term->tl_title;
3734 else if (term_none_open(term))
3735 txt = (char_u *)_("active");
3736 else if (term_job_running(term))
3737 txt = (char_u *)_("running");
3738 else
3739 txt = (char_u *)_("finished");
3740 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3741 term->tl_status_text = alloc((int)len);
3742 if (term->tl_status_text != NULL)
3743 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3744 term->tl_buffer->b_fname, txt);
3745 }
3746 return term->tl_status_text;
3747}
3748
3749/*
3750 * Mark references in jobs of terminals.
3751 */
3752 int
3753set_ref_in_term(int copyID)
3754{
3755 int abort = FALSE;
3756 term_T *term;
3757 typval_T tv;
3758
3759 for (term = first_term; term != NULL; term = term->tl_next)
3760 if (term->tl_job != NULL)
3761 {
3762 tv.v_type = VAR_JOB;
3763 tv.vval.v_job = term->tl_job;
3764 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3765 }
3766 return abort;
3767}
3768
3769/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003770 * Cache "Terminal" highlight group colors.
3771 */
3772 void
3773set_terminal_default_colors(int cterm_fg, int cterm_bg)
3774{
3775 term_default_cterm_fg = cterm_fg - 1;
3776 term_default_cterm_bg = cterm_bg - 1;
3777}
3778
3779/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003780 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003781 * Returns NULL when the buffer is not for a terminal window and logs a message
3782 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003783 */
3784 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003785term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003786{
3787 buf_T *buf;
3788
3789 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3790 ++emsg_off;
3791 buf = get_buf_tv(&argvars[0], FALSE);
3792 --emsg_off;
3793 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003794 {
3795 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003796 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003797 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003798 return buf;
3799}
3800
Bram Moolenaard96ff162018-02-18 22:13:29 +01003801 static int
3802same_color(VTermColor *a, VTermColor *b)
3803{
3804 return a->red == b->red
3805 && a->green == b->green
3806 && a->blue == b->blue
3807 && a->ansi_index == b->ansi_index;
3808}
3809
3810 static void
3811dump_term_color(FILE *fd, VTermColor *color)
3812{
3813 fprintf(fd, "%02x%02x%02x%d",
3814 (int)color->red, (int)color->green, (int)color->blue,
3815 (int)color->ansi_index);
3816}
3817
3818/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003819 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003820 *
3821 * Each screen cell in full is:
3822 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3823 * {characters} is a space for an empty cell
3824 * For a double-width character "+" is changed to "*" and the next cell is
3825 * skipped.
3826 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3827 * when "&" use the same as the previous cell.
3828 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3829 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3830 * {color-idx} is a number from 0 to 255
3831 *
3832 * Screen cell with same width, attributes and color as the previous one:
3833 * |{characters}
3834 *
3835 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3836 *
3837 * Repeating the previous screen cell:
3838 * @{count}
3839 */
3840 void
3841f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3842{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003843 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003844 term_T *term;
3845 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003846 int max_height = 0;
3847 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003848 stat_T st;
3849 FILE *fd;
3850 VTermPos pos;
3851 VTermScreen *screen;
3852 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003853 VTermState *state;
3854 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003855
3856 if (check_restricted() || check_secure())
3857 return;
3858 if (buf == NULL)
3859 return;
3860 term = buf->b_term;
3861
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003862 if (argvars[2].v_type != VAR_UNKNOWN)
3863 {
3864 dict_T *d;
3865
3866 if (argvars[2].v_type != VAR_DICT)
3867 {
3868 EMSG(_(e_dictreq));
3869 return;
3870 }
3871 d = argvars[2].vval.v_dict;
3872 if (d != NULL)
3873 {
3874 max_height = get_dict_number(d, (char_u *)"rows");
3875 max_width = get_dict_number(d, (char_u *)"columns");
3876 }
3877 }
3878
Bram Moolenaard96ff162018-02-18 22:13:29 +01003879 fname = get_tv_string_chk(&argvars[1]);
3880 if (fname == NULL)
3881 return;
3882 if (mch_stat((char *)fname, &st) >= 0)
3883 {
3884 EMSG2(_("E953: File exists: %s"), fname);
3885 return;
3886 }
3887
Bram Moolenaard96ff162018-02-18 22:13:29 +01003888 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3889 {
3890 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3891 return;
3892 }
3893
3894 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3895
3896 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003897 state = vterm_obtain_state(term->tl_vterm);
3898 vterm_state_get_cursorpos(state, &cursor_pos);
3899
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003900 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3901 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003902 {
3903 int repeat = 0;
3904
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003905 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3906 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003907 {
3908 VTermScreenCell cell;
3909 int same_attr;
3910 int same_chars = TRUE;
3911 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003912 int is_cursor_pos = (pos.col == cursor_pos.col
3913 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003914
3915 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3916 vim_memset(&cell, 0, sizeof(cell));
3917
3918 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3919 {
Bram Moolenaar47015b82018-03-23 22:10:34 +01003920 int c = cell.chars[i];
3921 int pc = prev_cell.chars[i];
3922
3923 /* For the first character NUL is the same as space. */
3924 if (i == 0)
3925 {
3926 c = (c == NUL) ? ' ' : c;
3927 pc = (pc == NUL) ? ' ' : pc;
3928 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003929 if (cell.chars[i] != prev_cell.chars[i])
3930 same_chars = FALSE;
3931 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3932 break;
3933 }
3934 same_attr = vtermAttr2hl(cell.attrs)
3935 == vtermAttr2hl(prev_cell.attrs)
3936 && same_color(&cell.fg, &prev_cell.fg)
3937 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003938 if (same_chars && cell.width == prev_cell.width && same_attr
3939 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003940 {
3941 ++repeat;
3942 }
3943 else
3944 {
3945 if (repeat > 0)
3946 {
3947 fprintf(fd, "@%d", repeat);
3948 repeat = 0;
3949 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003950 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003951
3952 if (cell.chars[0] == NUL)
3953 fputs(" ", fd);
3954 else
3955 {
3956 char_u charbuf[10];
3957 int len;
3958
3959 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3960 && cell.chars[i] != NUL; ++i)
3961 {
Bram Moolenaarf06b0b62018-03-29 17:22:24 +02003962 len = utf_char2bytes(cell.chars[i], charbuf);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003963 fwrite(charbuf, len, 1, fd);
3964 }
3965 }
3966
3967 /* When only the characters differ we don't write anything, the
3968 * following "|", "@" or NL will indicate using the same
3969 * attributes. */
3970 if (cell.width != prev_cell.width || !same_attr)
3971 {
3972 if (cell.width == 2)
3973 {
3974 fputs("*", fd);
3975 ++pos.col;
3976 }
3977 else
3978 fputs("+", fd);
3979
3980 if (same_attr)
3981 {
3982 fputs("&", fd);
3983 }
3984 else
3985 {
3986 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3987 if (same_color(&cell.fg, &prev_cell.fg))
3988 fputs("&", fd);
3989 else
3990 {
3991 fputs("#", fd);
3992 dump_term_color(fd, &cell.fg);
3993 }
3994 if (same_color(&cell.bg, &prev_cell.bg))
3995 fputs("&", fd);
3996 else
3997 {
3998 fputs("#", fd);
3999 dump_term_color(fd, &cell.bg);
4000 }
4001 }
4002 }
4003
4004 prev_cell = cell;
4005 }
4006 }
4007 if (repeat > 0)
4008 fprintf(fd, "@%d", repeat);
4009 fputs("\n", fd);
4010 }
4011
4012 fclose(fd);
4013}
4014
4015/*
4016 * Called when a dump is corrupted. Put a breakpoint here when debugging.
4017 */
4018 static void
4019dump_is_corrupt(garray_T *gap)
4020{
4021 ga_concat(gap, (char_u *)"CORRUPT");
4022}
4023
4024 static void
4025append_cell(garray_T *gap, cellattr_T *cell)
4026{
4027 if (ga_grow(gap, 1) == OK)
4028 {
4029 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
4030 ++gap->ga_len;
4031 }
4032}
4033
4034/*
4035 * Read the dump file from "fd" and append lines to the current buffer.
4036 * Return the cell width of the longest line.
4037 */
4038 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01004039read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004040{
4041 int c;
4042 garray_T ga_text;
4043 garray_T ga_cell;
4044 char_u *prev_char = NULL;
4045 int attr = 0;
4046 cellattr_T cell;
4047 term_T *term = curbuf->b_term;
4048 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004049 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004050
4051 ga_init2(&ga_text, 1, 90);
4052 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
4053 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01004054 cursor_pos->row = -1;
4055 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004056
4057 c = fgetc(fd);
4058 for (;;)
4059 {
4060 if (c == EOF)
4061 break;
4062 if (c == '\n')
4063 {
4064 /* End of a line: append it to the buffer. */
4065 if (ga_text.ga_data == NULL)
4066 dump_is_corrupt(&ga_text);
4067 if (ga_grow(&term->tl_scrollback, 1) == OK)
4068 {
4069 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
4070 + term->tl_scrollback.ga_len;
4071
4072 if (max_cells < ga_cell.ga_len)
4073 max_cells = ga_cell.ga_len;
4074 line->sb_cols = ga_cell.ga_len;
4075 line->sb_cells = ga_cell.ga_data;
4076 line->sb_fill_attr = term->tl_default_color;
4077 ++term->tl_scrollback.ga_len;
4078 ga_init(&ga_cell);
4079
4080 ga_append(&ga_text, NUL);
4081 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4082 ga_text.ga_len, FALSE);
4083 }
4084 else
4085 ga_clear(&ga_cell);
4086 ga_text.ga_len = 0;
4087
4088 c = fgetc(fd);
4089 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01004090 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004091 {
4092 int prev_len = ga_text.ga_len;
4093
Bram Moolenaar9271d052018-02-25 21:39:46 +01004094 if (c == '>')
4095 {
4096 if (cursor_pos->row != -1)
4097 dump_is_corrupt(&ga_text); /* duplicate cursor */
4098 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
4099 cursor_pos->col = ga_cell.ga_len;
4100 }
4101
Bram Moolenaard96ff162018-02-18 22:13:29 +01004102 /* normal character(s) followed by "+", "*", "|", "@" or NL */
4103 c = fgetc(fd);
4104 if (c != EOF)
4105 ga_append(&ga_text, c);
4106 for (;;)
4107 {
4108 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01004109 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01004110 || c == EOF || c == '\n')
4111 break;
4112 ga_append(&ga_text, c);
4113 }
4114
4115 /* save the character for repeating it */
4116 vim_free(prev_char);
4117 if (ga_text.ga_data != NULL)
4118 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
4119 ga_text.ga_len - prev_len);
4120
Bram Moolenaar9271d052018-02-25 21:39:46 +01004121 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01004122 {
4123 /* use all attributes from previous cell */
4124 }
4125 else if (c == '+' || c == '*')
4126 {
4127 int is_bg;
4128
4129 cell.width = c == '+' ? 1 : 2;
4130
4131 c = fgetc(fd);
4132 if (c == '&')
4133 {
4134 /* use same attr as previous cell */
4135 c = fgetc(fd);
4136 }
4137 else if (isdigit(c))
4138 {
4139 /* get the decimal attribute */
4140 attr = 0;
4141 while (isdigit(c))
4142 {
4143 attr = attr * 10 + (c - '0');
4144 c = fgetc(fd);
4145 }
4146 hl2vtermAttr(attr, &cell);
4147 }
4148 else
4149 dump_is_corrupt(&ga_text);
4150
4151 /* is_bg == 0: fg, is_bg == 1: bg */
4152 for (is_bg = 0; is_bg <= 1; ++is_bg)
4153 {
4154 if (c == '&')
4155 {
4156 /* use same color as previous cell */
4157 c = fgetc(fd);
4158 }
4159 else if (c == '#')
4160 {
4161 int red, green, blue, index = 0;
4162
4163 c = fgetc(fd);
4164 red = hex2nr(c);
4165 c = fgetc(fd);
4166 red = (red << 4) + hex2nr(c);
4167 c = fgetc(fd);
4168 green = hex2nr(c);
4169 c = fgetc(fd);
4170 green = (green << 4) + hex2nr(c);
4171 c = fgetc(fd);
4172 blue = hex2nr(c);
4173 c = fgetc(fd);
4174 blue = (blue << 4) + hex2nr(c);
4175 c = fgetc(fd);
4176 if (!isdigit(c))
4177 dump_is_corrupt(&ga_text);
4178 while (isdigit(c))
4179 {
4180 index = index * 10 + (c - '0');
4181 c = fgetc(fd);
4182 }
4183
4184 if (is_bg)
4185 {
4186 cell.bg.red = red;
4187 cell.bg.green = green;
4188 cell.bg.blue = blue;
4189 cell.bg.ansi_index = index;
4190 }
4191 else
4192 {
4193 cell.fg.red = red;
4194 cell.fg.green = green;
4195 cell.fg.blue = blue;
4196 cell.fg.ansi_index = index;
4197 }
4198 }
4199 else
4200 dump_is_corrupt(&ga_text);
4201 }
4202 }
4203 else
4204 dump_is_corrupt(&ga_text);
4205
4206 append_cell(&ga_cell, &cell);
4207 }
4208 else if (c == '@')
4209 {
4210 if (prev_char == NULL)
4211 dump_is_corrupt(&ga_text);
4212 else
4213 {
4214 int count = 0;
4215
4216 /* repeat previous character, get the count */
4217 for (;;)
4218 {
4219 c = fgetc(fd);
4220 if (!isdigit(c))
4221 break;
4222 count = count * 10 + (c - '0');
4223 }
4224
4225 while (count-- > 0)
4226 {
4227 ga_concat(&ga_text, prev_char);
4228 append_cell(&ga_cell, &cell);
4229 }
4230 }
4231 }
4232 else
4233 {
4234 dump_is_corrupt(&ga_text);
4235 c = fgetc(fd);
4236 }
4237 }
4238
4239 if (ga_text.ga_len > 0)
4240 {
4241 /* trailing characters after last NL */
4242 dump_is_corrupt(&ga_text);
4243 ga_append(&ga_text, NUL);
4244 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
4245 ga_text.ga_len, FALSE);
4246 }
4247
4248 ga_clear(&ga_text);
4249 vim_free(prev_char);
4250
4251 return max_cells;
4252}
4253
4254/*
Bram Moolenaar4a696342018-04-05 18:45:26 +02004255 * Return an allocated string with at least "text_width" "=" characters and
4256 * "fname" inserted in the middle.
4257 */
4258 static char_u *
4259get_separator(int text_width, char_u *fname)
4260{
4261 int width = MAX(text_width, curwin->w_width);
4262 char_u *textline;
4263 int fname_size;
4264 char_u *p = fname;
4265 int i;
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004266 size_t off;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004267
Bram Moolenaard6b4f2d2018-04-10 18:26:27 +02004268 textline = alloc(width + (int)STRLEN(fname) + 1);
Bram Moolenaar4a696342018-04-05 18:45:26 +02004269 if (textline == NULL)
4270 return NULL;
4271
4272 fname_size = vim_strsize(fname);
4273 if (fname_size < width - 8)
4274 {
4275 /* enough room, don't use the full window width */
4276 width = MAX(text_width, fname_size + 8);
4277 }
4278 else if (fname_size > width - 8)
4279 {
4280 /* full name doesn't fit, use only the tail */
4281 p = gettail(fname);
4282 fname_size = vim_strsize(p);
4283 }
4284 /* skip characters until the name fits */
4285 while (fname_size > width - 8)
4286 {
4287 p += (*mb_ptr2len)(p);
4288 fname_size = vim_strsize(p);
4289 }
4290
4291 for (i = 0; i < (width - fname_size) / 2 - 1; ++i)
4292 textline[i] = '=';
4293 textline[i++] = ' ';
4294
4295 STRCPY(textline + i, p);
4296 off = STRLEN(textline);
4297 textline[off] = ' ';
4298 for (i = 1; i < (width - fname_size) / 2; ++i)
4299 textline[off + i] = '=';
4300 textline[off + i] = NUL;
4301
4302 return textline;
4303}
4304
4305/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01004306 * Common for "term_dumpdiff()" and "term_dumpload()".
4307 */
4308 static void
4309term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
4310{
4311 jobopt_T opt;
4312 buf_T *buf;
4313 char_u buf1[NUMBUFLEN];
4314 char_u buf2[NUMBUFLEN];
4315 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004316 char_u *fname2 = NULL;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004317 char_u *fname_tofree = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004318 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004319 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004320 char_u *textline = NULL;
4321
4322 /* First open the files. If this fails bail out. */
4323 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
4324 if (do_diff)
4325 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
4326 if (fname1 == NULL || (do_diff && fname2 == NULL))
4327 {
4328 EMSG(_(e_invarg));
4329 return;
4330 }
4331 fd1 = mch_fopen((char *)fname1, READBIN);
4332 if (fd1 == NULL)
4333 {
4334 EMSG2(_(e_notread), fname1);
4335 return;
4336 }
4337 if (do_diff)
4338 {
4339 fd2 = mch_fopen((char *)fname2, READBIN);
4340 if (fd2 == NULL)
4341 {
4342 fclose(fd1);
4343 EMSG2(_(e_notread), fname2);
4344 return;
4345 }
4346 }
4347
4348 init_job_options(&opt);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004349 if (argvars[do_diff ? 2 : 1].v_type != VAR_UNKNOWN
4350 && get_job_options(&argvars[do_diff ? 2 : 1], &opt, 0,
4351 JO2_TERM_NAME + JO2_TERM_COLS + JO2_TERM_ROWS
4352 + JO2_VERTICAL + JO2_CURWIN + JO2_NORESTORE) == FAIL)
4353 goto theend;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004354
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004355 if (opt.jo_term_name == NULL)
4356 {
Bram Moolenaarb571c632018-03-21 22:27:59 +01004357 size_t len = STRLEN(fname1) + 12;
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004358
Bram Moolenaarb571c632018-03-21 22:27:59 +01004359 fname_tofree = alloc((int)len);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004360 if (fname_tofree != NULL)
4361 {
4362 vim_snprintf((char *)fname_tofree, len, "dump diff %s", fname1);
4363 opt.jo_term_name = fname_tofree;
4364 }
4365 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004366
Bram Moolenaar13568252018-03-16 20:46:58 +01004367 buf = term_start(&argvars[0], NULL, &opt, TERM_START_NOJOB);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004368 if (buf != NULL && buf->b_term != NULL)
4369 {
4370 int i;
4371 linenr_T bot_lnum;
4372 linenr_T lnum;
4373 term_T *term = buf->b_term;
4374 int width;
4375 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004376 VTermPos cursor_pos1;
4377 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004378
Bram Moolenaar52acb112018-03-18 19:20:22 +01004379 init_default_colors(term);
4380
Bram Moolenaard96ff162018-02-18 22:13:29 +01004381 rettv->vval.v_number = buf->b_fnum;
4382
4383 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01004384 width = read_dump_file(fd1, &cursor_pos1);
4385
4386 /* position the cursor */
4387 if (cursor_pos1.row >= 0)
4388 {
4389 curwin->w_cursor.lnum = cursor_pos1.row + 1;
4390 coladvance(cursor_pos1.col);
4391 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01004392
4393 /* Delete the empty line that was in the empty buffer. */
4394 ml_delete(1, FALSE);
4395
4396 /* For term_dumpload() we are done here. */
4397 if (!do_diff)
4398 goto theend;
4399
4400 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
4401
Bram Moolenaar4a696342018-04-05 18:45:26 +02004402 textline = get_separator(width, fname1);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004403 if (textline == NULL)
4404 goto theend;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004405 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4406 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
4407 vim_free(textline);
4408
4409 textline = get_separator(width, fname2);
4410 if (textline == NULL)
4411 goto theend;
4412 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
4413 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004414 textline[width] = NUL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004415
4416 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01004417 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004418 if (width2 > width)
4419 {
4420 vim_free(textline);
4421 textline = alloc(width2 + 1);
4422 if (textline == NULL)
4423 goto theend;
4424 width = width2;
4425 textline[width] = NUL;
4426 }
4427 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
4428
4429 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
4430 {
4431 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
4432 {
4433 /* bottom part has fewer rows, fill with "-" */
4434 for (i = 0; i < width; ++i)
4435 textline[i] = '-';
4436 }
4437 else
4438 {
4439 char_u *line1;
4440 char_u *line2;
4441 char_u *p1;
4442 char_u *p2;
4443 int col;
4444 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4445 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
4446 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
4447 ->sb_cells;
4448
4449 /* Make a copy, getting the second line will invalidate it. */
4450 line1 = vim_strsave(ml_get(lnum));
4451 if (line1 == NULL)
4452 break;
4453 p1 = line1;
4454
4455 line2 = ml_get(lnum + bot_lnum);
4456 p2 = line2;
4457 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
4458 {
4459 int len1 = utfc_ptr2len(p1);
4460 int len2 = utfc_ptr2len(p2);
4461
4462 textline[col] = ' ';
4463 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01004464 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01004465 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01004466 else if (lnum == cursor_pos1.row + 1
4467 && col == cursor_pos1.col
4468 && (cursor_pos1.row != cursor_pos2.row
4469 || cursor_pos1.col != cursor_pos2.col))
4470 /* cursor in first but not in second */
4471 textline[col] = '>';
4472 else if (lnum == cursor_pos2.row + 1
4473 && col == cursor_pos2.col
4474 && (cursor_pos1.row != cursor_pos2.row
4475 || cursor_pos1.col != cursor_pos2.col))
4476 /* cursor in second but not in first */
4477 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01004478 else if (cellattr1 != NULL && cellattr2 != NULL)
4479 {
4480 if ((cellattr1 + col)->width
4481 != (cellattr2 + col)->width)
4482 textline[col] = 'w';
4483 else if (!same_color(&(cellattr1 + col)->fg,
4484 &(cellattr2 + col)->fg))
4485 textline[col] = 'f';
4486 else if (!same_color(&(cellattr1 + col)->bg,
4487 &(cellattr2 + col)->bg))
4488 textline[col] = 'b';
4489 else if (vtermAttr2hl((cellattr1 + col)->attrs)
4490 != vtermAttr2hl(((cellattr2 + col)->attrs)))
4491 textline[col] = 'a';
4492 }
4493 p1 += len1;
4494 p2 += len2;
4495 /* TODO: handle different width */
4496 }
4497 vim_free(line1);
4498
4499 while (col < width)
4500 {
4501 if (*p1 == NUL && *p2 == NUL)
4502 textline[col] = '?';
4503 else if (*p1 == NUL)
4504 {
4505 textline[col] = '+';
4506 p2 += utfc_ptr2len(p2);
4507 }
4508 else
4509 {
4510 textline[col] = '-';
4511 p1 += utfc_ptr2len(p1);
4512 }
4513 ++col;
4514 }
4515 }
4516 if (add_empty_scrollback(term, &term->tl_default_color,
4517 term->tl_top_diff_rows) == OK)
4518 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4519 ++bot_lnum;
4520 }
4521
4522 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
4523 {
4524 /* bottom part has more rows, fill with "+" */
4525 for (i = 0; i < width; ++i)
4526 textline[i] = '+';
4527 if (add_empty_scrollback(term, &term->tl_default_color,
4528 term->tl_top_diff_rows) == OK)
4529 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
4530 ++lnum;
4531 ++bot_lnum;
4532 }
4533
4534 term->tl_cols = width;
Bram Moolenaar4a696342018-04-05 18:45:26 +02004535
4536 /* looks better without wrapping */
4537 curwin->w_p_wrap = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004538 }
4539
4540theend:
4541 vim_free(textline);
Bram Moolenaar5a3a49e2018-03-20 18:35:53 +01004542 vim_free(fname_tofree);
Bram Moolenaard96ff162018-02-18 22:13:29 +01004543 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01004544 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01004545 fclose(fd2);
4546}
4547
4548/*
4549 * If the current buffer shows the output of term_dumpdiff(), swap the top and
4550 * bottom files.
4551 * Return FAIL when this is not possible.
4552 */
4553 int
4554term_swap_diff()
4555{
4556 term_T *term = curbuf->b_term;
4557 linenr_T line_count;
4558 linenr_T top_rows;
4559 linenr_T bot_rows;
4560 linenr_T bot_start;
4561 linenr_T lnum;
4562 char_u *p;
4563 sb_line_T *sb_line;
4564
4565 if (term == NULL
4566 || !term_is_finished(curbuf)
4567 || term->tl_top_diff_rows == 0
4568 || term->tl_scrollback.ga_len == 0)
4569 return FAIL;
4570
4571 line_count = curbuf->b_ml.ml_line_count;
4572 top_rows = term->tl_top_diff_rows;
4573 bot_rows = term->tl_bot_diff_rows;
4574 bot_start = line_count - bot_rows;
4575 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
4576
4577 /* move lines from top to above the bottom part */
4578 for (lnum = 1; lnum <= top_rows; ++lnum)
4579 {
4580 p = vim_strsave(ml_get(1));
4581 if (p == NULL)
4582 return OK;
4583 ml_append(bot_start, p, 0, FALSE);
4584 ml_delete(1, FALSE);
4585 vim_free(p);
4586 }
4587
4588 /* move lines from bottom to the top */
4589 for (lnum = 1; lnum <= bot_rows; ++lnum)
4590 {
4591 p = vim_strsave(ml_get(bot_start + lnum));
4592 if (p == NULL)
4593 return OK;
4594 ml_delete(bot_start + lnum, FALSE);
4595 ml_append(lnum - 1, p, 0, FALSE);
4596 vim_free(p);
4597 }
4598
4599 if (top_rows == bot_rows)
4600 {
4601 /* rows counts are equal, can swap cell properties */
4602 for (lnum = 0; lnum < top_rows; ++lnum)
4603 {
4604 sb_line_T temp;
4605
4606 temp = *(sb_line + lnum);
4607 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
4608 *(sb_line + bot_start + lnum) = temp;
4609 }
4610 }
4611 else
4612 {
4613 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
4614 sb_line_T *temp = (sb_line_T *)alloc((int)size);
4615
4616 /* need to copy cell properties into temp memory */
4617 if (temp != NULL)
4618 {
4619 mch_memmove(temp, term->tl_scrollback.ga_data, size);
4620 mch_memmove(term->tl_scrollback.ga_data,
4621 temp + bot_start,
4622 sizeof(sb_line_T) * bot_rows);
4623 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
4624 temp + top_rows,
4625 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
4626 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
4627 + line_count - top_rows,
4628 temp,
4629 sizeof(sb_line_T) * top_rows);
4630 vim_free(temp);
4631 }
4632 }
4633
4634 term->tl_top_diff_rows = bot_rows;
4635 term->tl_bot_diff_rows = top_rows;
4636
4637 update_screen(NOT_VALID);
4638 return OK;
4639}
4640
4641/*
4642 * "term_dumpdiff(filename, filename, options)" function
4643 */
4644 void
4645f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
4646{
4647 term_load_dump(argvars, rettv, TRUE);
4648}
4649
4650/*
4651 * "term_dumpload(filename, options)" function
4652 */
4653 void
4654f_term_dumpload(typval_T *argvars, typval_T *rettv)
4655{
4656 term_load_dump(argvars, rettv, FALSE);
4657}
4658
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004659/*
4660 * "term_getaltscreen(buf)" function
4661 */
4662 void
4663f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
4664{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004665 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004666
4667 if (buf == NULL)
4668 return;
4669 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
4670}
4671
4672/*
4673 * "term_getattr(attr, name)" function
4674 */
4675 void
4676f_term_getattr(typval_T *argvars, typval_T *rettv)
4677{
4678 int attr;
4679 size_t i;
4680 char_u *name;
4681
4682 static struct {
4683 char *name;
4684 int attr;
4685 } attrs[] = {
4686 {"bold", HL_BOLD},
4687 {"italic", HL_ITALIC},
4688 {"underline", HL_UNDERLINE},
4689 {"strike", HL_STRIKETHROUGH},
4690 {"reverse", HL_INVERSE},
4691 };
4692
4693 attr = get_tv_number(&argvars[0]);
4694 name = get_tv_string_chk(&argvars[1]);
4695 if (name == NULL)
4696 return;
4697
4698 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
4699 if (STRCMP(name, attrs[i].name) == 0)
4700 {
4701 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
4702 break;
4703 }
4704}
4705
4706/*
4707 * "term_getcursor(buf)" function
4708 */
4709 void
4710f_term_getcursor(typval_T *argvars, typval_T *rettv)
4711{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004712 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004713 term_T *term;
4714 list_T *l;
4715 dict_T *d;
4716
4717 if (rettv_list_alloc(rettv) == FAIL)
4718 return;
4719 if (buf == NULL)
4720 return;
4721 term = buf->b_term;
4722
4723 l = rettv->vval.v_list;
4724 list_append_number(l, term->tl_cursor_pos.row + 1);
4725 list_append_number(l, term->tl_cursor_pos.col + 1);
4726
4727 d = dict_alloc();
4728 if (d != NULL)
4729 {
4730 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
4731 dict_add_nr_str(d, "blink", blink_state_is_inverted()
4732 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
4733 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
4734 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
4735 ? (char_u *)"" : term->tl_cursor_color);
4736 list_append_dict(l, d);
4737 }
4738}
4739
4740/*
4741 * "term_getjob(buf)" function
4742 */
4743 void
4744f_term_getjob(typval_T *argvars, typval_T *rettv)
4745{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004746 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004747
4748 rettv->v_type = VAR_JOB;
4749 rettv->vval.v_job = NULL;
4750 if (buf == NULL)
4751 return;
4752
4753 rettv->vval.v_job = buf->b_term->tl_job;
4754 if (rettv->vval.v_job != NULL)
4755 ++rettv->vval.v_job->jv_refcount;
4756}
4757
4758 static int
4759get_row_number(typval_T *tv, term_T *term)
4760{
4761 if (tv->v_type == VAR_STRING
4762 && tv->vval.v_string != NULL
4763 && STRCMP(tv->vval.v_string, ".") == 0)
4764 return term->tl_cursor_pos.row;
4765 return (int)get_tv_number(tv) - 1;
4766}
4767
4768/*
4769 * "term_getline(buf, row)" function
4770 */
4771 void
4772f_term_getline(typval_T *argvars, typval_T *rettv)
4773{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004774 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004775 term_T *term;
4776 int row;
4777
4778 rettv->v_type = VAR_STRING;
4779 if (buf == NULL)
4780 return;
4781 term = buf->b_term;
4782 row = get_row_number(&argvars[1], term);
4783
4784 if (term->tl_vterm == NULL)
4785 {
4786 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4787
4788 /* vterm is finished, get the text from the buffer */
4789 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4790 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4791 }
4792 else
4793 {
4794 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4795 VTermRect rect;
4796 int len;
4797 char_u *p;
4798
4799 if (row < 0 || row >= term->tl_rows)
4800 return;
4801 len = term->tl_cols * MB_MAXBYTES + 1;
4802 p = alloc(len);
4803 if (p == NULL)
4804 return;
4805 rettv->vval.v_string = p;
4806
4807 rect.start_col = 0;
4808 rect.end_col = term->tl_cols;
4809 rect.start_row = row;
4810 rect.end_row = row + 1;
4811 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4812 }
4813}
4814
4815/*
4816 * "term_getscrolled(buf)" function
4817 */
4818 void
4819f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4820{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004821 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004822
4823 if (buf == NULL)
4824 return;
4825 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4826}
4827
4828/*
4829 * "term_getsize(buf)" function
4830 */
4831 void
4832f_term_getsize(typval_T *argvars, typval_T *rettv)
4833{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004834 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004835 list_T *l;
4836
4837 if (rettv_list_alloc(rettv) == FAIL)
4838 return;
4839 if (buf == NULL)
4840 return;
4841
4842 l = rettv->vval.v_list;
4843 list_append_number(l, buf->b_term->tl_rows);
4844 list_append_number(l, buf->b_term->tl_cols);
4845}
4846
4847/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02004848 * "term_setsize(buf, rows, cols)" function
4849 */
4850 void
4851f_term_setsize(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4852{
4853 buf_T *buf = term_get_buf(argvars, "term_setsize()");
4854 term_T *term;
4855 varnumber_T rows, cols;
4856
Bram Moolenaar6e72cd02018-04-14 21:31:35 +02004857 if (buf == NULL)
4858 {
4859 EMSG(_("E955: Not a terminal buffer"));
4860 return;
4861 }
4862 if (buf->b_term->tl_vterm == NULL)
Bram Moolenaara42d3632018-04-14 17:05:38 +02004863 return;
4864 term = buf->b_term;
4865 rows = get_tv_number(&argvars[1]);
4866 rows = rows <= 0 ? term->tl_rows : rows;
4867 cols = get_tv_number(&argvars[2]);
4868 cols = cols <= 0 ? term->tl_cols : cols;
4869 vterm_set_size(term->tl_vterm, rows, cols);
4870 /* handle_resize() will resize the windows */
4871
4872 /* Get and remember the size we ended up with. Update the pty. */
4873 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
4874 term_report_winsize(term, term->tl_rows, term->tl_cols);
4875}
4876
4877/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004878 * "term_getstatus(buf)" function
4879 */
4880 void
4881f_term_getstatus(typval_T *argvars, typval_T *rettv)
4882{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004883 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004884 term_T *term;
4885 char_u val[100];
4886
4887 rettv->v_type = VAR_STRING;
4888 if (buf == NULL)
4889 return;
4890 term = buf->b_term;
4891
4892 if (term_job_running(term))
4893 STRCPY(val, "running");
4894 else
4895 STRCPY(val, "finished");
4896 if (term->tl_normal_mode)
4897 STRCAT(val, ",normal");
4898 rettv->vval.v_string = vim_strsave(val);
4899}
4900
4901/*
4902 * "term_gettitle(buf)" function
4903 */
4904 void
4905f_term_gettitle(typval_T *argvars, typval_T *rettv)
4906{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004907 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004908
4909 rettv->v_type = VAR_STRING;
4910 if (buf == NULL)
4911 return;
4912
4913 if (buf->b_term->tl_title != NULL)
4914 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4915}
4916
4917/*
4918 * "term_gettty(buf)" function
4919 */
4920 void
4921f_term_gettty(typval_T *argvars, typval_T *rettv)
4922{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004923 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar9b50f362018-05-07 20:10:17 +02004924 char_u *p = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004925 int num = 0;
4926
4927 rettv->v_type = VAR_STRING;
4928 if (buf == NULL)
4929 return;
4930 if (argvars[1].v_type != VAR_UNKNOWN)
4931 num = get_tv_number(&argvars[1]);
4932
4933 switch (num)
4934 {
4935 case 0:
4936 if (buf->b_term->tl_job != NULL)
4937 p = buf->b_term->tl_job->jv_tty_out;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004938 break;
4939 case 1:
4940 if (buf->b_term->tl_job != NULL)
4941 p = buf->b_term->tl_job->jv_tty_in;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004942 break;
4943 default:
4944 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4945 return;
4946 }
4947 if (p != NULL)
4948 rettv->vval.v_string = vim_strsave(p);
4949}
4950
4951/*
4952 * "term_list()" function
4953 */
4954 void
4955f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4956{
4957 term_T *tp;
4958 list_T *l;
4959
4960 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4961 return;
4962
4963 l = rettv->vval.v_list;
4964 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4965 if (tp != NULL && tp->tl_buffer != NULL)
4966 if (list_append_number(l,
4967 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4968 return;
4969}
4970
4971/*
4972 * "term_scrape(buf, row)" function
4973 */
4974 void
4975f_term_scrape(typval_T *argvars, typval_T *rettv)
4976{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004977 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004978 VTermScreen *screen = NULL;
4979 VTermPos pos;
4980 list_T *l;
4981 term_T *term;
4982 char_u *p;
4983 sb_line_T *line;
4984
4985 if (rettv_list_alloc(rettv) == FAIL)
4986 return;
4987 if (buf == NULL)
4988 return;
4989 term = buf->b_term;
4990
4991 l = rettv->vval.v_list;
4992 pos.row = get_row_number(&argvars[1], term);
4993
4994 if (term->tl_vterm != NULL)
4995 {
4996 screen = vterm_obtain_screen(term->tl_vterm);
4997 p = NULL;
4998 line = NULL;
4999 }
5000 else
5001 {
5002 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
5003
5004 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
5005 return;
5006 p = ml_get_buf(buf, lnum + 1, FALSE);
5007 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
5008 }
5009
5010 for (pos.col = 0; pos.col < term->tl_cols; )
5011 {
5012 dict_T *dcell;
5013 int width;
5014 VTermScreenCellAttrs attrs;
5015 VTermColor fg, bg;
5016 char_u rgb[8];
5017 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
5018 int off = 0;
5019 int i;
5020
5021 if (screen == NULL)
5022 {
5023 cellattr_T *cellattr;
5024 int len;
5025
5026 /* vterm has finished, get the cell from scrollback */
5027 if (pos.col >= line->sb_cols)
5028 break;
5029 cellattr = line->sb_cells + pos.col;
5030 width = cellattr->width;
5031 attrs = cellattr->attrs;
5032 fg = cellattr->fg;
5033 bg = cellattr->bg;
5034 len = MB_PTR2LEN(p);
5035 mch_memmove(mbs, p, len);
5036 mbs[len] = NUL;
5037 p += len;
5038 }
5039 else
5040 {
5041 VTermScreenCell cell;
5042 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
5043 break;
5044 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
5045 {
5046 if (cell.chars[i] == 0)
5047 break;
5048 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
5049 }
5050 mbs[off] = NUL;
5051 width = cell.width;
5052 attrs = cell.attrs;
5053 fg = cell.fg;
5054 bg = cell.bg;
5055 }
5056 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01005057 if (dcell == NULL)
5058 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005059 list_append_dict(l, dcell);
5060
5061 dict_add_nr_str(dcell, "chars", 0, mbs);
5062
5063 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5064 fg.red, fg.green, fg.blue);
5065 dict_add_nr_str(dcell, "fg", 0, rgb);
5066 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
5067 bg.red, bg.green, bg.blue);
5068 dict_add_nr_str(dcell, "bg", 0, rgb);
5069
5070 dict_add_nr_str(dcell, "attr",
5071 cell2attr(attrs, fg, bg), NULL);
5072 dict_add_nr_str(dcell, "width", width, NULL);
5073
5074 ++pos.col;
5075 if (width == 2)
5076 ++pos.col;
5077 }
5078}
5079
5080/*
5081 * "term_sendkeys(buf, keys)" function
5082 */
5083 void
5084f_term_sendkeys(typval_T *argvars, typval_T *rettv)
5085{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005086 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005087 char_u *msg;
5088 term_T *term;
5089
5090 rettv->v_type = VAR_UNKNOWN;
5091 if (buf == NULL)
5092 return;
5093
5094 msg = get_tv_string_chk(&argvars[1]);
5095 if (msg == NULL)
5096 return;
5097 term = buf->b_term;
5098 if (term->tl_vterm == NULL)
5099 return;
5100
5101 while (*msg != NUL)
5102 {
5103 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02005104 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005105 }
5106}
5107
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005108#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS) || defined(PROTO)
5109/*
5110 * "term_getansicolors(buf)" function
5111 */
5112 void
5113f_term_getansicolors(typval_T *argvars, typval_T *rettv)
5114{
5115 buf_T *buf = term_get_buf(argvars, "term_getansicolors()");
5116 term_T *term;
5117 VTermState *state;
5118 VTermColor color;
5119 char_u hexbuf[10];
5120 int index;
5121 list_T *list;
5122
5123 if (rettv_list_alloc(rettv) == FAIL)
5124 return;
5125
5126 if (buf == NULL)
5127 return;
5128 term = buf->b_term;
5129 if (term->tl_vterm == NULL)
5130 return;
5131
5132 list = rettv->vval.v_list;
5133 state = vterm_obtain_state(term->tl_vterm);
5134 for (index = 0; index < 16; index++)
5135 {
5136 vterm_state_get_palette_color(state, index, &color);
5137 sprintf((char *)hexbuf, "#%02x%02x%02x",
5138 color.red, color.green, color.blue);
5139 if (list_append_string(list, hexbuf, 7) == FAIL)
5140 return;
5141 }
5142}
5143
5144/*
5145 * "term_setansicolors(buf, list)" function
5146 */
5147 void
5148f_term_setansicolors(typval_T *argvars, typval_T *rettv UNUSED)
5149{
5150 buf_T *buf = term_get_buf(argvars, "term_setansicolors()");
5151 term_T *term;
5152
5153 if (buf == NULL)
5154 return;
5155 term = buf->b_term;
5156 if (term->tl_vterm == NULL)
5157 return;
5158
5159 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
5160 {
5161 EMSG(_(e_listreq));
5162 return;
5163 }
5164
5165 if (set_ansi_colors_list(term->tl_vterm, argvars[1].vval.v_list) == FAIL)
5166 EMSG(_(e_invarg));
5167}
5168#endif
5169
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005170/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005171 * "term_setrestore(buf, command)" function
5172 */
5173 void
5174f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5175{
5176#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005177 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005178 term_T *term;
5179 char_u *cmd;
5180
5181 if (buf == NULL)
5182 return;
5183 term = buf->b_term;
5184 vim_free(term->tl_command);
5185 cmd = get_tv_string_chk(&argvars[1]);
5186 if (cmd != NULL)
5187 term->tl_command = vim_strsave(cmd);
5188 else
5189 term->tl_command = NULL;
5190#endif
5191}
5192
5193/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005194 * "term_setkill(buf, how)" function
5195 */
5196 void
5197f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
5198{
5199 buf_T *buf = term_get_buf(argvars, "term_setkill()");
5200 term_T *term;
5201 char_u *how;
5202
5203 if (buf == NULL)
5204 return;
5205 term = buf->b_term;
5206 vim_free(term->tl_kill);
5207 how = get_tv_string_chk(&argvars[1]);
5208 if (how != NULL)
5209 term->tl_kill = vim_strsave(how);
5210 else
5211 term->tl_kill = NULL;
5212}
5213
5214/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005215 * "term_start(command, options)" function
5216 */
5217 void
5218f_term_start(typval_T *argvars, typval_T *rettv)
5219{
5220 jobopt_T opt;
5221 buf_T *buf;
5222
5223 init_job_options(&opt);
5224 if (argvars[1].v_type != VAR_UNKNOWN
5225 && get_job_options(&argvars[1], &opt,
5226 JO_TIMEOUT_ALL + JO_STOPONEXIT
5227 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
5228 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
5229 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
5230 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01005231 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005232 + JO2_NORESTORE + JO2_TERM_KILL
5233 + JO2_ANSI_COLORS) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005234 return;
5235
Bram Moolenaar13568252018-03-16 20:46:58 +01005236 buf = term_start(&argvars[0], NULL, &opt, 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005237
5238 if (buf != NULL && buf->b_term != NULL)
5239 rettv->vval.v_number = buf->b_fnum;
5240}
5241
5242/*
5243 * "term_wait" function
5244 */
5245 void
5246f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
5247{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01005248 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005249
5250 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005251 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005252 if (buf->b_term->tl_job == NULL)
5253 {
5254 ch_log(NULL, "term_wait(): no job to wait for");
5255 return;
5256 }
5257 if (buf->b_term->tl_job->jv_channel == NULL)
5258 /* channel is closed, nothing to do */
5259 return;
5260
5261 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01005262 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005263 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
5264 {
5265 /* The job is dead, keep reading channel I/O until the channel is
5266 * closed. buf->b_term may become NULL if the terminal was closed while
5267 * waiting. */
5268 ch_log(NULL, "term_wait(): waiting for channel to close");
5269 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
5270 {
5271 mch_check_messages();
5272 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01005273 if (!buf_valid(buf))
5274 /* If the terminal is closed when the channel is closed the
5275 * buffer disappears. */
5276 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005277 ui_delay(10L, FALSE);
5278 }
5279 mch_check_messages();
5280 parse_queued_messages();
5281 }
5282 else
5283 {
5284 long wait = 10L;
5285
5286 mch_check_messages();
5287 parse_queued_messages();
5288
5289 /* Wait for some time for any channel I/O. */
5290 if (argvars[1].v_type != VAR_UNKNOWN)
5291 wait = get_tv_number(&argvars[1]);
5292 ui_delay(wait, TRUE);
5293 mch_check_messages();
5294
5295 /* Flushing messages on channels is hopefully sufficient.
5296 * TODO: is there a better way? */
5297 parse_queued_messages();
5298 }
5299}
5300
5301/*
5302 * Called when a channel has sent all the lines to a terminal.
5303 * Send a CTRL-D to mark the end of the text.
5304 */
5305 void
5306term_send_eof(channel_T *ch)
5307{
5308 term_T *term;
5309
5310 for (term = first_term; term != NULL; term = term->tl_next)
5311 if (term->tl_job == ch->ch_job)
5312 {
5313 if (term->tl_eof_chars != NULL)
5314 {
5315 channel_send(ch, PART_IN, term->tl_eof_chars,
5316 (int)STRLEN(term->tl_eof_chars), NULL);
5317 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
5318 }
5319# ifdef WIN3264
5320 else
5321 /* Default: CTRL-D */
5322 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
5323# endif
5324 }
5325}
5326
5327# if defined(WIN3264) || defined(PROTO)
5328
5329/**************************************
5330 * 2. MS-Windows implementation.
5331 */
5332
5333# ifndef PROTO
5334
5335#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
5336#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01005337#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005338
5339void* (*winpty_config_new)(UINT64, void*);
5340void* (*winpty_open)(void*, void*);
5341void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
5342BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
5343void (*winpty_config_set_mouse_mode)(void*, int);
5344void (*winpty_config_set_initial_size)(void*, int, int);
5345LPCWSTR (*winpty_conin_name)(void*);
5346LPCWSTR (*winpty_conout_name)(void*);
5347LPCWSTR (*winpty_conerr_name)(void*);
5348void (*winpty_free)(void*);
5349void (*winpty_config_free)(void*);
5350void (*winpty_spawn_config_free)(void*);
5351void (*winpty_error_free)(void*);
5352LPCWSTR (*winpty_error_msg)(void*);
5353BOOL (*winpty_set_size)(void*, int, int, void*);
5354HANDLE (*winpty_agent_process)(void*);
5355
5356#define WINPTY_DLL "winpty.dll"
5357
5358static HINSTANCE hWinPtyDLL = NULL;
5359# endif
5360
5361 static int
5362dyn_winpty_init(int verbose)
5363{
5364 int i;
5365 static struct
5366 {
5367 char *name;
5368 FARPROC *ptr;
5369 } winpty_entry[] =
5370 {
5371 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
5372 {"winpty_config_free", (FARPROC*)&winpty_config_free},
5373 {"winpty_config_new", (FARPROC*)&winpty_config_new},
5374 {"winpty_config_set_mouse_mode",
5375 (FARPROC*)&winpty_config_set_mouse_mode},
5376 {"winpty_config_set_initial_size",
5377 (FARPROC*)&winpty_config_set_initial_size},
5378 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
5379 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
5380 {"winpty_error_free", (FARPROC*)&winpty_error_free},
5381 {"winpty_free", (FARPROC*)&winpty_free},
5382 {"winpty_open", (FARPROC*)&winpty_open},
5383 {"winpty_spawn", (FARPROC*)&winpty_spawn},
5384 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
5385 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
5386 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
5387 {"winpty_set_size", (FARPROC*)&winpty_set_size},
5388 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
5389 {NULL, NULL}
5390 };
5391
5392 /* No need to initialize twice. */
5393 if (hWinPtyDLL)
5394 return OK;
5395 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
5396 * winpty.dll. */
5397 if (*p_winptydll != NUL)
5398 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
5399 if (!hWinPtyDLL)
5400 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
5401 if (!hWinPtyDLL)
5402 {
5403 if (verbose)
5404 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
5405 : (char_u *)WINPTY_DLL);
5406 return FAIL;
5407 }
5408 for (i = 0; winpty_entry[i].name != NULL
5409 && winpty_entry[i].ptr != NULL; ++i)
5410 {
5411 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
5412 winpty_entry[i].name)) == NULL)
5413 {
5414 if (verbose)
5415 EMSG2(_(e_loadfunc), winpty_entry[i].name);
5416 return FAIL;
5417 }
5418 }
5419
5420 return OK;
5421}
5422
5423/*
5424 * Create a new terminal of "rows" by "cols" cells.
5425 * Store a reference in "term".
5426 * Return OK or FAIL.
5427 */
5428 static int
5429term_and_job_init(
5430 term_T *term,
5431 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005432 char **argv UNUSED,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005433 jobopt_T *opt,
5434 jobopt_T *orig_opt)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005435{
5436 WCHAR *cmd_wchar = NULL;
5437 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005438 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005439 channel_T *channel = NULL;
5440 job_T *job = NULL;
5441 DWORD error;
5442 HANDLE jo = NULL;
5443 HANDLE child_process_handle;
5444 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01005445 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005446 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005447 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005448 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005449
5450 if (dyn_winpty_init(TRUE) == FAIL)
5451 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005452 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
5453 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005454
5455 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005456 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005457 cmd = argvar->vval.v_string;
5458 }
5459 else if (argvar->v_type == VAR_LIST)
5460 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005461 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005462 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005463 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005464 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005465 if (cmd == NULL || *cmd == NUL)
5466 {
5467 EMSG(_(e_invarg));
5468 goto failed;
5469 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005470
5471 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005472 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005473 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005474 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005475 if (opt->jo_cwd != NULL)
5476 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005477
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005478 win32_build_env(opt->jo_env, &ga_env, TRUE);
5479 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005480
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005481 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
5482 if (term->tl_winpty_config == NULL)
5483 goto failed;
5484
5485 winpty_config_set_mouse_mode(term->tl_winpty_config,
5486 WINPTY_MOUSE_MODE_FORCE);
5487 winpty_config_set_initial_size(term->tl_winpty_config,
5488 term->tl_cols, term->tl_rows);
5489 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
5490 if (term->tl_winpty == NULL)
5491 goto failed;
5492
5493 spawn_config = winpty_spawn_config_new(
5494 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
5495 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
5496 NULL,
5497 cmd_wchar,
5498 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005499 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005500 &winpty_err);
5501 if (spawn_config == NULL)
5502 goto failed;
5503
5504 channel = add_channel();
5505 if (channel == NULL)
5506 goto failed;
5507
5508 job = job_alloc();
5509 if (job == NULL)
5510 goto failed;
Bram Moolenaarebe74b72018-04-21 23:34:43 +02005511 if (argvar->v_type == VAR_STRING)
5512 {
5513 int argc;
5514
5515 build_argv_from_string(cmd, &job->jv_argv, &argc);
5516 }
5517 else
5518 {
5519 int argc;
5520
5521 build_argv_from_list(argvar->vval.v_list, &job->jv_argv, &argc);
5522 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005523
5524 if (opt->jo_set & JO_IN_BUF)
5525 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
5526
5527 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
5528 &child_thread_handle, &error, &winpty_err))
5529 goto failed;
5530
5531 channel_set_pipes(channel,
5532 (sock_T)CreateFileW(
5533 winpty_conin_name(term->tl_winpty),
5534 GENERIC_WRITE, 0, NULL,
5535 OPEN_EXISTING, 0, NULL),
5536 (sock_T)CreateFileW(
5537 winpty_conout_name(term->tl_winpty),
5538 GENERIC_READ, 0, NULL,
5539 OPEN_EXISTING, 0, NULL),
5540 (sock_T)CreateFileW(
5541 winpty_conerr_name(term->tl_winpty),
5542 GENERIC_READ, 0, NULL,
5543 OPEN_EXISTING, 0, NULL));
5544
5545 /* Write lines with CR instead of NL. */
5546 channel->ch_write_text_mode = TRUE;
5547
5548 jo = CreateJobObject(NULL, NULL);
5549 if (jo == NULL)
5550 goto failed;
5551
5552 if (!AssignProcessToJobObject(jo, child_process_handle))
5553 {
5554 /* Failed, switch the way to terminate process with TerminateProcess. */
5555 CloseHandle(jo);
5556 jo = NULL;
5557 }
5558
5559 winpty_spawn_config_free(spawn_config);
5560 vim_free(cmd_wchar);
5561 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005562 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005563
5564 create_vterm(term, term->tl_rows, term->tl_cols);
5565
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005566#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5567 if (opt->jo_set2 & JO2_ANSI_COLORS)
5568 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5569 else
5570 init_vterm_ansi_colors(term->tl_vterm);
5571#endif
5572
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005573 channel_set_job(channel, job, opt);
5574 job_set_options(job, opt);
5575
5576 job->jv_channel = channel;
5577 job->jv_proc_info.hProcess = child_process_handle;
5578 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
5579 job->jv_job_object = jo;
5580 job->jv_status = JOB_STARTED;
5581 job->jv_tty_in = utf16_to_enc(
5582 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
5583 job->jv_tty_out = utf16_to_enc(
5584 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
5585 ++job->jv_refcount;
5586 term->tl_job = job;
5587
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005588 /* Redirecting stdout and stderr doesn't work at the job level. Instead
5589 * open the file here and handle it in. opt->jo_io was changed in
5590 * setup_job_options(), use the original flags here. */
5591 if (orig_opt->jo_io[PART_OUT] == JIO_FILE)
5592 {
5593 char_u *fname = opt->jo_io_name[PART_OUT];
5594
5595 ch_log(channel, "Opening output file %s", fname);
5596 term->tl_out_fd = mch_fopen((char *)fname, WRITEBIN);
5597 if (term->tl_out_fd == NULL)
5598 EMSG2(_(e_notopen), fname);
5599 }
5600
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005601 return OK;
5602
5603failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01005604 ga_clear(&ga_cmd);
5605 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005606 vim_free(cmd_wchar);
5607 vim_free(cwd_wchar);
5608 if (spawn_config != NULL)
5609 winpty_spawn_config_free(spawn_config);
5610 if (channel != NULL)
5611 channel_clear(channel);
5612 if (job != NULL)
5613 {
5614 job->jv_channel = NULL;
5615 job_cleanup(job);
5616 }
5617 term->tl_job = NULL;
5618 if (jo != NULL)
5619 CloseHandle(jo);
5620 if (term->tl_winpty != NULL)
5621 winpty_free(term->tl_winpty);
5622 term->tl_winpty = NULL;
5623 if (term->tl_winpty_config != NULL)
5624 winpty_config_free(term->tl_winpty_config);
5625 term->tl_winpty_config = NULL;
5626 if (winpty_err != NULL)
5627 {
5628 char_u *msg = utf16_to_enc(
5629 (short_u *)winpty_error_msg(winpty_err), NULL);
5630
5631 EMSG(msg);
5632 winpty_error_free(winpty_err);
5633 }
5634 return FAIL;
5635}
5636
5637 static int
5638create_pty_only(term_T *term, jobopt_T *options)
5639{
5640 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
5641 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
5642 char in_name[80], out_name[80];
5643 channel_T *channel = NULL;
5644
5645 create_vterm(term, term->tl_rows, term->tl_cols);
5646
5647 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
5648 GetCurrentProcessId(),
5649 curbuf->b_fnum);
5650 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
5651 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5652 PIPE_UNLIMITED_INSTANCES,
5653 0, 0, NMPWAIT_NOWAIT, NULL);
5654 if (hPipeIn == INVALID_HANDLE_VALUE)
5655 goto failed;
5656
5657 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
5658 GetCurrentProcessId(),
5659 curbuf->b_fnum);
5660 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
5661 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
5662 PIPE_UNLIMITED_INSTANCES,
5663 0, 0, 0, NULL);
5664 if (hPipeOut == INVALID_HANDLE_VALUE)
5665 goto failed;
5666
5667 ConnectNamedPipe(hPipeIn, NULL);
5668 ConnectNamedPipe(hPipeOut, NULL);
5669
5670 term->tl_job = job_alloc();
5671 if (term->tl_job == NULL)
5672 goto failed;
5673 ++term->tl_job->jv_refcount;
5674
5675 /* behave like the job is already finished */
5676 term->tl_job->jv_status = JOB_FINISHED;
5677
5678 channel = add_channel();
5679 if (channel == NULL)
5680 goto failed;
5681 term->tl_job->jv_channel = channel;
5682 channel->ch_keep_open = TRUE;
5683 channel->ch_named_pipe = TRUE;
5684
5685 channel_set_pipes(channel,
5686 (sock_T)hPipeIn,
5687 (sock_T)hPipeOut,
5688 (sock_T)hPipeOut);
5689 channel_set_job(channel, term->tl_job, options);
5690 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
5691 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
5692
5693 return OK;
5694
5695failed:
5696 if (hPipeIn != NULL)
5697 CloseHandle(hPipeIn);
5698 if (hPipeOut != NULL)
5699 CloseHandle(hPipeOut);
5700 return FAIL;
5701}
5702
5703/*
5704 * Free the terminal emulator part of "term".
5705 */
5706 static void
5707term_free_vterm(term_T *term)
5708{
5709 if (term->tl_winpty != NULL)
5710 winpty_free(term->tl_winpty);
5711 term->tl_winpty = NULL;
5712 if (term->tl_winpty_config != NULL)
5713 winpty_config_free(term->tl_winpty_config);
5714 term->tl_winpty_config = NULL;
5715 if (term->tl_vterm != NULL)
5716 vterm_free(term->tl_vterm);
5717 term->tl_vterm = NULL;
5718}
5719
5720/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005721 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005722 */
5723 static void
5724term_report_winsize(term_T *term, int rows, int cols)
5725{
5726 if (term->tl_winpty)
5727 winpty_set_size(term->tl_winpty, cols, rows, NULL);
5728}
5729
5730 int
5731terminal_enabled(void)
5732{
5733 return dyn_winpty_init(FALSE) == OK;
5734}
5735
5736# else
5737
5738/**************************************
5739 * 3. Unix-like implementation.
5740 */
5741
5742/*
5743 * Create a new terminal of "rows" by "cols" cells.
5744 * Start job for "cmd".
5745 * Store the pointers in "term".
Bram Moolenaar13568252018-03-16 20:46:58 +01005746 * When "argv" is not NULL then "argvar" is not used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005747 * Return OK or FAIL.
5748 */
5749 static int
5750term_and_job_init(
5751 term_T *term,
5752 typval_T *argvar,
Bram Moolenaar13568252018-03-16 20:46:58 +01005753 char **argv,
Bram Moolenaarf25329c2018-05-06 21:49:32 +02005754 jobopt_T *opt,
5755 jobopt_T *orig_opt UNUSED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005756{
5757 create_vterm(term, term->tl_rows, term->tl_cols);
5758
Bram Moolenaarf59c6e82018-04-10 15:59:11 +02005759#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
5760 if (opt->jo_set2 & JO2_ANSI_COLORS)
5761 set_vterm_palette(term->tl_vterm, opt->jo_ansi_colors);
5762 else
5763 init_vterm_ansi_colors(term->tl_vterm);
5764#endif
5765
Bram Moolenaar13568252018-03-16 20:46:58 +01005766 /* This may change a string in "argvar". */
5767 term->tl_job = job_start(argvar, argv, opt);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005768 if (term->tl_job != NULL)
5769 ++term->tl_job->jv_refcount;
5770
5771 return term->tl_job != NULL
5772 && term->tl_job->jv_channel != NULL
5773 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
5774}
5775
5776 static int
5777create_pty_only(term_T *term, jobopt_T *opt)
5778{
5779 create_vterm(term, term->tl_rows, term->tl_cols);
5780
5781 term->tl_job = job_alloc();
5782 if (term->tl_job == NULL)
5783 return FAIL;
5784 ++term->tl_job->jv_refcount;
5785
5786 /* behave like the job is already finished */
5787 term->tl_job->jv_status = JOB_FINISHED;
5788
5789 return mch_create_pty_channel(term->tl_job, opt);
5790}
5791
5792/*
5793 * Free the terminal emulator part of "term".
5794 */
5795 static void
5796term_free_vterm(term_T *term)
5797{
5798 if (term->tl_vterm != NULL)
5799 vterm_free(term->tl_vterm);
5800 term->tl_vterm = NULL;
5801}
5802
5803/*
Bram Moolenaara42d3632018-04-14 17:05:38 +02005804 * Report the size to the terminal.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02005805 */
5806 static void
5807term_report_winsize(term_T *term, int rows, int cols)
5808{
5809 /* Use an ioctl() to report the new window size to the job. */
5810 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
5811 {
5812 int fd = -1;
5813 int part;
5814
5815 for (part = PART_OUT; part < PART_COUNT; ++part)
5816 {
5817 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
5818 if (isatty(fd))
5819 break;
5820 }
5821 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
5822 mch_signal_job(term->tl_job, (char_u *)"winch");
5823 }
5824}
5825
5826# endif
5827
5828#endif /* FEAT_TERMINAL */