blob: 53591f15c9708068f513d32b3f0a0a96ee31bc81 [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 Moolenaar46359e12017-11-29 22:33:38 +010041 * - When using 'termguicolors' still use the 16 ANSI colors as-is. Helps for
42 * a job that uses 16 colors while Vim is using > 256.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020043 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
44 * Higashi, 2017 Sep 19)
Bram Moolenaarede35bb2018-01-26 20:05:18 +010045 * - Trigger TerminalOpen event? #2422 patch in #2484
Bram Moolenaar3a497e12017-09-30 20:40:27 +020046 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020047 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
48 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020049 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaard96ff162018-02-18 22:13:29 +010050 * - What to store in a session file? Shell at the prompt would be OK to
51 * restore, but others may not. Open the window and let the user start the
52 * command? Also see #2650.
Bram Moolenaarba6febd2017-10-30 21:56:23 +010053 * - When closing gvim with an active terminal buffer, the dialog suggests
54 * saving the buffer. Should say something else. (Manas Thakur, #2215)
55 * Also: #2223
Bram Moolenaarba6febd2017-10-30 21:56:23 +010056 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020057 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaarff546792017-11-21 14:47:57 +010058 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020059 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010060 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar46359e12017-11-29 22:33:38 +010061 * - implement term_setsize()
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020062 * - add test for giving error for invalid 'termsize' value.
63 * - support minimal size when 'termsize' is "rows*cols".
64 * - support minimal size when 'termsize' is empty?
Bram Moolenaarede35bb2018-01-26 20:05:18 +010065 * - if the job in the terminal does not support the mouse, we can use the
66 * mouse in the Terminal window for copy/paste and scrolling.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067 * - GUI: when using tabs, focus in terminal, click on tab does not work.
68 * - GUI: when 'confirm' is set and trying to exit Vim, dialog offers to save
69 * changes to "!shell".
70 * (justrajdeep, 2017 Aug 22)
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020071 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020072 * - For the GUI fill termios with default values, perhaps like pangoterm:
73 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020074 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
75 * conversions.
76 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
77 * the window and position it higher up when it gets filled, so it looks like
78 * the text scrolls up.
79 * - Copy text in the vterm to the Vim buffer once in a while, so that
80 * completion works.
81 * - add an optional limit for the scrollback size. When reaching it remove
82 * 10% at the start.
83 */
84
85#include "vim.h"
86
87#if defined(FEAT_TERMINAL) || defined(PROTO)
88
89#ifndef MIN
90# define MIN(x,y) ((x) < (y) ? (x) : (y))
91#endif
92#ifndef MAX
93# define MAX(x,y) ((x) > (y) ? (x) : (y))
94#endif
95
96#include "libvterm/include/vterm.h"
97
98/* This is VTermScreenCell without the characters, thus much smaller. */
99typedef struct {
100 VTermScreenCellAttrs attrs;
101 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100102 VTermColor fg;
103 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200104} cellattr_T;
105
106typedef struct sb_line_S {
107 int sb_cols; /* can differ per line */
108 cellattr_T *sb_cells; /* allocated */
109 cellattr_T sb_fill_attr; /* for short line */
110} sb_line_T;
111
112/* typedef term_T in structs.h */
113struct terminal_S {
114 term_T *tl_next;
115
116 VTerm *tl_vterm;
117 job_T *tl_job;
118 buf_T *tl_buffer;
119
120 /* Set when setting the size of a vterm, reset after redrawing. */
121 int tl_vterm_size_changed;
122
123 /* used when tl_job is NULL and only a pty was created */
124 int tl_tty_fd;
125 char_u *tl_tty_in;
126 char_u *tl_tty_out;
127
128 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
129 int tl_channel_closed;
130 int tl_finish; /* 'c' for ++close, 'o' for ++open */
131 char_u *tl_opencmd;
132 char_u *tl_eof_chars;
133
134#ifdef WIN3264
135 void *tl_winpty_config;
136 void *tl_winpty;
137#endif
138
139 /* last known vterm size */
140 int tl_rows;
141 int tl_cols;
142 /* vterm size does not follow window size */
143 int tl_rows_fixed;
144 int tl_cols_fixed;
145
146 char_u *tl_title; /* NULL or allocated */
147 char_u *tl_status_text; /* NULL or allocated */
148
149 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200150 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200151 int tl_dirty_row_end; /* row below last one to update */
152
153 garray_T tl_scrollback;
154 int tl_scrollback_scrolled;
155 cellattr_T tl_default_color;
156
Bram Moolenaard96ff162018-02-18 22:13:29 +0100157 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
158 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
159
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200160 VTermPos tl_cursor_pos;
161 int tl_cursor_visible;
162 int tl_cursor_blink;
163 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
164 char_u *tl_cursor_color; /* NULL or allocated */
165
166 int tl_using_altscreen;
167};
168
169#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
170#define TMODE_LOOP 2 /* CTRL-W N used */
171
172/*
173 * List of all active terminals.
174 */
175static term_T *first_term = NULL;
176
177/* Terminal active in terminal_loop(). */
178static term_T *in_terminal_loop = NULL;
179
180#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
181#define KEY_BUF_LEN 200
182
183/*
184 * Functions with separate implementation for MS-Windows and Unix-like systems.
185 */
186static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
187static int create_pty_only(term_T *term, jobopt_T *opt);
188static void term_report_winsize(term_T *term, int rows, int cols);
189static void term_free_vterm(term_T *term);
190
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100191/* The character that we know (or assume) that the terminal expects for the
192 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200193static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200194
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100195/* "Terminal" highlight group colors. */
196static int term_default_cterm_fg = -1;
197static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200198
Bram Moolenaard317b382018-02-08 22:33:31 +0100199/* Store the last set and the desired cursor properties, so that we only update
200 * them when needed. Doing it unnecessary may result in flicker. */
201static char_u *last_set_cursor_color = (char_u *)"";
202static char_u *desired_cursor_color = (char_u *)"";
203static int last_set_cursor_shape = -1;
204static int desired_cursor_shape = -1;
205static int last_set_cursor_blink = -1;
206static int desired_cursor_blink = -1;
207
208
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200209/**************************************
210 * 1. Generic code for all systems.
211 */
212
213/*
214 * Determine the terminal size from 'termsize' and the current window.
215 * Assumes term->tl_rows and term->tl_cols are zero.
216 */
217 static void
218set_term_and_win_size(term_T *term)
219{
220 if (*curwin->w_p_tms != NUL)
221 {
222 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
223
224 term->tl_rows = atoi((char *)curwin->w_p_tms);
225 term->tl_cols = atoi((char *)p);
226 }
227 if (term->tl_rows == 0)
228 term->tl_rows = curwin->w_height;
229 else
230 {
231 win_setheight_win(term->tl_rows, curwin);
232 term->tl_rows_fixed = TRUE;
233 }
234 if (term->tl_cols == 0)
235 term->tl_cols = curwin->w_width;
236 else
237 {
238 win_setwidth_win(term->tl_cols, curwin);
239 term->tl_cols_fixed = TRUE;
240 }
241}
242
243/*
244 * Initialize job options for a terminal job.
245 * Caller may overrule some of them.
246 */
247 static void
248init_job_options(jobopt_T *opt)
249{
250 clear_job_options(opt);
251
252 opt->jo_mode = MODE_RAW;
253 opt->jo_out_mode = MODE_RAW;
254 opt->jo_err_mode = MODE_RAW;
255 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
256}
257
258/*
259 * Set job options mandatory for a terminal job.
260 */
261 static void
262setup_job_options(jobopt_T *opt, int rows, int cols)
263{
264 if (!(opt->jo_set & JO_OUT_IO))
265 {
266 /* Connect stdout to the terminal. */
267 opt->jo_io[PART_OUT] = JIO_BUFFER;
268 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
269 opt->jo_modifiable[PART_OUT] = 0;
270 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
271 }
272
273 if (!(opt->jo_set & JO_ERR_IO))
274 {
275 /* Connect stderr to the terminal. */
276 opt->jo_io[PART_ERR] = JIO_BUFFER;
277 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
278 opt->jo_modifiable[PART_ERR] = 0;
279 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
280 }
281
282 opt->jo_pty = TRUE;
283 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
284 opt->jo_term_rows = rows;
285 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
286 opt->jo_term_cols = cols;
287}
288
289/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100290 * Close a terminal buffer (and its window). Used when creating the terminal
291 * fails.
292 */
293 static void
294term_close_buffer(buf_T *buf, buf_T *old_curbuf)
295{
296 free_terminal(buf);
297 if (old_curbuf != NULL)
298 {
299 --curbuf->b_nwindows;
300 curbuf = old_curbuf;
301 curwin->w_buffer = curbuf;
302 ++curbuf->b_nwindows;
303 }
304
305 /* Wiping out the buffer will also close the window and call
306 * free_terminal(). */
307 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
308}
309
310/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200311 * Start a terminal window and return its buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +0100312 * When "without_job" is TRUE only create the buffer, b_term and open the
313 * window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200314 * Returns NULL when failed.
315 */
316 static buf_T *
Bram Moolenaard96ff162018-02-18 22:13:29 +0100317term_start(typval_T *argvar, jobopt_T *opt, int without_job, int forceit)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200318{
319 exarg_T split_ea;
320 win_T *old_curwin = curwin;
321 term_T *term;
322 buf_T *old_curbuf = NULL;
323 int res;
324 buf_T *newbuf;
325
326 if (check_restricted() || check_secure())
327 return NULL;
328
329 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
330 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
331 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
332 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
333 {
334 EMSG(_(e_invarg));
335 return NULL;
336 }
337
338 term = (term_T *)alloc_clear(sizeof(term_T));
339 if (term == NULL)
340 return NULL;
341 term->tl_dirty_row_end = MAX_ROW;
342 term->tl_cursor_visible = TRUE;
343 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
344 term->tl_finish = opt->jo_term_finish;
345 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
346
347 vim_memset(&split_ea, 0, sizeof(split_ea));
348 if (opt->jo_curwin)
349 {
350 /* Create a new buffer in the current window. */
351 if (!can_abandon(curbuf, forceit))
352 {
353 no_write_message();
354 vim_free(term);
355 return NULL;
356 }
357 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
358 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
359 {
360 vim_free(term);
361 return NULL;
362 }
363 }
364 else if (opt->jo_hidden)
365 {
366 buf_T *buf;
367
368 /* Create a new buffer without a window. Make it the current buffer for
369 * a moment to be able to do the initialisations. */
370 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
371 BLN_NEW | BLN_LISTED);
372 if (buf == NULL || ml_open(buf) == FAIL)
373 {
374 vim_free(term);
375 return NULL;
376 }
377 old_curbuf = curbuf;
378 --curbuf->b_nwindows;
379 curbuf = buf;
380 curwin->w_buffer = buf;
381 ++curbuf->b_nwindows;
382 }
383 else
384 {
385 /* Open a new window or tab. */
386 split_ea.cmdidx = CMD_new;
387 split_ea.cmd = (char_u *)"new";
388 split_ea.arg = (char_u *)"";
389 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
390 {
391 split_ea.line2 = opt->jo_term_rows;
392 split_ea.addr_count = 1;
393 }
394 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
395 {
396 split_ea.line2 = opt->jo_term_cols;
397 split_ea.addr_count = 1;
398 }
399
400 ex_splitview(&split_ea);
401 if (curwin == old_curwin)
402 {
403 /* split failed */
404 vim_free(term);
405 return NULL;
406 }
407 }
408 term->tl_buffer = curbuf;
409 curbuf->b_term = term;
410
411 if (!opt->jo_hidden)
412 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100413 /* Only one size was taken care of with :new, do the other one. With
414 * "curwin" both need to be done. */
415 if (opt->jo_term_rows > 0 && (opt->jo_curwin
416 || (cmdmod.split & WSP_VERT)))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200417 win_setheight(opt->jo_term_rows);
Bram Moolenaarda650582018-02-20 15:51:40 +0100418 if (opt->jo_term_cols > 0 && (opt->jo_curwin
419 || !(cmdmod.split & WSP_VERT)))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200420 win_setwidth(opt->jo_term_cols);
421 }
422
423 /* Link the new terminal in the list of active terminals. */
424 term->tl_next = first_term;
425 first_term = term;
426
427 if (opt->jo_term_name != NULL)
428 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
429 else
430 {
431 int i;
432 size_t len;
433 char_u *cmd, *p;
434
435 if (argvar->v_type == VAR_STRING)
436 {
437 cmd = argvar->vval.v_string;
438 if (cmd == NULL)
439 cmd = (char_u *)"";
440 else if (STRCMP(cmd, "NONE") == 0)
441 cmd = (char_u *)"pty";
442 }
443 else if (argvar->v_type != VAR_LIST
444 || argvar->vval.v_list == NULL
445 || argvar->vval.v_list->lv_len < 1
446 || (cmd = get_tv_string_chk(
447 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
448 cmd = (char_u*)"";
449
450 len = STRLEN(cmd) + 10;
451 p = alloc((int)len);
452
453 for (i = 0; p != NULL; ++i)
454 {
455 /* Prepend a ! to the command name to avoid the buffer name equals
456 * the executable, otherwise ":w!" would overwrite it. */
457 if (i == 0)
458 vim_snprintf((char *)p, len, "!%s", cmd);
459 else
460 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
461 if (buflist_findname(p) == NULL)
462 {
463 vim_free(curbuf->b_ffname);
464 curbuf->b_ffname = p;
465 break;
466 }
467 }
468 }
469 curbuf->b_fname = curbuf->b_ffname;
470
471 if (opt->jo_term_opencmd != NULL)
472 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
473
474 if (opt->jo_eof_chars != NULL)
475 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
476
477 set_string_option_direct((char_u *)"buftype", -1,
478 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
479
480 /* Mark the buffer as not modifiable. It can only be made modifiable after
481 * the job finished. */
482 curbuf->b_p_ma = FALSE;
483
484 set_term_and_win_size(term);
485 setup_job_options(opt, term->tl_rows, term->tl_cols);
486
Bram Moolenaard96ff162018-02-18 22:13:29 +0100487 if (without_job)
488 return curbuf;
489
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200490 /* System dependent: setup the vterm and maybe start the job in it. */
491 if (argvar->v_type == VAR_STRING
492 && argvar->vval.v_string != NULL
493 && STRCMP(argvar->vval.v_string, "NONE") == 0)
494 res = create_pty_only(term, opt);
495 else
496 res = term_and_job_init(term, argvar, opt);
497
498 newbuf = curbuf;
499 if (res == OK)
500 {
501 /* Get and remember the size we ended up with. Update the pty. */
502 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
503 term_report_winsize(term, term->tl_rows, term->tl_cols);
504
505 /* Make sure we don't get stuck on sending keys to the job, it leads to
506 * a deadlock if the job is waiting for Vim to read. */
507 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
508
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200509#ifdef FEAT_AUTOCMD
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100510 if (!opt->jo_hidden)
511 {
512 ++curbuf->b_locked;
513 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
514 --curbuf->b_locked;
515 }
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200516#endif
517
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200518 if (old_curbuf != NULL)
519 {
520 --curbuf->b_nwindows;
521 curbuf = old_curbuf;
522 curwin->w_buffer = curbuf;
523 ++curbuf->b_nwindows;
524 }
525 }
526 else
527 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100528 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200529 return NULL;
530 }
531 return newbuf;
532}
533
534/*
535 * ":terminal": open a terminal window and execute a job in it.
536 */
537 void
538ex_terminal(exarg_T *eap)
539{
540 typval_T argvar[2];
541 jobopt_T opt;
542 char_u *cmd;
543 char_u *tofree = NULL;
544
545 init_job_options(&opt);
546
547 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100548 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200549 {
550 char_u *p, *ep;
551
552 cmd += 2;
553 p = skiptowhite(cmd);
554 ep = vim_strchr(cmd, '=');
555 if (ep != NULL && ep < p)
556 p = ep;
557
558 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
559 opt.jo_term_finish = 'c';
560 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
561 opt.jo_term_finish = 'o';
562 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
563 opt.jo_curwin = 1;
564 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
565 opt.jo_hidden = 1;
566 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
567 && ep != NULL && isdigit(ep[1]))
568 {
569 opt.jo_set2 |= JO2_TERM_ROWS;
570 opt.jo_term_rows = atoi((char *)ep + 1);
571 p = skiptowhite(cmd);
572 }
573 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
574 && ep != NULL && isdigit(ep[1]))
575 {
576 opt.jo_set2 |= JO2_TERM_COLS;
577 opt.jo_term_cols = atoi((char *)ep + 1);
578 p = skiptowhite(cmd);
579 }
580 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
581 && ep != NULL)
582 {
583 char_u *buf = NULL;
584 char_u *keys;
585
586 p = skiptowhite(cmd);
587 *p = NUL;
588 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
589 opt.jo_set2 |= JO2_EOF_CHARS;
590 opt.jo_eof_chars = vim_strsave(keys);
591 vim_free(buf);
592 *p = ' ';
593 }
594 else
595 {
596 if (*p)
597 *p = NUL;
598 EMSG2(_("E181: Invalid attribute: %s"), cmd);
599 return;
600 }
601 cmd = skipwhite(p);
602 }
603 if (*cmd == NUL)
604 /* Make a copy of 'shell', an autocommand may change the option. */
605 tofree = cmd = vim_strsave(p_sh);
606
607 if (eap->addr_count > 0)
608 {
609 /* Write lines from current buffer to the job. */
610 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
611 opt.jo_io[PART_IN] = JIO_BUFFER;
612 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
613 opt.jo_in_top = eap->line1;
614 opt.jo_in_bot = eap->line2;
615 }
616
617 argvar[0].v_type = VAR_STRING;
618 argvar[0].vval.v_string = cmd;
619 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100620 term_start(argvar, &opt, FALSE, eap->forceit);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200621 vim_free(tofree);
622 vim_free(opt.jo_eof_chars);
623}
624
625/*
626 * Free the scrollback buffer for "term".
627 */
628 static void
629free_scrollback(term_T *term)
630{
631 int i;
632
633 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
634 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
635 ga_clear(&term->tl_scrollback);
636}
637
638/*
639 * Free a terminal and everything it refers to.
640 * Kills the job if there is one.
641 * Called when wiping out a buffer.
642 */
643 void
644free_terminal(buf_T *buf)
645{
646 term_T *term = buf->b_term;
647 term_T *tp;
648
649 if (term == NULL)
650 return;
651 if (first_term == term)
652 first_term = term->tl_next;
653 else
654 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
655 if (tp->tl_next == term)
656 {
657 tp->tl_next = term->tl_next;
658 break;
659 }
660
661 if (term->tl_job != NULL)
662 {
663 if (term->tl_job->jv_status != JOB_ENDED
664 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100665 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200666 job_stop(term->tl_job, NULL, "kill");
667 job_unref(term->tl_job);
668 }
669
670 free_scrollback(term);
671
672 term_free_vterm(term);
673 vim_free(term->tl_title);
674 vim_free(term->tl_status_text);
675 vim_free(term->tl_opencmd);
676 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100677 if (desired_cursor_color == term->tl_cursor_color)
678 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200679 vim_free(term->tl_cursor_color);
680 vim_free(term);
681 buf->b_term = NULL;
682 if (in_terminal_loop == term)
683 in_terminal_loop = NULL;
684}
685
686/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100687 * Get the part that is connected to the tty. Normally this is PART_IN, but
688 * when writing buffer lines to the job it can be another. This makes it
689 * possible to do "1,5term vim -".
690 */
691 static ch_part_T
692get_tty_part(term_T *term)
693{
694#ifdef UNIX
695 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
696 int i;
697
698 for (i = 0; i < 3; ++i)
699 {
700 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
701
702 if (isatty(fd))
703 return parts[i];
704 }
705#endif
706 return PART_IN;
707}
708
709/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200710 * Write job output "msg[len]" to the vterm.
711 */
712 static void
713term_write_job_output(term_T *term, char_u *msg, size_t len)
714{
715 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100716 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200717
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100718 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200719
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100720 /* flush vterm buffer when vterm responded to control sequence */
721 if (prevlen != vterm_output_get_buffer_current(vterm))
722 {
723 char buf[KEY_BUF_LEN];
724 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
725
726 if (curlen > 0)
727 channel_send(term->tl_job->jv_channel, get_tty_part(term),
728 (char_u *)buf, (int)curlen, NULL);
729 }
730
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200731 /* this invokes the damage callbacks */
732 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
733}
734
735 static void
736update_cursor(term_T *term, int redraw)
737{
738 if (term->tl_normal_mode)
739 return;
740 setcursor();
741 if (redraw)
742 {
743 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
744 cursor_on();
745 out_flush();
746#ifdef FEAT_GUI
747 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100748 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100750 gui_mch_flush();
751 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752#endif
753 }
754}
755
756/*
757 * Invoked when "msg" output from a job was received. Write it to the terminal
758 * of "buffer".
759 */
760 void
761write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
762{
763 size_t len = STRLEN(msg);
764 term_T *term = buffer->b_term;
765
766 if (term->tl_vterm == NULL)
767 {
768 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
769 return;
770 }
771 ch_log(channel, "writing %d bytes to terminal", (int)len);
772 term_write_job_output(term, msg, len);
773
774 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
775 * contents, thus no screen update is needed. */
776 if (!term->tl_normal_mode)
777 {
778 /* TODO: only update once in a while. */
779 ch_log(term->tl_job->jv_channel, "updating screen");
780 if (buffer == curbuf)
781 {
782 update_screen(0);
783 update_cursor(term, TRUE);
784 }
785 else
786 redraw_after_callback(TRUE);
787 }
788}
789
790/*
791 * Send a mouse position and click to the vterm
792 */
793 static int
794term_send_mouse(VTerm *vterm, int button, int pressed)
795{
796 VTermModifier mod = VTERM_MOD_NONE;
797
798 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200799 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100800 if (button != 0)
801 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200802 return TRUE;
803}
804
805/*
806 * Convert typed key "c" into bytes to send to the job.
807 * Return the number of bytes in "buf".
808 */
809 static int
810term_convert_key(term_T *term, int c, char *buf)
811{
812 VTerm *vterm = term->tl_vterm;
813 VTermKey key = VTERM_KEY_NONE;
814 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100815 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200816
817 switch (c)
818 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100819 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
820
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200821 /* don't use VTERM_KEY_BACKSPACE, it always
822 * becomes 0x7f DEL */
823 case K_BS: c = term_backspace_char; break;
824
825 case ESC: key = VTERM_KEY_ESCAPE; break;
826 case K_DEL: key = VTERM_KEY_DEL; break;
827 case K_DOWN: key = VTERM_KEY_DOWN; break;
828 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
829 key = VTERM_KEY_DOWN; break;
830 case K_END: key = VTERM_KEY_END; break;
831 case K_S_END: mod = VTERM_MOD_SHIFT;
832 key = VTERM_KEY_END; break;
833 case K_C_END: mod = VTERM_MOD_CTRL;
834 key = VTERM_KEY_END; break;
835 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
836 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
837 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
838 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
839 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
840 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
841 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
842 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
843 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
844 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
845 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
846 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
847 case K_HOME: key = VTERM_KEY_HOME; break;
848 case K_S_HOME: mod = VTERM_MOD_SHIFT;
849 key = VTERM_KEY_HOME; break;
850 case K_C_HOME: mod = VTERM_MOD_CTRL;
851 key = VTERM_KEY_HOME; break;
852 case K_INS: key = VTERM_KEY_INS; break;
853 case K_K0: key = VTERM_KEY_KP_0; break;
854 case K_K1: key = VTERM_KEY_KP_1; break;
855 case K_K2: key = VTERM_KEY_KP_2; break;
856 case K_K3: key = VTERM_KEY_KP_3; break;
857 case K_K4: key = VTERM_KEY_KP_4; break;
858 case K_K5: key = VTERM_KEY_KP_5; break;
859 case K_K6: key = VTERM_KEY_KP_6; break;
860 case K_K7: key = VTERM_KEY_KP_7; break;
861 case K_K8: key = VTERM_KEY_KP_8; break;
862 case K_K9: key = VTERM_KEY_KP_9; break;
863 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
864 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
865 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
866 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
867 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
868 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
869 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
870 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
871 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
872 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
873 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
874 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
875 case K_LEFT: key = VTERM_KEY_LEFT; break;
876 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
877 key = VTERM_KEY_LEFT; break;
878 case K_C_LEFT: mod = VTERM_MOD_CTRL;
879 key = VTERM_KEY_LEFT; break;
880 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
881 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
882 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
883 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
884 key = VTERM_KEY_RIGHT; break;
885 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
886 key = VTERM_KEY_RIGHT; break;
887 case K_UP: key = VTERM_KEY_UP; break;
888 case K_S_UP: mod = VTERM_MOD_SHIFT;
889 key = VTERM_KEY_UP; break;
890 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +0100891 case K_S_TAB: mod = VTERM_MOD_SHIFT;
892 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200893
Bram Moolenaara42ad572017-11-16 13:08:04 +0100894 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
895 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200896 case K_MOUSELEFT: /* TODO */ return 0;
897 case K_MOUSERIGHT: /* TODO */ return 0;
898
899 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100900 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
901 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200902 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100903 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100904 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100905 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
906 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
907 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
908 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
909 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
910 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200911 case K_X1MOUSE: /* TODO */ return 0;
912 case K_X1DRAG: /* TODO */ return 0;
913 case K_X1RELEASE: /* TODO */ return 0;
914 case K_X2MOUSE: /* TODO */ return 0;
915 case K_X2DRAG: /* TODO */ return 0;
916 case K_X2RELEASE: /* TODO */ return 0;
917
918 case K_IGNORE: return 0;
919 case K_NOP: return 0;
920 case K_UNDO: return 0;
921 case K_HELP: return 0;
922 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
923 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
924 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
925 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
926 case K_SELECT: return 0;
927#ifdef FEAT_GUI
928 case K_VER_SCROLLBAR: return 0;
929 case K_HOR_SCROLLBAR: return 0;
930#endif
931#ifdef FEAT_GUI_TABLINE
932 case K_TABLINE: return 0;
933 case K_TABMENU: return 0;
934#endif
935#ifdef FEAT_NETBEANS_INTG
936 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
937#endif
938#ifdef FEAT_DND
939 case K_DROP: return 0;
940#endif
941#ifdef FEAT_AUTOCMD
942 case K_CURSORHOLD: return 0;
943#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100944 case K_PS: vterm_keyboard_start_paste(vterm);
945 other = TRUE;
946 break;
947 case K_PE: vterm_keyboard_end_paste(vterm);
948 other = TRUE;
949 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200950 }
951
952 /*
953 * Convert special keys to vterm keys:
954 * - Write keys to vterm: vterm_keyboard_key()
955 * - Write output to channel.
956 * TODO: use mod_mask
957 */
958 if (key != VTERM_KEY_NONE)
959 /* Special key, let vterm convert it. */
960 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100961 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200962 /* Normal character, let vterm convert it. */
963 vterm_keyboard_unichar(vterm, c, mod);
964
965 /* Read back the converted escape sequence. */
966 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
967}
968
969/*
970 * Return TRUE if the job for "term" is still running.
971 */
972 int
973term_job_running(term_T *term)
974{
975 /* Also consider the job finished when the channel is closed, to avoid a
976 * race condition when updating the title. */
977 return term != NULL
978 && term->tl_job != NULL
979 && channel_is_open(term->tl_job->jv_channel)
980 && (term->tl_job->jv_status == JOB_STARTED
981 || term->tl_job->jv_channel->ch_keep_open);
982}
983
984/*
985 * Return TRUE if "term" has an active channel and used ":term NONE".
986 */
987 int
988term_none_open(term_T *term)
989{
990 /* Also consider the job finished when the channel is closed, to avoid a
991 * race condition when updating the title. */
992 return term != NULL
993 && term->tl_job != NULL
994 && channel_is_open(term->tl_job->jv_channel)
995 && term->tl_job->jv_channel->ch_keep_open;
996}
997
998/*
999 * Add the last line of the scrollback buffer to the buffer in the window.
1000 */
1001 static void
1002add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1003{
1004 buf_T *buf = term->tl_buffer;
1005 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1006 linenr_T lnum = buf->b_ml.ml_line_count;
1007
1008#ifdef WIN3264
1009 if (!enc_utf8 && enc_codepage > 0)
1010 {
1011 WCHAR *ret = NULL;
1012 int length = 0;
1013
1014 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1015 &ret, &length);
1016 if (ret != NULL)
1017 {
1018 WideCharToMultiByte_alloc(enc_codepage, 0,
1019 ret, length, (char **)&text, &len, 0, 0);
1020 vim_free(ret);
1021 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1022 vim_free(text);
1023 }
1024 }
1025 else
1026#endif
1027 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1028 if (empty)
1029 {
1030 /* Delete the empty line that was in the empty buffer. */
1031 curbuf = buf;
1032 ml_delete(1, FALSE);
1033 curbuf = curwin->w_buffer;
1034 }
1035}
1036
1037 static void
1038cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1039{
1040 attr->width = cell->width;
1041 attr->attrs = cell->attrs;
1042 attr->fg = cell->fg;
1043 attr->bg = cell->bg;
1044}
1045
1046 static int
1047equal_celattr(cellattr_T *a, cellattr_T *b)
1048{
1049 /* Comparing the colors should be sufficient. */
1050 return a->fg.red == b->fg.red
1051 && a->fg.green == b->fg.green
1052 && a->fg.blue == b->fg.blue
1053 && a->bg.red == b->bg.red
1054 && a->bg.green == b->bg.green
1055 && a->bg.blue == b->bg.blue;
1056}
1057
Bram Moolenaard96ff162018-02-18 22:13:29 +01001058/*
1059 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1060 * line at this position. Otherwise at the end.
1061 */
1062 static int
1063add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1064{
1065 if (ga_grow(&term->tl_scrollback, 1) == OK)
1066 {
1067 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1068 + term->tl_scrollback.ga_len;
1069
1070 if (lnum > 0)
1071 {
1072 int i;
1073
1074 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1075 {
1076 *line = *(line - 1);
1077 --line;
1078 }
1079 }
1080 line->sb_cols = 0;
1081 line->sb_cells = NULL;
1082 line->sb_fill_attr = *fill_attr;
1083 ++term->tl_scrollback.ga_len;
1084 return OK;
1085 }
1086 return FALSE;
1087}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001088
1089/*
1090 * Add the current lines of the terminal to scrollback and to the buffer.
1091 * Called after the job has ended and when switching to Terminal-Normal mode.
1092 */
1093 static void
1094move_terminal_to_buffer(term_T *term)
1095{
1096 win_T *wp;
1097 int len;
1098 int lines_skipped = 0;
1099 VTermPos pos;
1100 VTermScreenCell cell;
1101 cellattr_T fill_attr, new_fill_attr;
1102 cellattr_T *p;
1103 VTermScreen *screen;
1104
1105 if (term->tl_vterm == NULL)
1106 return;
1107 screen = vterm_obtain_screen(term->tl_vterm);
1108 fill_attr = new_fill_attr = term->tl_default_color;
1109
1110 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1111 {
1112 len = 0;
1113 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1114 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1115 && cell.chars[0] != NUL)
1116 {
1117 len = pos.col + 1;
1118 new_fill_attr = term->tl_default_color;
1119 }
1120 else
1121 /* Assume the last attr is the filler attr. */
1122 cell2cellattr(&cell, &new_fill_attr);
1123
1124 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1125 ++lines_skipped;
1126 else
1127 {
1128 while (lines_skipped > 0)
1129 {
1130 /* Line was skipped, add an empty line. */
1131 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001132 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001133 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001134 }
1135
1136 if (len == 0)
1137 p = NULL;
1138 else
1139 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1140 if ((p != NULL || len == 0)
1141 && ga_grow(&term->tl_scrollback, 1) == OK)
1142 {
1143 garray_T ga;
1144 int width;
1145 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1146 + term->tl_scrollback.ga_len;
1147
1148 ga_init2(&ga, 1, 100);
1149 for (pos.col = 0; pos.col < len; pos.col += width)
1150 {
1151 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1152 {
1153 width = 1;
1154 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1155 if (ga_grow(&ga, 1) == OK)
1156 ga.ga_len += utf_char2bytes(' ',
1157 (char_u *)ga.ga_data + ga.ga_len);
1158 }
1159 else
1160 {
1161 width = cell.width;
1162
1163 cell2cellattr(&cell, &p[pos.col]);
1164
1165 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1166 {
1167 int i;
1168 int c;
1169
1170 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1171 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1172 (char_u *)ga.ga_data + ga.ga_len);
1173 }
1174 }
1175 }
1176 line->sb_cols = len;
1177 line->sb_cells = p;
1178 line->sb_fill_attr = new_fill_attr;
1179 fill_attr = new_fill_attr;
1180 ++term->tl_scrollback.ga_len;
1181
1182 if (ga_grow(&ga, 1) == FAIL)
1183 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1184 else
1185 {
1186 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1187 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1188 }
1189 ga_clear(&ga);
1190 }
1191 else
1192 vim_free(p);
1193 }
1194 }
1195
1196 /* Obtain the current background color. */
1197 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1198 &term->tl_default_color.fg, &term->tl_default_color.bg);
1199
1200 FOR_ALL_WINDOWS(wp)
1201 {
1202 if (wp->w_buffer == term->tl_buffer)
1203 {
1204 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1205 wp->w_cursor.col = 0;
1206 wp->w_valid = 0;
1207 if (wp->w_cursor.lnum >= wp->w_height)
1208 {
1209 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1210
1211 if (wp->w_topline < min_topline)
1212 wp->w_topline = min_topline;
1213 }
1214 redraw_win_later(wp, NOT_VALID);
1215 }
1216 }
1217}
1218
1219 static void
1220set_terminal_mode(term_T *term, int normal_mode)
1221{
1222 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001223 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001224 if (term->tl_buffer == curbuf)
1225 maketitle();
1226}
1227
1228/*
1229 * Called after the job if finished and Terminal mode is not active:
1230 * Move the vterm contents into the scrollback buffer and free the vterm.
1231 */
1232 static void
1233cleanup_vterm(term_T *term)
1234{
1235 if (term->tl_finish != 'c')
1236 move_terminal_to_buffer(term);
1237 term_free_vterm(term);
1238 set_terminal_mode(term, FALSE);
1239}
1240
1241/*
1242 * Switch from Terminal-Job mode to Terminal-Normal mode.
1243 * Suspends updating the terminal window.
1244 */
1245 static void
1246term_enter_normal_mode(void)
1247{
1248 term_T *term = curbuf->b_term;
1249
1250 /* Append the current terminal contents to the buffer. */
1251 move_terminal_to_buffer(term);
1252
1253 set_terminal_mode(term, TRUE);
1254
1255 /* Move the window cursor to the position of the cursor in the
1256 * terminal. */
1257 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1258 + term->tl_cursor_pos.row + 1;
1259 check_cursor();
1260 coladvance(term->tl_cursor_pos.col);
1261
1262 /* Display the same lines as in the terminal. */
1263 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1264}
1265
1266/*
1267 * Returns TRUE if the current window contains a terminal and we are in
1268 * Terminal-Normal mode.
1269 */
1270 int
1271term_in_normal_mode(void)
1272{
1273 term_T *term = curbuf->b_term;
1274
1275 return term != NULL && term->tl_normal_mode;
1276}
1277
1278/*
1279 * Switch from Terminal-Normal mode to Terminal-Job mode.
1280 * Restores updating the terminal window.
1281 */
1282 void
1283term_enter_job_mode()
1284{
1285 term_T *term = curbuf->b_term;
1286 sb_line_T *line;
1287 garray_T *gap;
1288
1289 /* Remove the terminal contents from the scrollback and the buffer. */
1290 gap = &term->tl_scrollback;
1291 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1292 && gap->ga_len > 0)
1293 {
1294 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1295 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1296 vim_free(line->sb_cells);
1297 --gap->ga_len;
1298 }
1299 check_cursor();
1300
1301 set_terminal_mode(term, FALSE);
1302
1303 if (term->tl_channel_closed)
1304 cleanup_vterm(term);
1305 redraw_buf_and_status_later(curbuf, NOT_VALID);
1306}
1307
1308/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001309 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001310 * Note: while waiting a terminal may be closed and freed if the channel is
1311 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001312 */
1313 static int
1314term_vgetc()
1315{
1316 int c;
1317 int save_State = State;
1318
1319 State = TERMINAL;
1320 got_int = FALSE;
1321#ifdef WIN3264
1322 ctrl_break_was_pressed = FALSE;
1323#endif
1324 c = vgetc();
1325 got_int = FALSE;
1326 State = save_State;
1327 return c;
1328}
1329
1330/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001331 * Send keys to terminal.
1332 * Return FAIL when the key needs to be handled in Normal mode.
1333 * Return OK when the key was dropped or sent to the terminal.
1334 */
1335 int
1336send_keys_to_term(term_T *term, int c, int typed)
1337{
1338 char msg[KEY_BUF_LEN];
1339 size_t len;
1340 static int mouse_was_outside = FALSE;
1341 int dragging_outside = FALSE;
1342
1343 /* Catch keys that need to be handled as in Normal mode. */
1344 switch (c)
1345 {
1346 case NUL:
1347 case K_ZERO:
1348 if (typed)
1349 stuffcharReadbuff(c);
1350 return FAIL;
1351
1352 case K_IGNORE:
1353 return FAIL;
1354
1355 case K_LEFTDRAG:
1356 case K_MIDDLEDRAG:
1357 case K_RIGHTDRAG:
1358 case K_X1DRAG:
1359 case K_X2DRAG:
1360 dragging_outside = mouse_was_outside;
1361 /* FALLTHROUGH */
1362 case K_LEFTMOUSE:
1363 case K_LEFTMOUSE_NM:
1364 case K_LEFTRELEASE:
1365 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001366 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001367 case K_MIDDLEMOUSE:
1368 case K_MIDDLERELEASE:
1369 case K_RIGHTMOUSE:
1370 case K_RIGHTRELEASE:
1371 case K_X1MOUSE:
1372 case K_X1RELEASE:
1373 case K_X2MOUSE:
1374 case K_X2RELEASE:
1375
1376 case K_MOUSEUP:
1377 case K_MOUSEDOWN:
1378 case K_MOUSELEFT:
1379 case K_MOUSERIGHT:
1380 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001381 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001382 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001383 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001384 || dragging_outside)
1385 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001386 /* click or scroll outside the current window or on status line
1387 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001388 if (typed)
1389 {
1390 stuffcharReadbuff(c);
1391 mouse_was_outside = TRUE;
1392 }
1393 return FAIL;
1394 }
1395 }
1396 if (typed)
1397 mouse_was_outside = FALSE;
1398
1399 /* Convert the typed key to a sequence of bytes for the job. */
1400 len = term_convert_key(term, c, msg);
1401 if (len > 0)
1402 /* TODO: if FAIL is returned, stop? */
1403 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1404 (char_u *)msg, (int)len, NULL);
1405
1406 return OK;
1407}
1408
1409 static void
1410position_cursor(win_T *wp, VTermPos *pos)
1411{
1412 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1413 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1414 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1415}
1416
1417/*
1418 * Handle CTRL-W "": send register contents to the job.
1419 */
1420 static void
1421term_paste_register(int prev_c UNUSED)
1422{
1423 int c;
1424 list_T *l;
1425 listitem_T *item;
1426 long reglen = 0;
1427 int type;
1428
1429#ifdef FEAT_CMDL_INFO
1430 if (add_to_showcmd(prev_c))
1431 if (add_to_showcmd('"'))
1432 out_flush();
1433#endif
1434 c = term_vgetc();
1435#ifdef FEAT_CMDL_INFO
1436 clear_showcmd();
1437#endif
1438 if (!term_use_loop())
1439 /* job finished while waiting for a character */
1440 return;
1441
1442 /* CTRL-W "= prompt for expression to evaluate. */
1443 if (c == '=' && get_expr_register() != '=')
1444 return;
1445 if (!term_use_loop())
1446 /* job finished while waiting for a character */
1447 return;
1448
1449 l = (list_T *)get_reg_contents(c, GREG_LIST);
1450 if (l != NULL)
1451 {
1452 type = get_reg_type(c, &reglen);
1453 for (item = l->lv_first; item != NULL; item = item->li_next)
1454 {
1455 char_u *s = get_tv_string(&item->li_tv);
1456#ifdef WIN3264
1457 char_u *tmp = s;
1458
1459 if (!enc_utf8 && enc_codepage > 0)
1460 {
1461 WCHAR *ret = NULL;
1462 int length = 0;
1463
1464 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1465 (int)STRLEN(s), &ret, &length);
1466 if (ret != NULL)
1467 {
1468 WideCharToMultiByte_alloc(CP_UTF8, 0,
1469 ret, length, (char **)&s, &length, 0, 0);
1470 vim_free(ret);
1471 }
1472 }
1473#endif
1474 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1475 s, (int)STRLEN(s), NULL);
1476#ifdef WIN3264
1477 if (tmp != s)
1478 vim_free(s);
1479#endif
1480
1481 if (item->li_next != NULL || type == MLINE)
1482 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1483 (char_u *)"\r", 1, NULL);
1484 }
1485 list_free(l);
1486 }
1487}
1488
1489#if defined(FEAT_GUI) || defined(PROTO)
1490/*
1491 * Return TRUE when the cursor of the terminal should be displayed.
1492 */
1493 int
1494terminal_is_active()
1495{
1496 return in_terminal_loop != NULL;
1497}
1498
1499 cursorentry_T *
1500term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1501{
1502 term_T *term = in_terminal_loop;
1503 static cursorentry_T entry;
1504
1505 vim_memset(&entry, 0, sizeof(entry));
1506 entry.shape = entry.mshape =
1507 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1508 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1509 SHAPE_BLOCK;
1510 entry.percentage = 20;
1511 if (term->tl_cursor_blink)
1512 {
1513 entry.blinkwait = 700;
1514 entry.blinkon = 400;
1515 entry.blinkoff = 250;
1516 }
1517 *fg = gui.back_pixel;
1518 if (term->tl_cursor_color == NULL)
1519 *bg = gui.norm_pixel;
1520 else
1521 *bg = color_name2handle(term->tl_cursor_color);
1522 entry.name = "n";
1523 entry.used_for = SHAPE_CURSOR;
1524
1525 return &entry;
1526}
1527#endif
1528
Bram Moolenaard317b382018-02-08 22:33:31 +01001529 static void
1530may_output_cursor_props(void)
1531{
1532 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1533 || last_set_cursor_shape != desired_cursor_shape
1534 || last_set_cursor_blink != desired_cursor_blink)
1535 {
1536 last_set_cursor_color = desired_cursor_color;
1537 last_set_cursor_shape = desired_cursor_shape;
1538 last_set_cursor_blink = desired_cursor_blink;
1539 term_cursor_color(desired_cursor_color);
1540 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1541 /* this will restore the initial cursor style, if possible */
1542 ui_cursor_shape_forced(TRUE);
1543 else
1544 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1545 }
1546}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001547
Bram Moolenaard317b382018-02-08 22:33:31 +01001548/*
1549 * Set the cursor color and shape, if not last set to these.
1550 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001551 static void
1552may_set_cursor_props(term_T *term)
1553{
1554#ifdef FEAT_GUI
1555 /* For the GUI the cursor properties are obtained with
1556 * term_get_cursor_shape(). */
1557 if (gui.in_use)
1558 return;
1559#endif
1560 if (in_terminal_loop == term)
1561 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001563 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001564 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001565 desired_cursor_color = (char_u *)"";
1566 desired_cursor_shape = term->tl_cursor_shape;
1567 desired_cursor_blink = term->tl_cursor_blink;
1568 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001569 }
1570}
1571
Bram Moolenaard317b382018-02-08 22:33:31 +01001572/*
1573 * Reset the desired cursor properties and restore them when needed.
1574 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001575 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001576prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001577{
1578#ifdef FEAT_GUI
1579 if (gui.in_use)
1580 return;
1581#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001582 desired_cursor_color = (char_u *)"";
1583 desired_cursor_shape = -1;
1584 desired_cursor_blink = -1;
1585 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001586}
1587
1588/*
1589 * Returns TRUE if the current window contains a terminal and we are sending
1590 * keys to the job.
1591 */
1592 int
1593term_use_loop(void)
1594{
1595 term_T *term = curbuf->b_term;
1596
1597 return term != NULL
1598 && !term->tl_normal_mode
1599 && term->tl_vterm != NULL
1600 && term_job_running(term);
1601}
1602
1603/*
1604 * Wait for input and send it to the job.
1605 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1606 * when there is no more typahead.
1607 * Return when the start of a CTRL-W command is typed or anything else that
1608 * should be handled as a Normal mode command.
1609 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1610 * the terminal was closed.
1611 */
1612 int
1613terminal_loop(int blocking)
1614{
1615 int c;
1616 int termkey = 0;
1617 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001618#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001619 int tty_fd = curbuf->b_term->tl_job->jv_channel
1620 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001621#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001622 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001623
1624 /* Remember the terminal we are sending keys to. However, the terminal
1625 * might be closed while waiting for a character, e.g. typing "exit" in a
1626 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1627 * stored reference. */
1628 in_terminal_loop = curbuf->b_term;
1629
1630 if (*curwin->w_p_tk != NUL)
1631 termkey = string_to_key(curwin->w_p_tk, TRUE);
1632 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1633 may_set_cursor_props(curbuf->b_term);
1634
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001635 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 {
1637 /* TODO: skip screen update when handling a sequence of keys. */
1638 /* Repeat redrawing in case a message is received while redrawing. */
1639 while (must_redraw != 0)
1640 if (update_screen(0) == FAIL)
1641 break;
1642 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001643 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001644
1645 c = term_vgetc();
1646 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001647 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001648 /* Job finished while waiting for a character. Push back the
1649 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001650 if (c != K_IGNORE)
1651 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001652 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001653 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001654 if (c == K_IGNORE)
1655 continue;
1656
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001657#ifdef UNIX
1658 /*
1659 * The shell or another program may change the tty settings. Getting
1660 * them for every typed character is a bit of overhead, but it's needed
1661 * for the first character typed, e.g. when Vim starts in a shell.
1662 */
1663 if (isatty(tty_fd))
1664 {
1665 ttyinfo_T info;
1666
1667 /* Get the current backspace character of the pty. */
1668 if (get_tty_info(tty_fd, &info) == OK)
1669 term_backspace_char = info.backspace;
1670 }
1671#endif
1672
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001673#ifdef WIN3264
1674 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1675 * Use CTRL-BREAK to kill the job. */
1676 if (ctrl_break_was_pressed)
1677 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1678#endif
1679 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1680 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1681 {
1682 int prev_c = c;
1683
1684#ifdef FEAT_CMDL_INFO
1685 if (add_to_showcmd(c))
1686 out_flush();
1687#endif
1688 c = term_vgetc();
1689#ifdef FEAT_CMDL_INFO
1690 clear_showcmd();
1691#endif
1692 if (!term_use_loop())
1693 /* job finished while waiting for a character */
1694 break;
1695
1696 if (prev_c == Ctrl_BSL)
1697 {
1698 if (c == Ctrl_N)
1699 {
1700 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1701 term_enter_normal_mode();
1702 ret = FAIL;
1703 goto theend;
1704 }
1705 /* Send both keys to the terminal. */
1706 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1707 }
1708 else if (c == Ctrl_C)
1709 {
1710 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1711 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1712 }
1713 else if (termkey == 0 && c == '.')
1714 {
1715 /* "CTRL-W .": send CTRL-W to the job */
1716 c = Ctrl_W;
1717 }
1718 else if (c == 'N')
1719 {
1720 /* CTRL-W N : go to Terminal-Normal mode. */
1721 term_enter_normal_mode();
1722 ret = FAIL;
1723 goto theend;
1724 }
1725 else if (c == '"')
1726 {
1727 term_paste_register(prev_c);
1728 continue;
1729 }
1730 else if (termkey == 0 || c != termkey)
1731 {
1732 stuffcharReadbuff(Ctrl_W);
1733 stuffcharReadbuff(c);
1734 ret = OK;
1735 goto theend;
1736 }
1737 }
1738# ifdef WIN3264
1739 if (!enc_utf8 && has_mbyte && c >= 0x80)
1740 {
1741 WCHAR wc;
1742 char_u mb[3];
1743
1744 mb[0] = (unsigned)c >> 8;
1745 mb[1] = c;
1746 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1747 c = wc;
1748 }
1749# endif
1750 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1751 {
Bram Moolenaard317b382018-02-08 22:33:31 +01001752 if (c == K_MOUSEMOVE)
1753 /* We are sure to come back here, don't reset the cursor color
1754 * and shape to avoid flickering. */
1755 restore_cursor = FALSE;
1756
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757 ret = OK;
1758 goto theend;
1759 }
1760 }
1761 ret = FAIL;
1762
1763theend:
1764 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01001765 if (restore_cursor)
1766 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001767 return ret;
1768}
1769
1770/*
1771 * Called when a job has finished.
1772 * This updates the title and status, but does not close the vterm, because
1773 * there might still be pending output in the channel.
1774 */
1775 void
1776term_job_ended(job_T *job)
1777{
1778 term_T *term;
1779 int did_one = FALSE;
1780
1781 for (term = first_term; term != NULL; term = term->tl_next)
1782 if (term->tl_job == job)
1783 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01001784 VIM_CLEAR(term->tl_title);
1785 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001786 redraw_buf_and_status_later(term->tl_buffer, VALID);
1787 did_one = TRUE;
1788 }
1789 if (did_one)
1790 redraw_statuslines();
1791 if (curbuf->b_term != NULL)
1792 {
1793 if (curbuf->b_term->tl_job == job)
1794 maketitle();
1795 update_cursor(curbuf->b_term, TRUE);
1796 }
1797}
1798
1799 static void
1800may_toggle_cursor(term_T *term)
1801{
1802 if (in_terminal_loop == term)
1803 {
1804 if (term->tl_cursor_visible)
1805 cursor_on();
1806 else
1807 cursor_off();
1808 }
1809}
1810
1811/*
1812 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001813 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001814 */
1815 static int
1816color2index(VTermColor *color, int fg, int *boldp)
1817{
1818 int red = color->red;
1819 int blue = color->blue;
1820 int green = color->green;
1821
Bram Moolenaar46359e12017-11-29 22:33:38 +01001822 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001823 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001824 /* First 16 colors and default: use the ANSI index, because these
1825 * colors can be redefined. */
1826 if (t_colors >= 16)
1827 return color->ansi_index;
1828 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001829 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001830 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01001831 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01001832 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1833 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1834 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1835 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1836 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1837 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1838 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1839 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1840 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1841 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1842 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1843 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1844 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1845 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1846 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001847 }
1848 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001849
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001850 if (t_colors >= 256)
1851 {
1852 if (red == blue && red == green)
1853 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001854 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001855 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001856 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1857 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1858 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001859 int i;
1860
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001861 if (red < 5)
1862 return 17; /* 00/00/00 */
1863 if (red > 245) /* ff/ff/ff */
1864 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001865 for (i = 0; i < 23; ++i)
1866 if (red < cutoff[i])
1867 return i + 233;
1868 return 256;
1869 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001870 {
1871 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1872 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001873
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001874 /* 216-color cube */
1875 for (ri = 0; ri < 5; ++ri)
1876 if (red < cutoff[ri])
1877 break;
1878 for (gi = 0; gi < 5; ++gi)
1879 if (green < cutoff[gi])
1880 break;
1881 for (bi = 0; bi < 5; ++bi)
1882 if (blue < cutoff[bi])
1883 break;
1884 return 17 + ri * 36 + gi * 6 + bi;
1885 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001886 }
1887 return 0;
1888}
1889
1890/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01001891 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001892 */
1893 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01001894vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001895{
1896 int attr = 0;
1897
1898 if (cellattrs.bold)
1899 attr |= HL_BOLD;
1900 if (cellattrs.underline)
1901 attr |= HL_UNDERLINE;
1902 if (cellattrs.italic)
1903 attr |= HL_ITALIC;
1904 if (cellattrs.strike)
1905 attr |= HL_STRIKETHROUGH;
1906 if (cellattrs.reverse)
1907 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001908 return attr;
1909}
1910
1911/*
1912 * Store Vterm attributes in "cell" from highlight flags.
1913 */
1914 static void
1915hl2vtermAttr(int attr, cellattr_T *cell)
1916{
1917 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
1918 if (attr & HL_BOLD)
1919 cell->attrs.bold = 1;
1920 if (attr & HL_UNDERLINE)
1921 cell->attrs.underline = 1;
1922 if (attr & HL_ITALIC)
1923 cell->attrs.italic = 1;
1924 if (attr & HL_STRIKETHROUGH)
1925 cell->attrs.strike = 1;
1926 if (attr & HL_INVERSE)
1927 cell->attrs.reverse = 1;
1928}
1929
1930/*
1931 * Convert the attributes of a vterm cell into an attribute index.
1932 */
1933 static int
1934cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1935{
1936 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001937
1938#ifdef FEAT_GUI
1939 if (gui.in_use)
1940 {
1941 guicolor_T fg, bg;
1942
1943 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1944 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1945 return get_gui_attr_idx(attr, fg, bg);
1946 }
1947 else
1948#endif
1949#ifdef FEAT_TERMGUICOLORS
1950 if (p_tgc)
1951 {
1952 guicolor_T fg, bg;
1953
1954 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1955 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1956
1957 return get_tgc_attr_idx(attr, fg, bg);
1958 }
1959 else
1960#endif
1961 {
1962 int bold = MAYBE;
1963 int fg = color2index(&cellfg, TRUE, &bold);
1964 int bg = color2index(&cellbg, FALSE, &bold);
1965
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001966 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001967 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001968 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001969 if (fg == 0 && term_default_cterm_fg >= 0)
1970 fg = term_default_cterm_fg + 1;
1971 if (bg == 0 && term_default_cterm_bg >= 0)
1972 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001973 }
1974
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001975 /* with 8 colors set the bold attribute to get a bright foreground */
1976 if (bold == TRUE)
1977 attr |= HL_BOLD;
1978 return get_cterm_attr_idx(attr, fg, bg);
1979 }
1980 return 0;
1981}
1982
1983 static int
1984handle_damage(VTermRect rect, void *user)
1985{
1986 term_T *term = (term_T *)user;
1987
1988 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1989 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1990 redraw_buf_later(term->tl_buffer, NOT_VALID);
1991 return 1;
1992}
1993
1994 static int
1995handle_moverect(VTermRect dest, VTermRect src, void *user)
1996{
1997 term_T *term = (term_T *)user;
1998
1999 /* Scrolling up is done much more efficiently by deleting lines instead of
2000 * redrawing the text. */
2001 if (dest.start_col == src.start_col
2002 && dest.end_col == src.end_col
2003 && dest.start_row < src.start_row)
2004 {
2005 win_T *wp;
2006 VTermColor fg, bg;
2007 VTermScreenCellAttrs attr;
2008 int clear_attr;
2009
2010 /* Set the color to clear lines with. */
2011 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2012 &fg, &bg);
2013 vim_memset(&attr, 0, sizeof(attr));
2014 clear_attr = cell2attr(attr, fg, bg);
2015
2016 FOR_ALL_WINDOWS(wp)
2017 {
2018 if (wp->w_buffer == term->tl_buffer)
2019 win_del_lines(wp, dest.start_row,
2020 src.start_row - dest.start_row, FALSE, FALSE,
2021 clear_attr);
2022 }
2023 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002024
2025 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2026 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2027
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 redraw_buf_later(term->tl_buffer, NOT_VALID);
2029 return 1;
2030}
2031
2032 static int
2033handle_movecursor(
2034 VTermPos pos,
2035 VTermPos oldpos UNUSED,
2036 int visible,
2037 void *user)
2038{
2039 term_T *term = (term_T *)user;
2040 win_T *wp;
2041
2042 term->tl_cursor_pos = pos;
2043 term->tl_cursor_visible = visible;
2044
2045 FOR_ALL_WINDOWS(wp)
2046 {
2047 if (wp->w_buffer == term->tl_buffer)
2048 position_cursor(wp, &pos);
2049 }
2050 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2051 {
2052 may_toggle_cursor(term);
2053 update_cursor(term, term->tl_cursor_visible);
2054 }
2055
2056 return 1;
2057}
2058
2059 static int
2060handle_settermprop(
2061 VTermProp prop,
2062 VTermValue *value,
2063 void *user)
2064{
2065 term_T *term = (term_T *)user;
2066
2067 switch (prop)
2068 {
2069 case VTERM_PROP_TITLE:
2070 vim_free(term->tl_title);
2071 /* a blank title isn't useful, make it empty, so that "running" is
2072 * displayed */
2073 if (*skipwhite((char_u *)value->string) == NUL)
2074 term->tl_title = NULL;
2075#ifdef WIN3264
2076 else if (!enc_utf8 && enc_codepage > 0)
2077 {
2078 WCHAR *ret = NULL;
2079 int length = 0;
2080
2081 MultiByteToWideChar_alloc(CP_UTF8, 0,
2082 (char*)value->string, (int)STRLEN(value->string),
2083 &ret, &length);
2084 if (ret != NULL)
2085 {
2086 WideCharToMultiByte_alloc(enc_codepage, 0,
2087 ret, length, (char**)&term->tl_title,
2088 &length, 0, 0);
2089 vim_free(ret);
2090 }
2091 }
2092#endif
2093 else
2094 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002095 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002096 if (term == curbuf->b_term)
2097 maketitle();
2098 break;
2099
2100 case VTERM_PROP_CURSORVISIBLE:
2101 term->tl_cursor_visible = value->boolean;
2102 may_toggle_cursor(term);
2103 out_flush();
2104 break;
2105
2106 case VTERM_PROP_CURSORBLINK:
2107 term->tl_cursor_blink = value->boolean;
2108 may_set_cursor_props(term);
2109 break;
2110
2111 case VTERM_PROP_CURSORSHAPE:
2112 term->tl_cursor_shape = value->number;
2113 may_set_cursor_props(term);
2114 break;
2115
2116 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002117 if (desired_cursor_color == term->tl_cursor_color)
2118 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002119 vim_free(term->tl_cursor_color);
2120 if (*value->string == NUL)
2121 term->tl_cursor_color = NULL;
2122 else
2123 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2124 may_set_cursor_props(term);
2125 break;
2126
2127 case VTERM_PROP_ALTSCREEN:
2128 /* TODO: do anything else? */
2129 term->tl_using_altscreen = value->boolean;
2130 break;
2131
2132 default:
2133 break;
2134 }
2135 /* Always return 1, otherwise vterm doesn't store the value internally. */
2136 return 1;
2137}
2138
2139/*
2140 * The job running in the terminal resized the terminal.
2141 */
2142 static int
2143handle_resize(int rows, int cols, void *user)
2144{
2145 term_T *term = (term_T *)user;
2146 win_T *wp;
2147
2148 term->tl_rows = rows;
2149 term->tl_cols = cols;
2150 if (term->tl_vterm_size_changed)
2151 /* Size was set by vterm_set_size(), don't set the window size. */
2152 term->tl_vterm_size_changed = FALSE;
2153 else
2154 {
2155 FOR_ALL_WINDOWS(wp)
2156 {
2157 if (wp->w_buffer == term->tl_buffer)
2158 {
2159 win_setheight_win(rows, wp);
2160 win_setwidth_win(cols, wp);
2161 }
2162 }
2163 redraw_buf_later(term->tl_buffer, NOT_VALID);
2164 }
2165 return 1;
2166}
2167
2168/*
2169 * Handle a line that is pushed off the top of the screen.
2170 */
2171 static int
2172handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2173{
2174 term_T *term = (term_T *)user;
2175
2176 /* TODO: Limit the number of lines that are stored. */
2177 if (ga_grow(&term->tl_scrollback, 1) == OK)
2178 {
2179 cellattr_T *p = NULL;
2180 int len = 0;
2181 int i;
2182 int c;
2183 int col;
2184 sb_line_T *line;
2185 garray_T ga;
2186 cellattr_T fill_attr = term->tl_default_color;
2187
2188 /* do not store empty cells at the end */
2189 for (i = 0; i < cols; ++i)
2190 if (cells[i].chars[0] != 0)
2191 len = i + 1;
2192 else
2193 cell2cellattr(&cells[i], &fill_attr);
2194
2195 ga_init2(&ga, 1, 100);
2196 if (len > 0)
2197 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2198 if (p != NULL)
2199 {
2200 for (col = 0; col < len; col += cells[col].width)
2201 {
2202 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2203 {
2204 ga.ga_len = 0;
2205 break;
2206 }
2207 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2208 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2209 (char_u *)ga.ga_data + ga.ga_len);
2210 cell2cellattr(&cells[col], &p[col]);
2211 }
2212 }
2213 if (ga_grow(&ga, 1) == FAIL)
2214 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2215 else
2216 {
2217 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2218 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2219 }
2220 ga_clear(&ga);
2221
2222 line = (sb_line_T *)term->tl_scrollback.ga_data
2223 + term->tl_scrollback.ga_len;
2224 line->sb_cols = len;
2225 line->sb_cells = p;
2226 line->sb_fill_attr = fill_attr;
2227 ++term->tl_scrollback.ga_len;
2228 ++term->tl_scrollback_scrolled;
2229 }
2230 return 0; /* ignored */
2231}
2232
2233static VTermScreenCallbacks screen_callbacks = {
2234 handle_damage, /* damage */
2235 handle_moverect, /* moverect */
2236 handle_movecursor, /* movecursor */
2237 handle_settermprop, /* settermprop */
2238 NULL, /* bell */
2239 handle_resize, /* resize */
2240 handle_pushline, /* sb_pushline */
2241 NULL /* sb_popline */
2242};
2243
2244/*
2245 * Called when a channel has been closed.
2246 * If this was a channel for a terminal window then finish it up.
2247 */
2248 void
2249term_channel_closed(channel_T *ch)
2250{
2251 term_T *term;
2252 int did_one = FALSE;
2253
2254 for (term = first_term; term != NULL; term = term->tl_next)
2255 if (term->tl_job == ch->ch_job)
2256 {
2257 term->tl_channel_closed = TRUE;
2258 did_one = TRUE;
2259
Bram Moolenaard23a8232018-02-10 18:45:26 +01002260 VIM_CLEAR(term->tl_title);
2261 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002262
2263 /* Unless in Terminal-Normal mode: clear the vterm. */
2264 if (!term->tl_normal_mode)
2265 {
2266 int fnum = term->tl_buffer->b_fnum;
2267
2268 cleanup_vterm(term);
2269
2270 if (term->tl_finish == 'c')
2271 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002272 aco_save_T aco;
2273
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 /* ++close or term_finish == "close" */
2275 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002276 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002278 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002279 break;
2280 }
2281 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2282 {
2283 char buf[50];
2284
2285 /* TODO: use term_opencmd */
2286 ch_log(NULL, "terminal job finished, opening window");
2287 vim_snprintf(buf, sizeof(buf),
2288 term->tl_opencmd == NULL
2289 ? "botright sbuf %d"
2290 : (char *)term->tl_opencmd, fnum);
2291 do_cmdline_cmd((char_u *)buf);
2292 }
2293 else
2294 ch_log(NULL, "terminal job finished");
2295 }
2296
2297 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2298 }
2299 if (did_one)
2300 {
2301 redraw_statuslines();
2302
2303 /* Need to break out of vgetc(). */
2304 ins_char_typebuf(K_IGNORE);
2305 typebuf_was_filled = TRUE;
2306
2307 term = curbuf->b_term;
2308 if (term != NULL)
2309 {
2310 if (term->tl_job == ch->ch_job)
2311 maketitle();
2312 update_cursor(term, term->tl_cursor_visible);
2313 }
2314 }
2315}
2316
2317/*
2318 * Called to update a window that contains an active terminal.
2319 * Returns FAIL when there is no terminal running in this window or in
2320 * Terminal-Normal mode.
2321 */
2322 int
2323term_update_window(win_T *wp)
2324{
2325 term_T *term = wp->w_buffer->b_term;
2326 VTerm *vterm;
2327 VTermScreen *screen;
2328 VTermState *state;
2329 VTermPos pos;
2330
2331 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2332 return FAIL;
2333
2334 vterm = term->tl_vterm;
2335 screen = vterm_obtain_screen(vterm);
2336 state = vterm_obtain_state(vterm);
2337
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002338 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002339 {
2340 term->tl_dirty_row_start = 0;
2341 term->tl_dirty_row_end = MAX_ROW;
2342 }
2343
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002344 /*
2345 * If the window was resized a redraw will be triggered and we get here.
2346 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2347 */
2348 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2349 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2350 {
2351 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2352 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2353 win_T *twp;
2354
2355 FOR_ALL_WINDOWS(twp)
2356 {
2357 /* When more than one window shows the same terminal, use the
2358 * smallest size. */
2359 if (twp->w_buffer == term->tl_buffer)
2360 {
2361 if (!term->tl_rows_fixed && rows > twp->w_height)
2362 rows = twp->w_height;
2363 if (!term->tl_cols_fixed && cols > twp->w_width)
2364 cols = twp->w_width;
2365 }
2366 }
2367
2368 term->tl_vterm_size_changed = TRUE;
2369 vterm_set_size(vterm, rows, cols);
2370 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2371 rows);
2372 term_report_winsize(term, rows, cols);
2373 }
2374
2375 /* The cursor may have been moved when resizing. */
2376 vterm_state_get_cursorpos(state, &pos);
2377 position_cursor(wp, &pos);
2378
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002379 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2380 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002381 {
2382 int off = screen_get_current_line_off();
2383 int max_col = MIN(wp->w_width, term->tl_cols);
2384
2385 if (pos.row < term->tl_rows)
2386 {
2387 for (pos.col = 0; pos.col < max_col; )
2388 {
2389 VTermScreenCell cell;
2390 int c;
2391
2392 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2393 vim_memset(&cell, 0, sizeof(cell));
2394
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002395 c = cell.chars[0];
2396 if (c == NUL)
2397 {
2398 ScreenLines[off] = ' ';
2399 if (enc_utf8)
2400 ScreenLinesUC[off] = NUL;
2401 }
2402 else
2403 {
2404 if (enc_utf8)
2405 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002406 int i;
2407
2408 /* composing chars */
2409 for (i = 0; i < Screen_mco
2410 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2411 {
2412 ScreenLinesC[i][off] = cell.chars[i + 1];
2413 if (cell.chars[i + 1] == 0)
2414 break;
2415 }
2416 if (c >= 0x80 || (Screen_mco > 0
2417 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002418 {
2419 ScreenLines[off] = ' ';
2420 ScreenLinesUC[off] = c;
2421 }
2422 else
2423 {
2424 ScreenLines[off] = c;
2425 ScreenLinesUC[off] = NUL;
2426 }
2427 }
2428#ifdef WIN3264
2429 else if (has_mbyte && c >= 0x80)
2430 {
2431 char_u mb[MB_MAXBYTES+1];
2432 WCHAR wc = c;
2433
2434 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2435 (char*)mb, 2, 0, 0) > 1)
2436 {
2437 ScreenLines[off] = mb[0];
2438 ScreenLines[off + 1] = mb[1];
2439 cell.width = mb_ptr2cells(mb);
2440 }
2441 else
2442 ScreenLines[off] = c;
2443 }
2444#endif
2445 else
2446 ScreenLines[off] = c;
2447 }
2448 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2449
2450 ++pos.col;
2451 ++off;
2452 if (cell.width == 2)
2453 {
2454 if (enc_utf8)
2455 ScreenLinesUC[off] = NUL;
2456
2457 /* don't set the second byte to NUL for a DBCS encoding, it
2458 * has been set above */
2459 if (enc_utf8 || !has_mbyte)
2460 ScreenLines[off] = NUL;
2461
2462 ++pos.col;
2463 ++off;
2464 }
2465 }
2466 }
2467 else
2468 pos.col = 0;
2469
Bram Moolenaar181ca992018-02-13 21:19:21 +01002470 screen_line(wp->w_winrow + pos.row + winbar_height(wp),
2471 wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002472 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002473 term->tl_dirty_row_start = MAX_ROW;
2474 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002475
2476 return OK;
2477}
2478
2479/*
2480 * Return TRUE if "wp" is a terminal window where the job has finished.
2481 */
2482 int
2483term_is_finished(buf_T *buf)
2484{
2485 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2486}
2487
2488/*
2489 * Return TRUE if "wp" is a terminal window where the job has finished or we
2490 * are in Terminal-Normal mode, thus we show the buffer contents.
2491 */
2492 int
2493term_show_buffer(buf_T *buf)
2494{
2495 term_T *term = buf->b_term;
2496
2497 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2498}
2499
2500/*
2501 * The current buffer is going to be changed. If there is terminal
2502 * highlighting remove it now.
2503 */
2504 void
2505term_change_in_curbuf(void)
2506{
2507 term_T *term = curbuf->b_term;
2508
2509 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2510 {
2511 free_scrollback(term);
2512 redraw_buf_later(term->tl_buffer, NOT_VALID);
2513
2514 /* The buffer is now like a normal buffer, it cannot be easily
2515 * abandoned when changed. */
2516 set_string_option_direct((char_u *)"buftype", -1,
2517 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2518 }
2519}
2520
2521/*
2522 * Get the screen attribute for a position in the buffer.
2523 * Use a negative "col" to get the filler background color.
2524 */
2525 int
2526term_get_attr(buf_T *buf, linenr_T lnum, int col)
2527{
2528 term_T *term = buf->b_term;
2529 sb_line_T *line;
2530 cellattr_T *cellattr;
2531
2532 if (lnum > term->tl_scrollback.ga_len)
2533 cellattr = &term->tl_default_color;
2534 else
2535 {
2536 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2537 if (col < 0 || col >= line->sb_cols)
2538 cellattr = &line->sb_fill_attr;
2539 else
2540 cellattr = line->sb_cells + col;
2541 }
2542 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2543}
2544
2545static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002546 { 0, 0, 0, 1}, /* black */
2547 {224, 0, 0, 2}, /* dark red */
2548 { 0, 224, 0, 3}, /* dark green */
2549 {224, 224, 0, 4}, /* dark yellow / brown */
2550 { 0, 0, 224, 5}, /* dark blue */
2551 {224, 0, 224, 6}, /* dark magenta */
2552 { 0, 224, 224, 7}, /* dark cyan */
2553 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002554
Bram Moolenaar46359e12017-11-29 22:33:38 +01002555 {128, 128, 128, 9}, /* dark grey */
2556 {255, 64, 64, 10}, /* light red */
2557 { 64, 255, 64, 11}, /* light green */
2558 {255, 255, 64, 12}, /* yellow */
2559 { 64, 64, 255, 13}, /* light blue */
2560 {255, 64, 255, 14}, /* light magenta */
2561 { 64, 255, 255, 15}, /* light cyan */
2562 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002563};
2564
2565static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002566 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002567};
2568
2569static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002570 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2571 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002572};
2573
2574/*
2575 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002576 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002577 */
2578 static void
2579cterm_color2rgb(int nr, VTermColor *rgb)
2580{
2581 int idx;
2582
2583 if (nr < 16)
2584 {
2585 *rgb = ansi_table[nr];
2586 }
2587 else if (nr < 232)
2588 {
2589 /* 216 color cube */
2590 idx = nr - 16;
2591 rgb->blue = cube_value[idx % 6];
2592 rgb->green = cube_value[idx / 6 % 6];
2593 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002594 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002595 }
2596 else if (nr < 256)
2597 {
2598 /* 24 grey scale ramp */
2599 idx = nr - 232;
2600 rgb->blue = grey_ramp[idx];
2601 rgb->green = grey_ramp[idx];
2602 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002603 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002604 }
2605}
2606
2607/*
2608 * Create a new vterm and initialize it.
2609 */
2610 static void
2611create_vterm(term_T *term, int rows, int cols)
2612{
2613 VTerm *vterm;
2614 VTermScreen *screen;
2615 VTermValue value;
2616 VTermColor *fg, *bg;
2617 int fgval, bgval;
2618 int id;
2619
2620 vterm = vterm_new(rows, cols);
2621 term->tl_vterm = vterm;
2622 screen = vterm_obtain_screen(vterm);
2623 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2624 /* TODO: depends on 'encoding'. */
2625 vterm_set_utf8(vterm, 1);
2626
2627 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2628 term->tl_default_color.width = 1;
2629 fg = &term->tl_default_color.fg;
2630 bg = &term->tl_default_color.bg;
2631
2632 /* Vterm uses a default black background. Set it to white when
2633 * 'background' is "light". */
2634 if (*p_bg == 'l')
2635 {
2636 fgval = 0;
2637 bgval = 255;
2638 }
2639 else
2640 {
2641 fgval = 255;
2642 bgval = 0;
2643 }
2644 fg->red = fg->green = fg->blue = fgval;
2645 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002646 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002647
2648 /* The "Terminal" highlight group overrules the defaults. */
2649 id = syn_name2id((char_u *)"Terminal");
2650
Bram Moolenaar46359e12017-11-29 22:33:38 +01002651 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2653 if (0
2654# ifdef FEAT_GUI
2655 || gui.in_use
2656# endif
2657# ifdef FEAT_TERMGUICOLORS
2658 || p_tgc
2659# endif
2660 )
2661 {
2662 guicolor_T fg_rgb = INVALCOLOR;
2663 guicolor_T bg_rgb = INVALCOLOR;
2664
2665 if (id != 0)
2666 syn_id2colors(id, &fg_rgb, &bg_rgb);
2667
2668# ifdef FEAT_GUI
2669 if (gui.in_use)
2670 {
2671 if (fg_rgb == INVALCOLOR)
2672 fg_rgb = gui.norm_pixel;
2673 if (bg_rgb == INVALCOLOR)
2674 bg_rgb = gui.back_pixel;
2675 }
2676# ifdef FEAT_TERMGUICOLORS
2677 else
2678# endif
2679# endif
2680# ifdef FEAT_TERMGUICOLORS
2681 {
2682 if (fg_rgb == INVALCOLOR)
2683 fg_rgb = cterm_normal_fg_gui_color;
2684 if (bg_rgb == INVALCOLOR)
2685 bg_rgb = cterm_normal_bg_gui_color;
2686 }
2687# endif
2688 if (fg_rgb != INVALCOLOR)
2689 {
2690 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2691
2692 fg->red = (unsigned)(rgb >> 16);
2693 fg->green = (unsigned)(rgb >> 8) & 255;
2694 fg->blue = (unsigned)rgb & 255;
2695 }
2696 if (bg_rgb != INVALCOLOR)
2697 {
2698 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2699
2700 bg->red = (unsigned)(rgb >> 16);
2701 bg->green = (unsigned)(rgb >> 8) & 255;
2702 bg->blue = (unsigned)rgb & 255;
2703 }
2704 }
2705 else
2706#endif
2707 if (id != 0 && t_colors >= 16)
2708 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002709 if (term_default_cterm_fg >= 0)
2710 cterm_color2rgb(term_default_cterm_fg, fg);
2711 if (term_default_cterm_bg >= 0)
2712 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002713 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002714 else
2715 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002716#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002718#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002719
2720 /* In an MS-Windows console we know the normal colors. */
2721 if (cterm_normal_fg_color > 0)
2722 {
2723 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002724# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002725 tmp = fg->red;
2726 fg->red = fg->blue;
2727 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002728# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002729 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002730# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002731 else
2732 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002733# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002734
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002735 if (cterm_normal_bg_color > 0)
2736 {
2737 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002738# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002739 tmp = bg->red;
2740 bg->red = bg->blue;
2741 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002742# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002743 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002744# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002745 else
2746 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002747# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002748 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002749
2750 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2751
2752 /* Required to initialize most things. */
2753 vterm_screen_reset(screen, 1 /* hard */);
2754
2755 /* Allow using alternate screen. */
2756 vterm_screen_enable_altscreen(screen, 1);
2757
2758 /* For unix do not use a blinking cursor. In an xterm this causes the
2759 * cursor to blink if it's blinking in the xterm.
2760 * For Windows we respect the system wide setting. */
2761#ifdef WIN3264
2762 if (GetCaretBlinkTime() == INFINITE)
2763 value.boolean = 0;
2764 else
2765 value.boolean = 1;
2766#else
2767 value.boolean = 0;
2768#endif
2769 vterm_state_set_termprop(vterm_obtain_state(vterm),
2770 VTERM_PROP_CURSORBLINK, &value);
2771}
2772
2773/*
2774 * Return the text to show for the buffer name and status.
2775 */
2776 char_u *
2777term_get_status_text(term_T *term)
2778{
2779 if (term->tl_status_text == NULL)
2780 {
2781 char_u *txt;
2782 size_t len;
2783
2784 if (term->tl_normal_mode)
2785 {
2786 if (term_job_running(term))
2787 txt = (char_u *)_("Terminal");
2788 else
2789 txt = (char_u *)_("Terminal-finished");
2790 }
2791 else if (term->tl_title != NULL)
2792 txt = term->tl_title;
2793 else if (term_none_open(term))
2794 txt = (char_u *)_("active");
2795 else if (term_job_running(term))
2796 txt = (char_u *)_("running");
2797 else
2798 txt = (char_u *)_("finished");
2799 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2800 term->tl_status_text = alloc((int)len);
2801 if (term->tl_status_text != NULL)
2802 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2803 term->tl_buffer->b_fname, txt);
2804 }
2805 return term->tl_status_text;
2806}
2807
2808/*
2809 * Mark references in jobs of terminals.
2810 */
2811 int
2812set_ref_in_term(int copyID)
2813{
2814 int abort = FALSE;
2815 term_T *term;
2816 typval_T tv;
2817
2818 for (term = first_term; term != NULL; term = term->tl_next)
2819 if (term->tl_job != NULL)
2820 {
2821 tv.v_type = VAR_JOB;
2822 tv.vval.v_job = term->tl_job;
2823 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2824 }
2825 return abort;
2826}
2827
2828/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002829 * Cache "Terminal" highlight group colors.
2830 */
2831 void
2832set_terminal_default_colors(int cterm_fg, int cterm_bg)
2833{
2834 term_default_cterm_fg = cterm_fg - 1;
2835 term_default_cterm_bg = cterm_bg - 1;
2836}
2837
2838/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002839 * Get the buffer from the first argument in "argvars".
2840 * Returns NULL when the buffer is not for a terminal window.
2841 */
2842 static buf_T *
2843term_get_buf(typval_T *argvars)
2844{
2845 buf_T *buf;
2846
2847 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2848 ++emsg_off;
2849 buf = get_buf_tv(&argvars[0], FALSE);
2850 --emsg_off;
2851 if (buf == NULL || buf->b_term == NULL)
2852 return NULL;
2853 return buf;
2854}
2855
Bram Moolenaard96ff162018-02-18 22:13:29 +01002856 static int
2857same_color(VTermColor *a, VTermColor *b)
2858{
2859 return a->red == b->red
2860 && a->green == b->green
2861 && a->blue == b->blue
2862 && a->ansi_index == b->ansi_index;
2863}
2864
2865 static void
2866dump_term_color(FILE *fd, VTermColor *color)
2867{
2868 fprintf(fd, "%02x%02x%02x%d",
2869 (int)color->red, (int)color->green, (int)color->blue,
2870 (int)color->ansi_index);
2871}
2872
2873/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002874 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01002875 *
2876 * Each screen cell in full is:
2877 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
2878 * {characters} is a space for an empty cell
2879 * For a double-width character "+" is changed to "*" and the next cell is
2880 * skipped.
2881 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
2882 * when "&" use the same as the previous cell.
2883 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
2884 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
2885 * {color-idx} is a number from 0 to 255
2886 *
2887 * Screen cell with same width, attributes and color as the previous one:
2888 * |{characters}
2889 *
2890 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
2891 *
2892 * Repeating the previous screen cell:
2893 * @{count}
2894 */
2895 void
2896f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
2897{
2898 buf_T *buf = term_get_buf(argvars);
2899 term_T *term;
2900 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002901 int max_height = 0;
2902 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002903 stat_T st;
2904 FILE *fd;
2905 VTermPos pos;
2906 VTermScreen *screen;
2907 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01002908 VTermState *state;
2909 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002910
2911 if (check_restricted() || check_secure())
2912 return;
2913 if (buf == NULL)
2914 return;
2915 term = buf->b_term;
2916
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002917 if (argvars[2].v_type != VAR_UNKNOWN)
2918 {
2919 dict_T *d;
2920
2921 if (argvars[2].v_type != VAR_DICT)
2922 {
2923 EMSG(_(e_dictreq));
2924 return;
2925 }
2926 d = argvars[2].vval.v_dict;
2927 if (d != NULL)
2928 {
2929 max_height = get_dict_number(d, (char_u *)"rows");
2930 max_width = get_dict_number(d, (char_u *)"columns");
2931 }
2932 }
2933
Bram Moolenaard96ff162018-02-18 22:13:29 +01002934 fname = get_tv_string_chk(&argvars[1]);
2935 if (fname == NULL)
2936 return;
2937 if (mch_stat((char *)fname, &st) >= 0)
2938 {
2939 EMSG2(_("E953: File exists: %s"), fname);
2940 return;
2941 }
2942
Bram Moolenaard96ff162018-02-18 22:13:29 +01002943 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
2944 {
2945 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2946 return;
2947 }
2948
2949 vim_memset(&prev_cell, 0, sizeof(prev_cell));
2950
2951 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01002952 state = vterm_obtain_state(term->tl_vterm);
2953 vterm_state_get_cursorpos(state, &cursor_pos);
2954
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002955 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
2956 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002957 {
2958 int repeat = 0;
2959
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002960 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
2961 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002962 {
2963 VTermScreenCell cell;
2964 int same_attr;
2965 int same_chars = TRUE;
2966 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01002967 int is_cursor_pos = (pos.col == cursor_pos.col
2968 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002969
2970 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2971 vim_memset(&cell, 0, sizeof(cell));
2972
2973 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
2974 {
2975 if (cell.chars[i] != prev_cell.chars[i])
2976 same_chars = FALSE;
2977 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
2978 break;
2979 }
2980 same_attr = vtermAttr2hl(cell.attrs)
2981 == vtermAttr2hl(prev_cell.attrs)
2982 && same_color(&cell.fg, &prev_cell.fg)
2983 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01002984 if (same_chars && cell.width == prev_cell.width && same_attr
2985 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002986 {
2987 ++repeat;
2988 }
2989 else
2990 {
2991 if (repeat > 0)
2992 {
2993 fprintf(fd, "@%d", repeat);
2994 repeat = 0;
2995 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01002996 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002997
2998 if (cell.chars[0] == NUL)
2999 fputs(" ", fd);
3000 else
3001 {
3002 char_u charbuf[10];
3003 int len;
3004
3005 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3006 && cell.chars[i] != NUL; ++i)
3007 {
3008 len = utf_char2bytes(cell.chars[0], charbuf);
3009 fwrite(charbuf, len, 1, fd);
3010 }
3011 }
3012
3013 /* When only the characters differ we don't write anything, the
3014 * following "|", "@" or NL will indicate using the same
3015 * attributes. */
3016 if (cell.width != prev_cell.width || !same_attr)
3017 {
3018 if (cell.width == 2)
3019 {
3020 fputs("*", fd);
3021 ++pos.col;
3022 }
3023 else
3024 fputs("+", fd);
3025
3026 if (same_attr)
3027 {
3028 fputs("&", fd);
3029 }
3030 else
3031 {
3032 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3033 if (same_color(&cell.fg, &prev_cell.fg))
3034 fputs("&", fd);
3035 else
3036 {
3037 fputs("#", fd);
3038 dump_term_color(fd, &cell.fg);
3039 }
3040 if (same_color(&cell.bg, &prev_cell.bg))
3041 fputs("&", fd);
3042 else
3043 {
3044 fputs("#", fd);
3045 dump_term_color(fd, &cell.bg);
3046 }
3047 }
3048 }
3049
3050 prev_cell = cell;
3051 }
3052 }
3053 if (repeat > 0)
3054 fprintf(fd, "@%d", repeat);
3055 fputs("\n", fd);
3056 }
3057
3058 fclose(fd);
3059}
3060
3061/*
3062 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3063 */
3064 static void
3065dump_is_corrupt(garray_T *gap)
3066{
3067 ga_concat(gap, (char_u *)"CORRUPT");
3068}
3069
3070 static void
3071append_cell(garray_T *gap, cellattr_T *cell)
3072{
3073 if (ga_grow(gap, 1) == OK)
3074 {
3075 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3076 ++gap->ga_len;
3077 }
3078}
3079
3080/*
3081 * Read the dump file from "fd" and append lines to the current buffer.
3082 * Return the cell width of the longest line.
3083 */
3084 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003085read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003086{
3087 int c;
3088 garray_T ga_text;
3089 garray_T ga_cell;
3090 char_u *prev_char = NULL;
3091 int attr = 0;
3092 cellattr_T cell;
3093 term_T *term = curbuf->b_term;
3094 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003095 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003096
3097 ga_init2(&ga_text, 1, 90);
3098 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3099 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003100 cursor_pos->row = -1;
3101 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003102
3103 c = fgetc(fd);
3104 for (;;)
3105 {
3106 if (c == EOF)
3107 break;
3108 if (c == '\n')
3109 {
3110 /* End of a line: append it to the buffer. */
3111 if (ga_text.ga_data == NULL)
3112 dump_is_corrupt(&ga_text);
3113 if (ga_grow(&term->tl_scrollback, 1) == OK)
3114 {
3115 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3116 + term->tl_scrollback.ga_len;
3117
3118 if (max_cells < ga_cell.ga_len)
3119 max_cells = ga_cell.ga_len;
3120 line->sb_cols = ga_cell.ga_len;
3121 line->sb_cells = ga_cell.ga_data;
3122 line->sb_fill_attr = term->tl_default_color;
3123 ++term->tl_scrollback.ga_len;
3124 ga_init(&ga_cell);
3125
3126 ga_append(&ga_text, NUL);
3127 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3128 ga_text.ga_len, FALSE);
3129 }
3130 else
3131 ga_clear(&ga_cell);
3132 ga_text.ga_len = 0;
3133
3134 c = fgetc(fd);
3135 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003136 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003137 {
3138 int prev_len = ga_text.ga_len;
3139
Bram Moolenaar9271d052018-02-25 21:39:46 +01003140 if (c == '>')
3141 {
3142 if (cursor_pos->row != -1)
3143 dump_is_corrupt(&ga_text); /* duplicate cursor */
3144 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3145 cursor_pos->col = ga_cell.ga_len;
3146 }
3147
Bram Moolenaard96ff162018-02-18 22:13:29 +01003148 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3149 c = fgetc(fd);
3150 if (c != EOF)
3151 ga_append(&ga_text, c);
3152 for (;;)
3153 {
3154 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003155 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003156 || c == EOF || c == '\n')
3157 break;
3158 ga_append(&ga_text, c);
3159 }
3160
3161 /* save the character for repeating it */
3162 vim_free(prev_char);
3163 if (ga_text.ga_data != NULL)
3164 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3165 ga_text.ga_len - prev_len);
3166
Bram Moolenaar9271d052018-02-25 21:39:46 +01003167 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003168 {
3169 /* use all attributes from previous cell */
3170 }
3171 else if (c == '+' || c == '*')
3172 {
3173 int is_bg;
3174
3175 cell.width = c == '+' ? 1 : 2;
3176
3177 c = fgetc(fd);
3178 if (c == '&')
3179 {
3180 /* use same attr as previous cell */
3181 c = fgetc(fd);
3182 }
3183 else if (isdigit(c))
3184 {
3185 /* get the decimal attribute */
3186 attr = 0;
3187 while (isdigit(c))
3188 {
3189 attr = attr * 10 + (c - '0');
3190 c = fgetc(fd);
3191 }
3192 hl2vtermAttr(attr, &cell);
3193 }
3194 else
3195 dump_is_corrupt(&ga_text);
3196
3197 /* is_bg == 0: fg, is_bg == 1: bg */
3198 for (is_bg = 0; is_bg <= 1; ++is_bg)
3199 {
3200 if (c == '&')
3201 {
3202 /* use same color as previous cell */
3203 c = fgetc(fd);
3204 }
3205 else if (c == '#')
3206 {
3207 int red, green, blue, index = 0;
3208
3209 c = fgetc(fd);
3210 red = hex2nr(c);
3211 c = fgetc(fd);
3212 red = (red << 4) + hex2nr(c);
3213 c = fgetc(fd);
3214 green = hex2nr(c);
3215 c = fgetc(fd);
3216 green = (green << 4) + hex2nr(c);
3217 c = fgetc(fd);
3218 blue = hex2nr(c);
3219 c = fgetc(fd);
3220 blue = (blue << 4) + hex2nr(c);
3221 c = fgetc(fd);
3222 if (!isdigit(c))
3223 dump_is_corrupt(&ga_text);
3224 while (isdigit(c))
3225 {
3226 index = index * 10 + (c - '0');
3227 c = fgetc(fd);
3228 }
3229
3230 if (is_bg)
3231 {
3232 cell.bg.red = red;
3233 cell.bg.green = green;
3234 cell.bg.blue = blue;
3235 cell.bg.ansi_index = index;
3236 }
3237 else
3238 {
3239 cell.fg.red = red;
3240 cell.fg.green = green;
3241 cell.fg.blue = blue;
3242 cell.fg.ansi_index = index;
3243 }
3244 }
3245 else
3246 dump_is_corrupt(&ga_text);
3247 }
3248 }
3249 else
3250 dump_is_corrupt(&ga_text);
3251
3252 append_cell(&ga_cell, &cell);
3253 }
3254 else if (c == '@')
3255 {
3256 if (prev_char == NULL)
3257 dump_is_corrupt(&ga_text);
3258 else
3259 {
3260 int count = 0;
3261
3262 /* repeat previous character, get the count */
3263 for (;;)
3264 {
3265 c = fgetc(fd);
3266 if (!isdigit(c))
3267 break;
3268 count = count * 10 + (c - '0');
3269 }
3270
3271 while (count-- > 0)
3272 {
3273 ga_concat(&ga_text, prev_char);
3274 append_cell(&ga_cell, &cell);
3275 }
3276 }
3277 }
3278 else
3279 {
3280 dump_is_corrupt(&ga_text);
3281 c = fgetc(fd);
3282 }
3283 }
3284
3285 if (ga_text.ga_len > 0)
3286 {
3287 /* trailing characters after last NL */
3288 dump_is_corrupt(&ga_text);
3289 ga_append(&ga_text, NUL);
3290 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3291 ga_text.ga_len, FALSE);
3292 }
3293
3294 ga_clear(&ga_text);
3295 vim_free(prev_char);
3296
3297 return max_cells;
3298}
3299
3300/*
3301 * Common for "term_dumpdiff()" and "term_dumpload()".
3302 */
3303 static void
3304term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
3305{
3306 jobopt_T opt;
3307 buf_T *buf;
3308 char_u buf1[NUMBUFLEN];
3309 char_u buf2[NUMBUFLEN];
3310 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003311 char_u *fname2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003312 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003313 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003314 char_u *textline = NULL;
3315
3316 /* First open the files. If this fails bail out. */
3317 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
3318 if (do_diff)
3319 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
3320 if (fname1 == NULL || (do_diff && fname2 == NULL))
3321 {
3322 EMSG(_(e_invarg));
3323 return;
3324 }
3325 fd1 = mch_fopen((char *)fname1, READBIN);
3326 if (fd1 == NULL)
3327 {
3328 EMSG2(_(e_notread), fname1);
3329 return;
3330 }
3331 if (do_diff)
3332 {
3333 fd2 = mch_fopen((char *)fname2, READBIN);
3334 if (fd2 == NULL)
3335 {
3336 fclose(fd1);
3337 EMSG2(_(e_notread), fname2);
3338 return;
3339 }
3340 }
3341
3342 init_job_options(&opt);
3343 /* TODO: use the {options} argument */
3344
3345 /* TODO: use the file name arguments for the buffer name */
3346 opt.jo_term_name = (char_u *)"dump diff";
3347
3348 buf = term_start(&argvars[0], &opt, TRUE, FALSE);
3349 if (buf != NULL && buf->b_term != NULL)
3350 {
3351 int i;
3352 linenr_T bot_lnum;
3353 linenr_T lnum;
3354 term_T *term = buf->b_term;
3355 int width;
3356 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003357 VTermPos cursor_pos1;
3358 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003359
3360 rettv->vval.v_number = buf->b_fnum;
3361
3362 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01003363 width = read_dump_file(fd1, &cursor_pos1);
3364
3365 /* position the cursor */
3366 if (cursor_pos1.row >= 0)
3367 {
3368 curwin->w_cursor.lnum = cursor_pos1.row + 1;
3369 coladvance(cursor_pos1.col);
3370 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003371
3372 /* Delete the empty line that was in the empty buffer. */
3373 ml_delete(1, FALSE);
3374
3375 /* For term_dumpload() we are done here. */
3376 if (!do_diff)
3377 goto theend;
3378
3379 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
3380
3381 textline = alloc(width + 1);
3382 if (textline == NULL)
3383 goto theend;
3384 for (i = 0; i < width; ++i)
3385 textline[i] = '=';
3386 textline[width] = NUL;
3387 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3388 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3389 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3390 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3391
3392 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003393 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003394 if (width2 > width)
3395 {
3396 vim_free(textline);
3397 textline = alloc(width2 + 1);
3398 if (textline == NULL)
3399 goto theend;
3400 width = width2;
3401 textline[width] = NUL;
3402 }
3403 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
3404
3405 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
3406 {
3407 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
3408 {
3409 /* bottom part has fewer rows, fill with "-" */
3410 for (i = 0; i < width; ++i)
3411 textline[i] = '-';
3412 }
3413 else
3414 {
3415 char_u *line1;
3416 char_u *line2;
3417 char_u *p1;
3418 char_u *p2;
3419 int col;
3420 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3421 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
3422 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
3423 ->sb_cells;
3424
3425 /* Make a copy, getting the second line will invalidate it. */
3426 line1 = vim_strsave(ml_get(lnum));
3427 if (line1 == NULL)
3428 break;
3429 p1 = line1;
3430
3431 line2 = ml_get(lnum + bot_lnum);
3432 p2 = line2;
3433 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
3434 {
3435 int len1 = utfc_ptr2len(p1);
3436 int len2 = utfc_ptr2len(p2);
3437
3438 textline[col] = ' ';
3439 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01003440 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01003441 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01003442 else if (lnum == cursor_pos1.row + 1
3443 && col == cursor_pos1.col
3444 && (cursor_pos1.row != cursor_pos2.row
3445 || cursor_pos1.col != cursor_pos2.col))
3446 /* cursor in first but not in second */
3447 textline[col] = '>';
3448 else if (lnum == cursor_pos2.row + 1
3449 && col == cursor_pos2.col
3450 && (cursor_pos1.row != cursor_pos2.row
3451 || cursor_pos1.col != cursor_pos2.col))
3452 /* cursor in second but not in first */
3453 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01003454 else if (cellattr1 != NULL && cellattr2 != NULL)
3455 {
3456 if ((cellattr1 + col)->width
3457 != (cellattr2 + col)->width)
3458 textline[col] = 'w';
3459 else if (!same_color(&(cellattr1 + col)->fg,
3460 &(cellattr2 + col)->fg))
3461 textline[col] = 'f';
3462 else if (!same_color(&(cellattr1 + col)->bg,
3463 &(cellattr2 + col)->bg))
3464 textline[col] = 'b';
3465 else if (vtermAttr2hl((cellattr1 + col)->attrs)
3466 != vtermAttr2hl(((cellattr2 + col)->attrs)))
3467 textline[col] = 'a';
3468 }
3469 p1 += len1;
3470 p2 += len2;
3471 /* TODO: handle different width */
3472 }
3473 vim_free(line1);
3474
3475 while (col < width)
3476 {
3477 if (*p1 == NUL && *p2 == NUL)
3478 textline[col] = '?';
3479 else if (*p1 == NUL)
3480 {
3481 textline[col] = '+';
3482 p2 += utfc_ptr2len(p2);
3483 }
3484 else
3485 {
3486 textline[col] = '-';
3487 p1 += utfc_ptr2len(p1);
3488 }
3489 ++col;
3490 }
3491 }
3492 if (add_empty_scrollback(term, &term->tl_default_color,
3493 term->tl_top_diff_rows) == OK)
3494 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3495 ++bot_lnum;
3496 }
3497
3498 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
3499 {
3500 /* bottom part has more rows, fill with "+" */
3501 for (i = 0; i < width; ++i)
3502 textline[i] = '+';
3503 if (add_empty_scrollback(term, &term->tl_default_color,
3504 term->tl_top_diff_rows) == OK)
3505 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3506 ++lnum;
3507 ++bot_lnum;
3508 }
3509
3510 term->tl_cols = width;
3511 }
3512
3513theend:
3514 vim_free(textline);
3515 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003516 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003517 fclose(fd2);
3518}
3519
3520/*
3521 * If the current buffer shows the output of term_dumpdiff(), swap the top and
3522 * bottom files.
3523 * Return FAIL when this is not possible.
3524 */
3525 int
3526term_swap_diff()
3527{
3528 term_T *term = curbuf->b_term;
3529 linenr_T line_count;
3530 linenr_T top_rows;
3531 linenr_T bot_rows;
3532 linenr_T bot_start;
3533 linenr_T lnum;
3534 char_u *p;
3535 sb_line_T *sb_line;
3536
3537 if (term == NULL
3538 || !term_is_finished(curbuf)
3539 || term->tl_top_diff_rows == 0
3540 || term->tl_scrollback.ga_len == 0)
3541 return FAIL;
3542
3543 line_count = curbuf->b_ml.ml_line_count;
3544 top_rows = term->tl_top_diff_rows;
3545 bot_rows = term->tl_bot_diff_rows;
3546 bot_start = line_count - bot_rows;
3547 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3548
3549 /* move lines from top to above the bottom part */
3550 for (lnum = 1; lnum <= top_rows; ++lnum)
3551 {
3552 p = vim_strsave(ml_get(1));
3553 if (p == NULL)
3554 return OK;
3555 ml_append(bot_start, p, 0, FALSE);
3556 ml_delete(1, FALSE);
3557 vim_free(p);
3558 }
3559
3560 /* move lines from bottom to the top */
3561 for (lnum = 1; lnum <= bot_rows; ++lnum)
3562 {
3563 p = vim_strsave(ml_get(bot_start + lnum));
3564 if (p == NULL)
3565 return OK;
3566 ml_delete(bot_start + lnum, FALSE);
3567 ml_append(lnum - 1, p, 0, FALSE);
3568 vim_free(p);
3569 }
3570
3571 if (top_rows == bot_rows)
3572 {
3573 /* rows counts are equal, can swap cell properties */
3574 for (lnum = 0; lnum < top_rows; ++lnum)
3575 {
3576 sb_line_T temp;
3577
3578 temp = *(sb_line + lnum);
3579 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
3580 *(sb_line + bot_start + lnum) = temp;
3581 }
3582 }
3583 else
3584 {
3585 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
3586 sb_line_T *temp = (sb_line_T *)alloc((int)size);
3587
3588 /* need to copy cell properties into temp memory */
3589 if (temp != NULL)
3590 {
3591 mch_memmove(temp, term->tl_scrollback.ga_data, size);
3592 mch_memmove(term->tl_scrollback.ga_data,
3593 temp + bot_start,
3594 sizeof(sb_line_T) * bot_rows);
3595 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
3596 temp + top_rows,
3597 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
3598 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
3599 + line_count - top_rows,
3600 temp,
3601 sizeof(sb_line_T) * top_rows);
3602 vim_free(temp);
3603 }
3604 }
3605
3606 term->tl_top_diff_rows = bot_rows;
3607 term->tl_bot_diff_rows = top_rows;
3608
3609 update_screen(NOT_VALID);
3610 return OK;
3611}
3612
3613/*
3614 * "term_dumpdiff(filename, filename, options)" function
3615 */
3616 void
3617f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
3618{
3619 term_load_dump(argvars, rettv, TRUE);
3620}
3621
3622/*
3623 * "term_dumpload(filename, options)" function
3624 */
3625 void
3626f_term_dumpload(typval_T *argvars, typval_T *rettv)
3627{
3628 term_load_dump(argvars, rettv, FALSE);
3629}
3630
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003631/*
3632 * "term_getaltscreen(buf)" function
3633 */
3634 void
3635f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
3636{
3637 buf_T *buf = term_get_buf(argvars);
3638
3639 if (buf == NULL)
3640 return;
3641 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
3642}
3643
3644/*
3645 * "term_getattr(attr, name)" function
3646 */
3647 void
3648f_term_getattr(typval_T *argvars, typval_T *rettv)
3649{
3650 int attr;
3651 size_t i;
3652 char_u *name;
3653
3654 static struct {
3655 char *name;
3656 int attr;
3657 } attrs[] = {
3658 {"bold", HL_BOLD},
3659 {"italic", HL_ITALIC},
3660 {"underline", HL_UNDERLINE},
3661 {"strike", HL_STRIKETHROUGH},
3662 {"reverse", HL_INVERSE},
3663 };
3664
3665 attr = get_tv_number(&argvars[0]);
3666 name = get_tv_string_chk(&argvars[1]);
3667 if (name == NULL)
3668 return;
3669
3670 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
3671 if (STRCMP(name, attrs[i].name) == 0)
3672 {
3673 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
3674 break;
3675 }
3676}
3677
3678/*
3679 * "term_getcursor(buf)" function
3680 */
3681 void
3682f_term_getcursor(typval_T *argvars, typval_T *rettv)
3683{
3684 buf_T *buf = term_get_buf(argvars);
3685 term_T *term;
3686 list_T *l;
3687 dict_T *d;
3688
3689 if (rettv_list_alloc(rettv) == FAIL)
3690 return;
3691 if (buf == NULL)
3692 return;
3693 term = buf->b_term;
3694
3695 l = rettv->vval.v_list;
3696 list_append_number(l, term->tl_cursor_pos.row + 1);
3697 list_append_number(l, term->tl_cursor_pos.col + 1);
3698
3699 d = dict_alloc();
3700 if (d != NULL)
3701 {
3702 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
3703 dict_add_nr_str(d, "blink", blink_state_is_inverted()
3704 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
3705 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
3706 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
3707 ? (char_u *)"" : term->tl_cursor_color);
3708 list_append_dict(l, d);
3709 }
3710}
3711
3712/*
3713 * "term_getjob(buf)" function
3714 */
3715 void
3716f_term_getjob(typval_T *argvars, typval_T *rettv)
3717{
3718 buf_T *buf = term_get_buf(argvars);
3719
3720 rettv->v_type = VAR_JOB;
3721 rettv->vval.v_job = NULL;
3722 if (buf == NULL)
3723 return;
3724
3725 rettv->vval.v_job = buf->b_term->tl_job;
3726 if (rettv->vval.v_job != NULL)
3727 ++rettv->vval.v_job->jv_refcount;
3728}
3729
3730 static int
3731get_row_number(typval_T *tv, term_T *term)
3732{
3733 if (tv->v_type == VAR_STRING
3734 && tv->vval.v_string != NULL
3735 && STRCMP(tv->vval.v_string, ".") == 0)
3736 return term->tl_cursor_pos.row;
3737 return (int)get_tv_number(tv) - 1;
3738}
3739
3740/*
3741 * "term_getline(buf, row)" function
3742 */
3743 void
3744f_term_getline(typval_T *argvars, typval_T *rettv)
3745{
3746 buf_T *buf = term_get_buf(argvars);
3747 term_T *term;
3748 int row;
3749
3750 rettv->v_type = VAR_STRING;
3751 if (buf == NULL)
3752 return;
3753 term = buf->b_term;
3754 row = get_row_number(&argvars[1], term);
3755
3756 if (term->tl_vterm == NULL)
3757 {
3758 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
3759
3760 /* vterm is finished, get the text from the buffer */
3761 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
3762 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
3763 }
3764 else
3765 {
3766 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
3767 VTermRect rect;
3768 int len;
3769 char_u *p;
3770
3771 if (row < 0 || row >= term->tl_rows)
3772 return;
3773 len = term->tl_cols * MB_MAXBYTES + 1;
3774 p = alloc(len);
3775 if (p == NULL)
3776 return;
3777 rettv->vval.v_string = p;
3778
3779 rect.start_col = 0;
3780 rect.end_col = term->tl_cols;
3781 rect.start_row = row;
3782 rect.end_row = row + 1;
3783 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
3784 }
3785}
3786
3787/*
3788 * "term_getscrolled(buf)" function
3789 */
3790 void
3791f_term_getscrolled(typval_T *argvars, typval_T *rettv)
3792{
3793 buf_T *buf = term_get_buf(argvars);
3794
3795 if (buf == NULL)
3796 return;
3797 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
3798}
3799
3800/*
3801 * "term_getsize(buf)" function
3802 */
3803 void
3804f_term_getsize(typval_T *argvars, typval_T *rettv)
3805{
3806 buf_T *buf = term_get_buf(argvars);
3807 list_T *l;
3808
3809 if (rettv_list_alloc(rettv) == FAIL)
3810 return;
3811 if (buf == NULL)
3812 return;
3813
3814 l = rettv->vval.v_list;
3815 list_append_number(l, buf->b_term->tl_rows);
3816 list_append_number(l, buf->b_term->tl_cols);
3817}
3818
3819/*
3820 * "term_getstatus(buf)" function
3821 */
3822 void
3823f_term_getstatus(typval_T *argvars, typval_T *rettv)
3824{
3825 buf_T *buf = term_get_buf(argvars);
3826 term_T *term;
3827 char_u val[100];
3828
3829 rettv->v_type = VAR_STRING;
3830 if (buf == NULL)
3831 return;
3832 term = buf->b_term;
3833
3834 if (term_job_running(term))
3835 STRCPY(val, "running");
3836 else
3837 STRCPY(val, "finished");
3838 if (term->tl_normal_mode)
3839 STRCAT(val, ",normal");
3840 rettv->vval.v_string = vim_strsave(val);
3841}
3842
3843/*
3844 * "term_gettitle(buf)" function
3845 */
3846 void
3847f_term_gettitle(typval_T *argvars, typval_T *rettv)
3848{
3849 buf_T *buf = term_get_buf(argvars);
3850
3851 rettv->v_type = VAR_STRING;
3852 if (buf == NULL)
3853 return;
3854
3855 if (buf->b_term->tl_title != NULL)
3856 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
3857}
3858
3859/*
3860 * "term_gettty(buf)" function
3861 */
3862 void
3863f_term_gettty(typval_T *argvars, typval_T *rettv)
3864{
3865 buf_T *buf = term_get_buf(argvars);
3866 char_u *p;
3867 int num = 0;
3868
3869 rettv->v_type = VAR_STRING;
3870 if (buf == NULL)
3871 return;
3872 if (argvars[1].v_type != VAR_UNKNOWN)
3873 num = get_tv_number(&argvars[1]);
3874
3875 switch (num)
3876 {
3877 case 0:
3878 if (buf->b_term->tl_job != NULL)
3879 p = buf->b_term->tl_job->jv_tty_out;
3880 else
3881 p = buf->b_term->tl_tty_out;
3882 break;
3883 case 1:
3884 if (buf->b_term->tl_job != NULL)
3885 p = buf->b_term->tl_job->jv_tty_in;
3886 else
3887 p = buf->b_term->tl_tty_in;
3888 break;
3889 default:
3890 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
3891 return;
3892 }
3893 if (p != NULL)
3894 rettv->vval.v_string = vim_strsave(p);
3895}
3896
3897/*
3898 * "term_list()" function
3899 */
3900 void
3901f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3902{
3903 term_T *tp;
3904 list_T *l;
3905
3906 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3907 return;
3908
3909 l = rettv->vval.v_list;
3910 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3911 if (tp != NULL && tp->tl_buffer != NULL)
3912 if (list_append_number(l,
3913 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3914 return;
3915}
3916
3917/*
3918 * "term_scrape(buf, row)" function
3919 */
3920 void
3921f_term_scrape(typval_T *argvars, typval_T *rettv)
3922{
3923 buf_T *buf = term_get_buf(argvars);
3924 VTermScreen *screen = NULL;
3925 VTermPos pos;
3926 list_T *l;
3927 term_T *term;
3928 char_u *p;
3929 sb_line_T *line;
3930
3931 if (rettv_list_alloc(rettv) == FAIL)
3932 return;
3933 if (buf == NULL)
3934 return;
3935 term = buf->b_term;
3936
3937 l = rettv->vval.v_list;
3938 pos.row = get_row_number(&argvars[1], term);
3939
3940 if (term->tl_vterm != NULL)
3941 {
3942 screen = vterm_obtain_screen(term->tl_vterm);
3943 p = NULL;
3944 line = NULL;
3945 }
3946 else
3947 {
3948 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3949
3950 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3951 return;
3952 p = ml_get_buf(buf, lnum + 1, FALSE);
3953 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3954 }
3955
3956 for (pos.col = 0; pos.col < term->tl_cols; )
3957 {
3958 dict_T *dcell;
3959 int width;
3960 VTermScreenCellAttrs attrs;
3961 VTermColor fg, bg;
3962 char_u rgb[8];
3963 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3964 int off = 0;
3965 int i;
3966
3967 if (screen == NULL)
3968 {
3969 cellattr_T *cellattr;
3970 int len;
3971
3972 /* vterm has finished, get the cell from scrollback */
3973 if (pos.col >= line->sb_cols)
3974 break;
3975 cellattr = line->sb_cells + pos.col;
3976 width = cellattr->width;
3977 attrs = cellattr->attrs;
3978 fg = cellattr->fg;
3979 bg = cellattr->bg;
3980 len = MB_PTR2LEN(p);
3981 mch_memmove(mbs, p, len);
3982 mbs[len] = NUL;
3983 p += len;
3984 }
3985 else
3986 {
3987 VTermScreenCell cell;
3988 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3989 break;
3990 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3991 {
3992 if (cell.chars[i] == 0)
3993 break;
3994 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3995 }
3996 mbs[off] = NUL;
3997 width = cell.width;
3998 attrs = cell.attrs;
3999 fg = cell.fg;
4000 bg = cell.bg;
4001 }
4002 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004003 if (dcell == NULL)
4004 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004005 list_append_dict(l, dcell);
4006
4007 dict_add_nr_str(dcell, "chars", 0, mbs);
4008
4009 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4010 fg.red, fg.green, fg.blue);
4011 dict_add_nr_str(dcell, "fg", 0, rgb);
4012 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4013 bg.red, bg.green, bg.blue);
4014 dict_add_nr_str(dcell, "bg", 0, rgb);
4015
4016 dict_add_nr_str(dcell, "attr",
4017 cell2attr(attrs, fg, bg), NULL);
4018 dict_add_nr_str(dcell, "width", width, NULL);
4019
4020 ++pos.col;
4021 if (width == 2)
4022 ++pos.col;
4023 }
4024}
4025
4026/*
4027 * "term_sendkeys(buf, keys)" function
4028 */
4029 void
4030f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4031{
4032 buf_T *buf = term_get_buf(argvars);
4033 char_u *msg;
4034 term_T *term;
4035
4036 rettv->v_type = VAR_UNKNOWN;
4037 if (buf == NULL)
4038 return;
4039
4040 msg = get_tv_string_chk(&argvars[1]);
4041 if (msg == NULL)
4042 return;
4043 term = buf->b_term;
4044 if (term->tl_vterm == NULL)
4045 return;
4046
4047 while (*msg != NUL)
4048 {
4049 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004050 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004051 }
4052}
4053
4054/*
4055 * "term_start(command, options)" function
4056 */
4057 void
4058f_term_start(typval_T *argvars, typval_T *rettv)
4059{
4060 jobopt_T opt;
4061 buf_T *buf;
4062
4063 init_job_options(&opt);
4064 if (argvars[1].v_type != VAR_UNKNOWN
4065 && get_job_options(&argvars[1], &opt,
4066 JO_TIMEOUT_ALL + JO_STOPONEXIT
4067 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4068 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4069 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4070 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
4071 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
4072 return;
4073
4074 if (opt.jo_vertical)
4075 cmdmod.split = WSP_VERT;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004076 buf = term_start(&argvars[0], &opt, FALSE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004077
4078 if (buf != NULL && buf->b_term != NULL)
4079 rettv->vval.v_number = buf->b_fnum;
4080}
4081
4082/*
4083 * "term_wait" function
4084 */
4085 void
4086f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4087{
4088 buf_T *buf = term_get_buf(argvars);
4089
4090 if (buf == NULL)
4091 {
4092 ch_log(NULL, "term_wait(): invalid argument");
4093 return;
4094 }
4095 if (buf->b_term->tl_job == NULL)
4096 {
4097 ch_log(NULL, "term_wait(): no job to wait for");
4098 return;
4099 }
4100 if (buf->b_term->tl_job->jv_channel == NULL)
4101 /* channel is closed, nothing to do */
4102 return;
4103
4104 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004105 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004106 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4107 {
4108 /* The job is dead, keep reading channel I/O until the channel is
4109 * closed. buf->b_term may become NULL if the terminal was closed while
4110 * waiting. */
4111 ch_log(NULL, "term_wait(): waiting for channel to close");
4112 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4113 {
4114 mch_check_messages();
4115 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01004116 if (!buf_valid(buf))
4117 /* If the terminal is closed when the channel is closed the
4118 * buffer disappears. */
4119 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004120 ui_delay(10L, FALSE);
4121 }
4122 mch_check_messages();
4123 parse_queued_messages();
4124 }
4125 else
4126 {
4127 long wait = 10L;
4128
4129 mch_check_messages();
4130 parse_queued_messages();
4131
4132 /* Wait for some time for any channel I/O. */
4133 if (argvars[1].v_type != VAR_UNKNOWN)
4134 wait = get_tv_number(&argvars[1]);
4135 ui_delay(wait, TRUE);
4136 mch_check_messages();
4137
4138 /* Flushing messages on channels is hopefully sufficient.
4139 * TODO: is there a better way? */
4140 parse_queued_messages();
4141 }
4142}
4143
4144/*
4145 * Called when a channel has sent all the lines to a terminal.
4146 * Send a CTRL-D to mark the end of the text.
4147 */
4148 void
4149term_send_eof(channel_T *ch)
4150{
4151 term_T *term;
4152
4153 for (term = first_term; term != NULL; term = term->tl_next)
4154 if (term->tl_job == ch->ch_job)
4155 {
4156 if (term->tl_eof_chars != NULL)
4157 {
4158 channel_send(ch, PART_IN, term->tl_eof_chars,
4159 (int)STRLEN(term->tl_eof_chars), NULL);
4160 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
4161 }
4162# ifdef WIN3264
4163 else
4164 /* Default: CTRL-D */
4165 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
4166# endif
4167 }
4168}
4169
4170# if defined(WIN3264) || defined(PROTO)
4171
4172/**************************************
4173 * 2. MS-Windows implementation.
4174 */
4175
4176# ifndef PROTO
4177
4178#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
4179#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01004180#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004181
4182void* (*winpty_config_new)(UINT64, void*);
4183void* (*winpty_open)(void*, void*);
4184void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
4185BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
4186void (*winpty_config_set_mouse_mode)(void*, int);
4187void (*winpty_config_set_initial_size)(void*, int, int);
4188LPCWSTR (*winpty_conin_name)(void*);
4189LPCWSTR (*winpty_conout_name)(void*);
4190LPCWSTR (*winpty_conerr_name)(void*);
4191void (*winpty_free)(void*);
4192void (*winpty_config_free)(void*);
4193void (*winpty_spawn_config_free)(void*);
4194void (*winpty_error_free)(void*);
4195LPCWSTR (*winpty_error_msg)(void*);
4196BOOL (*winpty_set_size)(void*, int, int, void*);
4197HANDLE (*winpty_agent_process)(void*);
4198
4199#define WINPTY_DLL "winpty.dll"
4200
4201static HINSTANCE hWinPtyDLL = NULL;
4202# endif
4203
4204 static int
4205dyn_winpty_init(int verbose)
4206{
4207 int i;
4208 static struct
4209 {
4210 char *name;
4211 FARPROC *ptr;
4212 } winpty_entry[] =
4213 {
4214 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
4215 {"winpty_config_free", (FARPROC*)&winpty_config_free},
4216 {"winpty_config_new", (FARPROC*)&winpty_config_new},
4217 {"winpty_config_set_mouse_mode",
4218 (FARPROC*)&winpty_config_set_mouse_mode},
4219 {"winpty_config_set_initial_size",
4220 (FARPROC*)&winpty_config_set_initial_size},
4221 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
4222 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
4223 {"winpty_error_free", (FARPROC*)&winpty_error_free},
4224 {"winpty_free", (FARPROC*)&winpty_free},
4225 {"winpty_open", (FARPROC*)&winpty_open},
4226 {"winpty_spawn", (FARPROC*)&winpty_spawn},
4227 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
4228 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
4229 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
4230 {"winpty_set_size", (FARPROC*)&winpty_set_size},
4231 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
4232 {NULL, NULL}
4233 };
4234
4235 /* No need to initialize twice. */
4236 if (hWinPtyDLL)
4237 return OK;
4238 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
4239 * winpty.dll. */
4240 if (*p_winptydll != NUL)
4241 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
4242 if (!hWinPtyDLL)
4243 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
4244 if (!hWinPtyDLL)
4245 {
4246 if (verbose)
4247 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
4248 : (char_u *)WINPTY_DLL);
4249 return FAIL;
4250 }
4251 for (i = 0; winpty_entry[i].name != NULL
4252 && winpty_entry[i].ptr != NULL; ++i)
4253 {
4254 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
4255 winpty_entry[i].name)) == NULL)
4256 {
4257 if (verbose)
4258 EMSG2(_(e_loadfunc), winpty_entry[i].name);
4259 return FAIL;
4260 }
4261 }
4262
4263 return OK;
4264}
4265
4266/*
4267 * Create a new terminal of "rows" by "cols" cells.
4268 * Store a reference in "term".
4269 * Return OK or FAIL.
4270 */
4271 static int
4272term_and_job_init(
4273 term_T *term,
4274 typval_T *argvar,
4275 jobopt_T *opt)
4276{
4277 WCHAR *cmd_wchar = NULL;
4278 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004279 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004280 channel_T *channel = NULL;
4281 job_T *job = NULL;
4282 DWORD error;
4283 HANDLE jo = NULL;
4284 HANDLE child_process_handle;
4285 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01004286 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004287 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004288 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004289 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004290
4291 if (dyn_winpty_init(TRUE) == FAIL)
4292 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004293 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
4294 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004295
4296 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004297 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004298 cmd = argvar->vval.v_string;
4299 }
4300 else if (argvar->v_type == VAR_LIST)
4301 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004302 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004303 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004304 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004305 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004306 if (cmd == NULL || *cmd == NUL)
4307 {
4308 EMSG(_(e_invarg));
4309 goto failed;
4310 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004311
4312 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004313 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004314 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004315 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004316 if (opt->jo_cwd != NULL)
4317 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004318
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004319 win32_build_env(opt->jo_env, &ga_env, TRUE);
4320 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004321
4322 job = job_alloc();
4323 if (job == NULL)
4324 goto failed;
4325
4326 channel = add_channel();
4327 if (channel == NULL)
4328 goto failed;
4329
4330 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
4331 if (term->tl_winpty_config == NULL)
4332 goto failed;
4333
4334 winpty_config_set_mouse_mode(term->tl_winpty_config,
4335 WINPTY_MOUSE_MODE_FORCE);
4336 winpty_config_set_initial_size(term->tl_winpty_config,
4337 term->tl_cols, term->tl_rows);
4338 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
4339 if (term->tl_winpty == NULL)
4340 goto failed;
4341
4342 spawn_config = winpty_spawn_config_new(
4343 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
4344 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
4345 NULL,
4346 cmd_wchar,
4347 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004348 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004349 &winpty_err);
4350 if (spawn_config == NULL)
4351 goto failed;
4352
4353 channel = add_channel();
4354 if (channel == NULL)
4355 goto failed;
4356
4357 job = job_alloc();
4358 if (job == NULL)
4359 goto failed;
4360
4361 if (opt->jo_set & JO_IN_BUF)
4362 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
4363
4364 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
4365 &child_thread_handle, &error, &winpty_err))
4366 goto failed;
4367
4368 channel_set_pipes(channel,
4369 (sock_T)CreateFileW(
4370 winpty_conin_name(term->tl_winpty),
4371 GENERIC_WRITE, 0, NULL,
4372 OPEN_EXISTING, 0, NULL),
4373 (sock_T)CreateFileW(
4374 winpty_conout_name(term->tl_winpty),
4375 GENERIC_READ, 0, NULL,
4376 OPEN_EXISTING, 0, NULL),
4377 (sock_T)CreateFileW(
4378 winpty_conerr_name(term->tl_winpty),
4379 GENERIC_READ, 0, NULL,
4380 OPEN_EXISTING, 0, NULL));
4381
4382 /* Write lines with CR instead of NL. */
4383 channel->ch_write_text_mode = TRUE;
4384
4385 jo = CreateJobObject(NULL, NULL);
4386 if (jo == NULL)
4387 goto failed;
4388
4389 if (!AssignProcessToJobObject(jo, child_process_handle))
4390 {
4391 /* Failed, switch the way to terminate process with TerminateProcess. */
4392 CloseHandle(jo);
4393 jo = NULL;
4394 }
4395
4396 winpty_spawn_config_free(spawn_config);
4397 vim_free(cmd_wchar);
4398 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004399 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400
4401 create_vterm(term, term->tl_rows, term->tl_cols);
4402
4403 channel_set_job(channel, job, opt);
4404 job_set_options(job, opt);
4405
4406 job->jv_channel = channel;
4407 job->jv_proc_info.hProcess = child_process_handle;
4408 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
4409 job->jv_job_object = jo;
4410 job->jv_status = JOB_STARTED;
4411 job->jv_tty_in = utf16_to_enc(
4412 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
4413 job->jv_tty_out = utf16_to_enc(
4414 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
4415 ++job->jv_refcount;
4416 term->tl_job = job;
4417
4418 return OK;
4419
4420failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004421 ga_clear(&ga_cmd);
4422 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004423 vim_free(cmd_wchar);
4424 vim_free(cwd_wchar);
4425 if (spawn_config != NULL)
4426 winpty_spawn_config_free(spawn_config);
4427 if (channel != NULL)
4428 channel_clear(channel);
4429 if (job != NULL)
4430 {
4431 job->jv_channel = NULL;
4432 job_cleanup(job);
4433 }
4434 term->tl_job = NULL;
4435 if (jo != NULL)
4436 CloseHandle(jo);
4437 if (term->tl_winpty != NULL)
4438 winpty_free(term->tl_winpty);
4439 term->tl_winpty = NULL;
4440 if (term->tl_winpty_config != NULL)
4441 winpty_config_free(term->tl_winpty_config);
4442 term->tl_winpty_config = NULL;
4443 if (winpty_err != NULL)
4444 {
4445 char_u *msg = utf16_to_enc(
4446 (short_u *)winpty_error_msg(winpty_err), NULL);
4447
4448 EMSG(msg);
4449 winpty_error_free(winpty_err);
4450 }
4451 return FAIL;
4452}
4453
4454 static int
4455create_pty_only(term_T *term, jobopt_T *options)
4456{
4457 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
4458 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
4459 char in_name[80], out_name[80];
4460 channel_T *channel = NULL;
4461
4462 create_vterm(term, term->tl_rows, term->tl_cols);
4463
4464 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
4465 GetCurrentProcessId(),
4466 curbuf->b_fnum);
4467 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
4468 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4469 PIPE_UNLIMITED_INSTANCES,
4470 0, 0, NMPWAIT_NOWAIT, NULL);
4471 if (hPipeIn == INVALID_HANDLE_VALUE)
4472 goto failed;
4473
4474 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
4475 GetCurrentProcessId(),
4476 curbuf->b_fnum);
4477 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
4478 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4479 PIPE_UNLIMITED_INSTANCES,
4480 0, 0, 0, NULL);
4481 if (hPipeOut == INVALID_HANDLE_VALUE)
4482 goto failed;
4483
4484 ConnectNamedPipe(hPipeIn, NULL);
4485 ConnectNamedPipe(hPipeOut, NULL);
4486
4487 term->tl_job = job_alloc();
4488 if (term->tl_job == NULL)
4489 goto failed;
4490 ++term->tl_job->jv_refcount;
4491
4492 /* behave like the job is already finished */
4493 term->tl_job->jv_status = JOB_FINISHED;
4494
4495 channel = add_channel();
4496 if (channel == NULL)
4497 goto failed;
4498 term->tl_job->jv_channel = channel;
4499 channel->ch_keep_open = TRUE;
4500 channel->ch_named_pipe = TRUE;
4501
4502 channel_set_pipes(channel,
4503 (sock_T)hPipeIn,
4504 (sock_T)hPipeOut,
4505 (sock_T)hPipeOut);
4506 channel_set_job(channel, term->tl_job, options);
4507 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
4508 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
4509
4510 return OK;
4511
4512failed:
4513 if (hPipeIn != NULL)
4514 CloseHandle(hPipeIn);
4515 if (hPipeOut != NULL)
4516 CloseHandle(hPipeOut);
4517 return FAIL;
4518}
4519
4520/*
4521 * Free the terminal emulator part of "term".
4522 */
4523 static void
4524term_free_vterm(term_T *term)
4525{
4526 if (term->tl_winpty != NULL)
4527 winpty_free(term->tl_winpty);
4528 term->tl_winpty = NULL;
4529 if (term->tl_winpty_config != NULL)
4530 winpty_config_free(term->tl_winpty_config);
4531 term->tl_winpty_config = NULL;
4532 if (term->tl_vterm != NULL)
4533 vterm_free(term->tl_vterm);
4534 term->tl_vterm = NULL;
4535}
4536
4537/*
4538 * Request size to terminal.
4539 */
4540 static void
4541term_report_winsize(term_T *term, int rows, int cols)
4542{
4543 if (term->tl_winpty)
4544 winpty_set_size(term->tl_winpty, cols, rows, NULL);
4545}
4546
4547 int
4548terminal_enabled(void)
4549{
4550 return dyn_winpty_init(FALSE) == OK;
4551}
4552
4553# else
4554
4555/**************************************
4556 * 3. Unix-like implementation.
4557 */
4558
4559/*
4560 * Create a new terminal of "rows" by "cols" cells.
4561 * Start job for "cmd".
4562 * Store the pointers in "term".
4563 * Return OK or FAIL.
4564 */
4565 static int
4566term_and_job_init(
4567 term_T *term,
4568 typval_T *argvar,
4569 jobopt_T *opt)
4570{
4571 create_vterm(term, term->tl_rows, term->tl_cols);
4572
4573 term->tl_job = job_start(argvar, opt);
4574 if (term->tl_job != NULL)
4575 ++term->tl_job->jv_refcount;
4576
4577 return term->tl_job != NULL
4578 && term->tl_job->jv_channel != NULL
4579 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
4580}
4581
4582 static int
4583create_pty_only(term_T *term, jobopt_T *opt)
4584{
4585 create_vterm(term, term->tl_rows, term->tl_cols);
4586
4587 term->tl_job = job_alloc();
4588 if (term->tl_job == NULL)
4589 return FAIL;
4590 ++term->tl_job->jv_refcount;
4591
4592 /* behave like the job is already finished */
4593 term->tl_job->jv_status = JOB_FINISHED;
4594
4595 return mch_create_pty_channel(term->tl_job, opt);
4596}
4597
4598/*
4599 * Free the terminal emulator part of "term".
4600 */
4601 static void
4602term_free_vterm(term_T *term)
4603{
4604 if (term->tl_vterm != NULL)
4605 vterm_free(term->tl_vterm);
4606 term->tl_vterm = NULL;
4607}
4608
4609/*
4610 * Request size to terminal.
4611 */
4612 static void
4613term_report_winsize(term_T *term, int rows, int cols)
4614{
4615 /* Use an ioctl() to report the new window size to the job. */
4616 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
4617 {
4618 int fd = -1;
4619 int part;
4620
4621 for (part = PART_OUT; part < PART_COUNT; ++part)
4622 {
4623 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
4624 if (isatty(fd))
4625 break;
4626 }
4627 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
4628 mch_signal_job(term->tl_job, (char_u *)"winch");
4629 }
4630}
4631
4632# endif
4633
4634#endif /* FEAT_TERMINAL */