blob: 867109b0796214dd4a51619b5e210cd4759ace6a [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/*
1309 * Get a key from the user without mapping.
1310 * Note: while waiting a terminal may be closed and freed if the channel is
1311 * closed and ++close was used.
1312 * Uses terminal mode mappings.
1313 */
1314 static int
1315term_vgetc()
1316{
1317 int c;
1318 int save_State = State;
1319
1320 State = TERMINAL;
1321 got_int = FALSE;
1322#ifdef WIN3264
1323 ctrl_break_was_pressed = FALSE;
1324#endif
1325 c = vgetc();
1326 got_int = FALSE;
1327 State = save_State;
1328 return c;
1329}
1330
1331/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001332 * Send keys to terminal.
1333 * Return FAIL when the key needs to be handled in Normal mode.
1334 * Return OK when the key was dropped or sent to the terminal.
1335 */
1336 int
1337send_keys_to_term(term_T *term, int c, int typed)
1338{
1339 char msg[KEY_BUF_LEN];
1340 size_t len;
1341 static int mouse_was_outside = FALSE;
1342 int dragging_outside = FALSE;
1343
1344 /* Catch keys that need to be handled as in Normal mode. */
1345 switch (c)
1346 {
1347 case NUL:
1348 case K_ZERO:
1349 if (typed)
1350 stuffcharReadbuff(c);
1351 return FAIL;
1352
1353 case K_IGNORE:
1354 return FAIL;
1355
1356 case K_LEFTDRAG:
1357 case K_MIDDLEDRAG:
1358 case K_RIGHTDRAG:
1359 case K_X1DRAG:
1360 case K_X2DRAG:
1361 dragging_outside = mouse_was_outside;
1362 /* FALLTHROUGH */
1363 case K_LEFTMOUSE:
1364 case K_LEFTMOUSE_NM:
1365 case K_LEFTRELEASE:
1366 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001367 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001368 case K_MIDDLEMOUSE:
1369 case K_MIDDLERELEASE:
1370 case K_RIGHTMOUSE:
1371 case K_RIGHTRELEASE:
1372 case K_X1MOUSE:
1373 case K_X1RELEASE:
1374 case K_X2MOUSE:
1375 case K_X2RELEASE:
1376
1377 case K_MOUSEUP:
1378 case K_MOUSEDOWN:
1379 case K_MOUSELEFT:
1380 case K_MOUSERIGHT:
1381 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001382 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001383 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001384 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001385 || dragging_outside)
1386 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001387 /* click or scroll outside the current window or on status line
1388 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001389 if (typed)
1390 {
1391 stuffcharReadbuff(c);
1392 mouse_was_outside = TRUE;
1393 }
1394 return FAIL;
1395 }
1396 }
1397 if (typed)
1398 mouse_was_outside = FALSE;
1399
1400 /* Convert the typed key to a sequence of bytes for the job. */
1401 len = term_convert_key(term, c, msg);
1402 if (len > 0)
1403 /* TODO: if FAIL is returned, stop? */
1404 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1405 (char_u *)msg, (int)len, NULL);
1406
1407 return OK;
1408}
1409
1410 static void
1411position_cursor(win_T *wp, VTermPos *pos)
1412{
1413 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1414 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1415 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1416}
1417
1418/*
1419 * Handle CTRL-W "": send register contents to the job.
1420 */
1421 static void
1422term_paste_register(int prev_c UNUSED)
1423{
1424 int c;
1425 list_T *l;
1426 listitem_T *item;
1427 long reglen = 0;
1428 int type;
1429
1430#ifdef FEAT_CMDL_INFO
1431 if (add_to_showcmd(prev_c))
1432 if (add_to_showcmd('"'))
1433 out_flush();
1434#endif
1435 c = term_vgetc();
1436#ifdef FEAT_CMDL_INFO
1437 clear_showcmd();
1438#endif
1439 if (!term_use_loop())
1440 /* job finished while waiting for a character */
1441 return;
1442
1443 /* CTRL-W "= prompt for expression to evaluate. */
1444 if (c == '=' && get_expr_register() != '=')
1445 return;
1446 if (!term_use_loop())
1447 /* job finished while waiting for a character */
1448 return;
1449
1450 l = (list_T *)get_reg_contents(c, GREG_LIST);
1451 if (l != NULL)
1452 {
1453 type = get_reg_type(c, &reglen);
1454 for (item = l->lv_first; item != NULL; item = item->li_next)
1455 {
1456 char_u *s = get_tv_string(&item->li_tv);
1457#ifdef WIN3264
1458 char_u *tmp = s;
1459
1460 if (!enc_utf8 && enc_codepage > 0)
1461 {
1462 WCHAR *ret = NULL;
1463 int length = 0;
1464
1465 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1466 (int)STRLEN(s), &ret, &length);
1467 if (ret != NULL)
1468 {
1469 WideCharToMultiByte_alloc(CP_UTF8, 0,
1470 ret, length, (char **)&s, &length, 0, 0);
1471 vim_free(ret);
1472 }
1473 }
1474#endif
1475 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1476 s, (int)STRLEN(s), NULL);
1477#ifdef WIN3264
1478 if (tmp != s)
1479 vim_free(s);
1480#endif
1481
1482 if (item->li_next != NULL || type == MLINE)
1483 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1484 (char_u *)"\r", 1, NULL);
1485 }
1486 list_free(l);
1487 }
1488}
1489
1490#if defined(FEAT_GUI) || defined(PROTO)
1491/*
1492 * Return TRUE when the cursor of the terminal should be displayed.
1493 */
1494 int
1495terminal_is_active()
1496{
1497 return in_terminal_loop != NULL;
1498}
1499
1500 cursorentry_T *
1501term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1502{
1503 term_T *term = in_terminal_loop;
1504 static cursorentry_T entry;
1505
1506 vim_memset(&entry, 0, sizeof(entry));
1507 entry.shape = entry.mshape =
1508 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1509 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1510 SHAPE_BLOCK;
1511 entry.percentage = 20;
1512 if (term->tl_cursor_blink)
1513 {
1514 entry.blinkwait = 700;
1515 entry.blinkon = 400;
1516 entry.blinkoff = 250;
1517 }
1518 *fg = gui.back_pixel;
1519 if (term->tl_cursor_color == NULL)
1520 *bg = gui.norm_pixel;
1521 else
1522 *bg = color_name2handle(term->tl_cursor_color);
1523 entry.name = "n";
1524 entry.used_for = SHAPE_CURSOR;
1525
1526 return &entry;
1527}
1528#endif
1529
Bram Moolenaard317b382018-02-08 22:33:31 +01001530 static void
1531may_output_cursor_props(void)
1532{
1533 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1534 || last_set_cursor_shape != desired_cursor_shape
1535 || last_set_cursor_blink != desired_cursor_blink)
1536 {
1537 last_set_cursor_color = desired_cursor_color;
1538 last_set_cursor_shape = desired_cursor_shape;
1539 last_set_cursor_blink = desired_cursor_blink;
1540 term_cursor_color(desired_cursor_color);
1541 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1542 /* this will restore the initial cursor style, if possible */
1543 ui_cursor_shape_forced(TRUE);
1544 else
1545 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1546 }
1547}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001548
Bram Moolenaard317b382018-02-08 22:33:31 +01001549/*
1550 * Set the cursor color and shape, if not last set to these.
1551 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001552 static void
1553may_set_cursor_props(term_T *term)
1554{
1555#ifdef FEAT_GUI
1556 /* For the GUI the cursor properties are obtained with
1557 * term_get_cursor_shape(). */
1558 if (gui.in_use)
1559 return;
1560#endif
1561 if (in_terminal_loop == term)
1562 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001564 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001566 desired_cursor_color = (char_u *)"";
1567 desired_cursor_shape = term->tl_cursor_shape;
1568 desired_cursor_blink = term->tl_cursor_blink;
1569 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001570 }
1571}
1572
Bram Moolenaard317b382018-02-08 22:33:31 +01001573/*
1574 * Reset the desired cursor properties and restore them when needed.
1575 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001577prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001578{
1579#ifdef FEAT_GUI
1580 if (gui.in_use)
1581 return;
1582#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001583 desired_cursor_color = (char_u *)"";
1584 desired_cursor_shape = -1;
1585 desired_cursor_blink = -1;
1586 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001587}
1588
1589/*
1590 * Returns TRUE if the current window contains a terminal and we are sending
1591 * keys to the job.
1592 */
1593 int
1594term_use_loop(void)
1595{
1596 term_T *term = curbuf->b_term;
1597
1598 return term != NULL
1599 && !term->tl_normal_mode
1600 && term->tl_vterm != NULL
1601 && term_job_running(term);
1602}
1603
1604/*
1605 * Wait for input and send it to the job.
1606 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1607 * when there is no more typahead.
1608 * Return when the start of a CTRL-W command is typed or anything else that
1609 * should be handled as a Normal mode command.
1610 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1611 * the terminal was closed.
1612 */
1613 int
1614terminal_loop(int blocking)
1615{
1616 int c;
1617 int termkey = 0;
1618 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001619#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001620 int tty_fd = curbuf->b_term->tl_job->jv_channel
1621 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001622#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001623 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001624
1625 /* Remember the terminal we are sending keys to. However, the terminal
1626 * might be closed while waiting for a character, e.g. typing "exit" in a
1627 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1628 * stored reference. */
1629 in_terminal_loop = curbuf->b_term;
1630
1631 if (*curwin->w_p_tk != NUL)
1632 termkey = string_to_key(curwin->w_p_tk, TRUE);
1633 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1634 may_set_cursor_props(curbuf->b_term);
1635
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 while (blocking || vpeekc() != NUL)
1637 {
1638 /* TODO: skip screen update when handling a sequence of keys. */
1639 /* Repeat redrawing in case a message is received while redrawing. */
1640 while (must_redraw != 0)
1641 if (update_screen(0) == FAIL)
1642 break;
1643 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001644 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001645
1646 c = term_vgetc();
1647 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001648 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001649 /* Job finished while waiting for a character. Push back the
1650 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001651 if (c != K_IGNORE)
1652 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001653 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001654 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001655 if (c == K_IGNORE)
1656 continue;
1657
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001658#ifdef UNIX
1659 /*
1660 * The shell or another program may change the tty settings. Getting
1661 * them for every typed character is a bit of overhead, but it's needed
1662 * for the first character typed, e.g. when Vim starts in a shell.
1663 */
1664 if (isatty(tty_fd))
1665 {
1666 ttyinfo_T info;
1667
1668 /* Get the current backspace character of the pty. */
1669 if (get_tty_info(tty_fd, &info) == OK)
1670 term_backspace_char = info.backspace;
1671 }
1672#endif
1673
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001674#ifdef WIN3264
1675 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1676 * Use CTRL-BREAK to kill the job. */
1677 if (ctrl_break_was_pressed)
1678 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1679#endif
1680 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1681 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1682 {
1683 int prev_c = c;
1684
1685#ifdef FEAT_CMDL_INFO
1686 if (add_to_showcmd(c))
1687 out_flush();
1688#endif
1689 c = term_vgetc();
1690#ifdef FEAT_CMDL_INFO
1691 clear_showcmd();
1692#endif
1693 if (!term_use_loop())
1694 /* job finished while waiting for a character */
1695 break;
1696
1697 if (prev_c == Ctrl_BSL)
1698 {
1699 if (c == Ctrl_N)
1700 {
1701 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1702 term_enter_normal_mode();
1703 ret = FAIL;
1704 goto theend;
1705 }
1706 /* Send both keys to the terminal. */
1707 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1708 }
1709 else if (c == Ctrl_C)
1710 {
1711 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1712 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1713 }
1714 else if (termkey == 0 && c == '.')
1715 {
1716 /* "CTRL-W .": send CTRL-W to the job */
1717 c = Ctrl_W;
1718 }
1719 else if (c == 'N')
1720 {
1721 /* CTRL-W N : go to Terminal-Normal mode. */
1722 term_enter_normal_mode();
1723 ret = FAIL;
1724 goto theend;
1725 }
1726 else if (c == '"')
1727 {
1728 term_paste_register(prev_c);
1729 continue;
1730 }
1731 else if (termkey == 0 || c != termkey)
1732 {
1733 stuffcharReadbuff(Ctrl_W);
1734 stuffcharReadbuff(c);
1735 ret = OK;
1736 goto theend;
1737 }
1738 }
1739# ifdef WIN3264
1740 if (!enc_utf8 && has_mbyte && c >= 0x80)
1741 {
1742 WCHAR wc;
1743 char_u mb[3];
1744
1745 mb[0] = (unsigned)c >> 8;
1746 mb[1] = c;
1747 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1748 c = wc;
1749 }
1750# endif
1751 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1752 {
Bram Moolenaard317b382018-02-08 22:33:31 +01001753 if (c == K_MOUSEMOVE)
1754 /* We are sure to come back here, don't reset the cursor color
1755 * and shape to avoid flickering. */
1756 restore_cursor = FALSE;
1757
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001758 ret = OK;
1759 goto theend;
1760 }
1761 }
1762 ret = FAIL;
1763
1764theend:
1765 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01001766 if (restore_cursor)
1767 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001768 return ret;
1769}
1770
1771/*
1772 * Called when a job has finished.
1773 * This updates the title and status, but does not close the vterm, because
1774 * there might still be pending output in the channel.
1775 */
1776 void
1777term_job_ended(job_T *job)
1778{
1779 term_T *term;
1780 int did_one = FALSE;
1781
1782 for (term = first_term; term != NULL; term = term->tl_next)
1783 if (term->tl_job == job)
1784 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01001785 VIM_CLEAR(term->tl_title);
1786 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001787 redraw_buf_and_status_later(term->tl_buffer, VALID);
1788 did_one = TRUE;
1789 }
1790 if (did_one)
1791 redraw_statuslines();
1792 if (curbuf->b_term != NULL)
1793 {
1794 if (curbuf->b_term->tl_job == job)
1795 maketitle();
1796 update_cursor(curbuf->b_term, TRUE);
1797 }
1798}
1799
1800 static void
1801may_toggle_cursor(term_T *term)
1802{
1803 if (in_terminal_loop == term)
1804 {
1805 if (term->tl_cursor_visible)
1806 cursor_on();
1807 else
1808 cursor_off();
1809 }
1810}
1811
1812/*
1813 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001814 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001815 */
1816 static int
1817color2index(VTermColor *color, int fg, int *boldp)
1818{
1819 int red = color->red;
1820 int blue = color->blue;
1821 int green = color->green;
1822
Bram Moolenaar46359e12017-11-29 22:33:38 +01001823 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001824 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001825 /* First 16 colors and default: use the ANSI index, because these
1826 * colors can be redefined. */
1827 if (t_colors >= 16)
1828 return color->ansi_index;
1829 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001830 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001831 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01001832 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01001833 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1834 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1835 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1836 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1837 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1838 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1839 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1840 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1841 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1842 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1843 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1844 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1845 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1846 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1847 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001848 }
1849 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001850
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001851 if (t_colors >= 256)
1852 {
1853 if (red == blue && red == green)
1854 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001855 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001856 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001857 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1858 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1859 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 int i;
1861
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001862 if (red < 5)
1863 return 17; /* 00/00/00 */
1864 if (red > 245) /* ff/ff/ff */
1865 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001866 for (i = 0; i < 23; ++i)
1867 if (red < cutoff[i])
1868 return i + 233;
1869 return 256;
1870 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001871 {
1872 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1873 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001874
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001875 /* 216-color cube */
1876 for (ri = 0; ri < 5; ++ri)
1877 if (red < cutoff[ri])
1878 break;
1879 for (gi = 0; gi < 5; ++gi)
1880 if (green < cutoff[gi])
1881 break;
1882 for (bi = 0; bi < 5; ++bi)
1883 if (blue < cutoff[bi])
1884 break;
1885 return 17 + ri * 36 + gi * 6 + bi;
1886 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001887 }
1888 return 0;
1889}
1890
1891/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01001892 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001893 */
1894 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01001895vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001896{
1897 int attr = 0;
1898
1899 if (cellattrs.bold)
1900 attr |= HL_BOLD;
1901 if (cellattrs.underline)
1902 attr |= HL_UNDERLINE;
1903 if (cellattrs.italic)
1904 attr |= HL_ITALIC;
1905 if (cellattrs.strike)
1906 attr |= HL_STRIKETHROUGH;
1907 if (cellattrs.reverse)
1908 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001909 return attr;
1910}
1911
1912/*
1913 * Store Vterm attributes in "cell" from highlight flags.
1914 */
1915 static void
1916hl2vtermAttr(int attr, cellattr_T *cell)
1917{
1918 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
1919 if (attr & HL_BOLD)
1920 cell->attrs.bold = 1;
1921 if (attr & HL_UNDERLINE)
1922 cell->attrs.underline = 1;
1923 if (attr & HL_ITALIC)
1924 cell->attrs.italic = 1;
1925 if (attr & HL_STRIKETHROUGH)
1926 cell->attrs.strike = 1;
1927 if (attr & HL_INVERSE)
1928 cell->attrs.reverse = 1;
1929}
1930
1931/*
1932 * Convert the attributes of a vterm cell into an attribute index.
1933 */
1934 static int
1935cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1936{
1937 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001938
1939#ifdef FEAT_GUI
1940 if (gui.in_use)
1941 {
1942 guicolor_T fg, bg;
1943
1944 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1945 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1946 return get_gui_attr_idx(attr, fg, bg);
1947 }
1948 else
1949#endif
1950#ifdef FEAT_TERMGUICOLORS
1951 if (p_tgc)
1952 {
1953 guicolor_T fg, bg;
1954
1955 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1956 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1957
1958 return get_tgc_attr_idx(attr, fg, bg);
1959 }
1960 else
1961#endif
1962 {
1963 int bold = MAYBE;
1964 int fg = color2index(&cellfg, TRUE, &bold);
1965 int bg = color2index(&cellbg, FALSE, &bold);
1966
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001967 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001968 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001969 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001970 if (fg == 0 && term_default_cterm_fg >= 0)
1971 fg = term_default_cterm_fg + 1;
1972 if (bg == 0 && term_default_cterm_bg >= 0)
1973 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001974 }
1975
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001976 /* with 8 colors set the bold attribute to get a bright foreground */
1977 if (bold == TRUE)
1978 attr |= HL_BOLD;
1979 return get_cterm_attr_idx(attr, fg, bg);
1980 }
1981 return 0;
1982}
1983
1984 static int
1985handle_damage(VTermRect rect, void *user)
1986{
1987 term_T *term = (term_T *)user;
1988
1989 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1990 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1991 redraw_buf_later(term->tl_buffer, NOT_VALID);
1992 return 1;
1993}
1994
1995 static int
1996handle_moverect(VTermRect dest, VTermRect src, void *user)
1997{
1998 term_T *term = (term_T *)user;
1999
2000 /* Scrolling up is done much more efficiently by deleting lines instead of
2001 * redrawing the text. */
2002 if (dest.start_col == src.start_col
2003 && dest.end_col == src.end_col
2004 && dest.start_row < src.start_row)
2005 {
2006 win_T *wp;
2007 VTermColor fg, bg;
2008 VTermScreenCellAttrs attr;
2009 int clear_attr;
2010
2011 /* Set the color to clear lines with. */
2012 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2013 &fg, &bg);
2014 vim_memset(&attr, 0, sizeof(attr));
2015 clear_attr = cell2attr(attr, fg, bg);
2016
2017 FOR_ALL_WINDOWS(wp)
2018 {
2019 if (wp->w_buffer == term->tl_buffer)
2020 win_del_lines(wp, dest.start_row,
2021 src.start_row - dest.start_row, FALSE, FALSE,
2022 clear_attr);
2023 }
2024 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002025
2026 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2027 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2028
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002029 redraw_buf_later(term->tl_buffer, NOT_VALID);
2030 return 1;
2031}
2032
2033 static int
2034handle_movecursor(
2035 VTermPos pos,
2036 VTermPos oldpos UNUSED,
2037 int visible,
2038 void *user)
2039{
2040 term_T *term = (term_T *)user;
2041 win_T *wp;
2042
2043 term->tl_cursor_pos = pos;
2044 term->tl_cursor_visible = visible;
2045
2046 FOR_ALL_WINDOWS(wp)
2047 {
2048 if (wp->w_buffer == term->tl_buffer)
2049 position_cursor(wp, &pos);
2050 }
2051 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2052 {
2053 may_toggle_cursor(term);
2054 update_cursor(term, term->tl_cursor_visible);
2055 }
2056
2057 return 1;
2058}
2059
2060 static int
2061handle_settermprop(
2062 VTermProp prop,
2063 VTermValue *value,
2064 void *user)
2065{
2066 term_T *term = (term_T *)user;
2067
2068 switch (prop)
2069 {
2070 case VTERM_PROP_TITLE:
2071 vim_free(term->tl_title);
2072 /* a blank title isn't useful, make it empty, so that "running" is
2073 * displayed */
2074 if (*skipwhite((char_u *)value->string) == NUL)
2075 term->tl_title = NULL;
2076#ifdef WIN3264
2077 else if (!enc_utf8 && enc_codepage > 0)
2078 {
2079 WCHAR *ret = NULL;
2080 int length = 0;
2081
2082 MultiByteToWideChar_alloc(CP_UTF8, 0,
2083 (char*)value->string, (int)STRLEN(value->string),
2084 &ret, &length);
2085 if (ret != NULL)
2086 {
2087 WideCharToMultiByte_alloc(enc_codepage, 0,
2088 ret, length, (char**)&term->tl_title,
2089 &length, 0, 0);
2090 vim_free(ret);
2091 }
2092 }
2093#endif
2094 else
2095 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002096 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002097 if (term == curbuf->b_term)
2098 maketitle();
2099 break;
2100
2101 case VTERM_PROP_CURSORVISIBLE:
2102 term->tl_cursor_visible = value->boolean;
2103 may_toggle_cursor(term);
2104 out_flush();
2105 break;
2106
2107 case VTERM_PROP_CURSORBLINK:
2108 term->tl_cursor_blink = value->boolean;
2109 may_set_cursor_props(term);
2110 break;
2111
2112 case VTERM_PROP_CURSORSHAPE:
2113 term->tl_cursor_shape = value->number;
2114 may_set_cursor_props(term);
2115 break;
2116
2117 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002118 if (desired_cursor_color == term->tl_cursor_color)
2119 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002120 vim_free(term->tl_cursor_color);
2121 if (*value->string == NUL)
2122 term->tl_cursor_color = NULL;
2123 else
2124 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2125 may_set_cursor_props(term);
2126 break;
2127
2128 case VTERM_PROP_ALTSCREEN:
2129 /* TODO: do anything else? */
2130 term->tl_using_altscreen = value->boolean;
2131 break;
2132
2133 default:
2134 break;
2135 }
2136 /* Always return 1, otherwise vterm doesn't store the value internally. */
2137 return 1;
2138}
2139
2140/*
2141 * The job running in the terminal resized the terminal.
2142 */
2143 static int
2144handle_resize(int rows, int cols, void *user)
2145{
2146 term_T *term = (term_T *)user;
2147 win_T *wp;
2148
2149 term->tl_rows = rows;
2150 term->tl_cols = cols;
2151 if (term->tl_vterm_size_changed)
2152 /* Size was set by vterm_set_size(), don't set the window size. */
2153 term->tl_vterm_size_changed = FALSE;
2154 else
2155 {
2156 FOR_ALL_WINDOWS(wp)
2157 {
2158 if (wp->w_buffer == term->tl_buffer)
2159 {
2160 win_setheight_win(rows, wp);
2161 win_setwidth_win(cols, wp);
2162 }
2163 }
2164 redraw_buf_later(term->tl_buffer, NOT_VALID);
2165 }
2166 return 1;
2167}
2168
2169/*
2170 * Handle a line that is pushed off the top of the screen.
2171 */
2172 static int
2173handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2174{
2175 term_T *term = (term_T *)user;
2176
2177 /* TODO: Limit the number of lines that are stored. */
2178 if (ga_grow(&term->tl_scrollback, 1) == OK)
2179 {
2180 cellattr_T *p = NULL;
2181 int len = 0;
2182 int i;
2183 int c;
2184 int col;
2185 sb_line_T *line;
2186 garray_T ga;
2187 cellattr_T fill_attr = term->tl_default_color;
2188
2189 /* do not store empty cells at the end */
2190 for (i = 0; i < cols; ++i)
2191 if (cells[i].chars[0] != 0)
2192 len = i + 1;
2193 else
2194 cell2cellattr(&cells[i], &fill_attr);
2195
2196 ga_init2(&ga, 1, 100);
2197 if (len > 0)
2198 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2199 if (p != NULL)
2200 {
2201 for (col = 0; col < len; col += cells[col].width)
2202 {
2203 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2204 {
2205 ga.ga_len = 0;
2206 break;
2207 }
2208 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2209 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2210 (char_u *)ga.ga_data + ga.ga_len);
2211 cell2cellattr(&cells[col], &p[col]);
2212 }
2213 }
2214 if (ga_grow(&ga, 1) == FAIL)
2215 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2216 else
2217 {
2218 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2219 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2220 }
2221 ga_clear(&ga);
2222
2223 line = (sb_line_T *)term->tl_scrollback.ga_data
2224 + term->tl_scrollback.ga_len;
2225 line->sb_cols = len;
2226 line->sb_cells = p;
2227 line->sb_fill_attr = fill_attr;
2228 ++term->tl_scrollback.ga_len;
2229 ++term->tl_scrollback_scrolled;
2230 }
2231 return 0; /* ignored */
2232}
2233
2234static VTermScreenCallbacks screen_callbacks = {
2235 handle_damage, /* damage */
2236 handle_moverect, /* moverect */
2237 handle_movecursor, /* movecursor */
2238 handle_settermprop, /* settermprop */
2239 NULL, /* bell */
2240 handle_resize, /* resize */
2241 handle_pushline, /* sb_pushline */
2242 NULL /* sb_popline */
2243};
2244
2245/*
2246 * Called when a channel has been closed.
2247 * If this was a channel for a terminal window then finish it up.
2248 */
2249 void
2250term_channel_closed(channel_T *ch)
2251{
2252 term_T *term;
2253 int did_one = FALSE;
2254
2255 for (term = first_term; term != NULL; term = term->tl_next)
2256 if (term->tl_job == ch->ch_job)
2257 {
2258 term->tl_channel_closed = TRUE;
2259 did_one = TRUE;
2260
Bram Moolenaard23a8232018-02-10 18:45:26 +01002261 VIM_CLEAR(term->tl_title);
2262 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002263
2264 /* Unless in Terminal-Normal mode: clear the vterm. */
2265 if (!term->tl_normal_mode)
2266 {
2267 int fnum = term->tl_buffer->b_fnum;
2268
2269 cleanup_vterm(term);
2270
2271 if (term->tl_finish == 'c')
2272 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002273 aco_save_T aco;
2274
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 /* ++close or term_finish == "close" */
2276 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002277 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002278 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002279 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002280 break;
2281 }
2282 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2283 {
2284 char buf[50];
2285
2286 /* TODO: use term_opencmd */
2287 ch_log(NULL, "terminal job finished, opening window");
2288 vim_snprintf(buf, sizeof(buf),
2289 term->tl_opencmd == NULL
2290 ? "botright sbuf %d"
2291 : (char *)term->tl_opencmd, fnum);
2292 do_cmdline_cmd((char_u *)buf);
2293 }
2294 else
2295 ch_log(NULL, "terminal job finished");
2296 }
2297
2298 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2299 }
2300 if (did_one)
2301 {
2302 redraw_statuslines();
2303
2304 /* Need to break out of vgetc(). */
2305 ins_char_typebuf(K_IGNORE);
2306 typebuf_was_filled = TRUE;
2307
2308 term = curbuf->b_term;
2309 if (term != NULL)
2310 {
2311 if (term->tl_job == ch->ch_job)
2312 maketitle();
2313 update_cursor(term, term->tl_cursor_visible);
2314 }
2315 }
2316}
2317
2318/*
2319 * Called to update a window that contains an active terminal.
2320 * Returns FAIL when there is no terminal running in this window or in
2321 * Terminal-Normal mode.
2322 */
2323 int
2324term_update_window(win_T *wp)
2325{
2326 term_T *term = wp->w_buffer->b_term;
2327 VTerm *vterm;
2328 VTermScreen *screen;
2329 VTermState *state;
2330 VTermPos pos;
2331
2332 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2333 return FAIL;
2334
2335 vterm = term->tl_vterm;
2336 screen = vterm_obtain_screen(vterm);
2337 state = vterm_obtain_state(vterm);
2338
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002339 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002340 {
2341 term->tl_dirty_row_start = 0;
2342 term->tl_dirty_row_end = MAX_ROW;
2343 }
2344
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002345 /*
2346 * If the window was resized a redraw will be triggered and we get here.
2347 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2348 */
2349 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2350 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2351 {
2352 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2353 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2354 win_T *twp;
2355
2356 FOR_ALL_WINDOWS(twp)
2357 {
2358 /* When more than one window shows the same terminal, use the
2359 * smallest size. */
2360 if (twp->w_buffer == term->tl_buffer)
2361 {
2362 if (!term->tl_rows_fixed && rows > twp->w_height)
2363 rows = twp->w_height;
2364 if (!term->tl_cols_fixed && cols > twp->w_width)
2365 cols = twp->w_width;
2366 }
2367 }
2368
2369 term->tl_vterm_size_changed = TRUE;
2370 vterm_set_size(vterm, rows, cols);
2371 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2372 rows);
2373 term_report_winsize(term, rows, cols);
2374 }
2375
2376 /* The cursor may have been moved when resizing. */
2377 vterm_state_get_cursorpos(state, &pos);
2378 position_cursor(wp, &pos);
2379
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002380 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2381 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002382 {
2383 int off = screen_get_current_line_off();
2384 int max_col = MIN(wp->w_width, term->tl_cols);
2385
2386 if (pos.row < term->tl_rows)
2387 {
2388 for (pos.col = 0; pos.col < max_col; )
2389 {
2390 VTermScreenCell cell;
2391 int c;
2392
2393 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2394 vim_memset(&cell, 0, sizeof(cell));
2395
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002396 c = cell.chars[0];
2397 if (c == NUL)
2398 {
2399 ScreenLines[off] = ' ';
2400 if (enc_utf8)
2401 ScreenLinesUC[off] = NUL;
2402 }
2403 else
2404 {
2405 if (enc_utf8)
2406 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002407 int i;
2408
2409 /* composing chars */
2410 for (i = 0; i < Screen_mco
2411 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2412 {
2413 ScreenLinesC[i][off] = cell.chars[i + 1];
2414 if (cell.chars[i + 1] == 0)
2415 break;
2416 }
2417 if (c >= 0x80 || (Screen_mco > 0
2418 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002419 {
2420 ScreenLines[off] = ' ';
2421 ScreenLinesUC[off] = c;
2422 }
2423 else
2424 {
2425 ScreenLines[off] = c;
2426 ScreenLinesUC[off] = NUL;
2427 }
2428 }
2429#ifdef WIN3264
2430 else if (has_mbyte && c >= 0x80)
2431 {
2432 char_u mb[MB_MAXBYTES+1];
2433 WCHAR wc = c;
2434
2435 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2436 (char*)mb, 2, 0, 0) > 1)
2437 {
2438 ScreenLines[off] = mb[0];
2439 ScreenLines[off + 1] = mb[1];
2440 cell.width = mb_ptr2cells(mb);
2441 }
2442 else
2443 ScreenLines[off] = c;
2444 }
2445#endif
2446 else
2447 ScreenLines[off] = c;
2448 }
2449 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2450
2451 ++pos.col;
2452 ++off;
2453 if (cell.width == 2)
2454 {
2455 if (enc_utf8)
2456 ScreenLinesUC[off] = NUL;
2457
2458 /* don't set the second byte to NUL for a DBCS encoding, it
2459 * has been set above */
2460 if (enc_utf8 || !has_mbyte)
2461 ScreenLines[off] = NUL;
2462
2463 ++pos.col;
2464 ++off;
2465 }
2466 }
2467 }
2468 else
2469 pos.col = 0;
2470
Bram Moolenaar181ca992018-02-13 21:19:21 +01002471 screen_line(wp->w_winrow + pos.row + winbar_height(wp),
2472 wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002473 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002474 term->tl_dirty_row_start = MAX_ROW;
2475 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002476
2477 return OK;
2478}
2479
2480/*
2481 * Return TRUE if "wp" is a terminal window where the job has finished.
2482 */
2483 int
2484term_is_finished(buf_T *buf)
2485{
2486 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2487}
2488
2489/*
2490 * Return TRUE if "wp" is a terminal window where the job has finished or we
2491 * are in Terminal-Normal mode, thus we show the buffer contents.
2492 */
2493 int
2494term_show_buffer(buf_T *buf)
2495{
2496 term_T *term = buf->b_term;
2497
2498 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2499}
2500
2501/*
2502 * The current buffer is going to be changed. If there is terminal
2503 * highlighting remove it now.
2504 */
2505 void
2506term_change_in_curbuf(void)
2507{
2508 term_T *term = curbuf->b_term;
2509
2510 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2511 {
2512 free_scrollback(term);
2513 redraw_buf_later(term->tl_buffer, NOT_VALID);
2514
2515 /* The buffer is now like a normal buffer, it cannot be easily
2516 * abandoned when changed. */
2517 set_string_option_direct((char_u *)"buftype", -1,
2518 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2519 }
2520}
2521
2522/*
2523 * Get the screen attribute for a position in the buffer.
2524 * Use a negative "col" to get the filler background color.
2525 */
2526 int
2527term_get_attr(buf_T *buf, linenr_T lnum, int col)
2528{
2529 term_T *term = buf->b_term;
2530 sb_line_T *line;
2531 cellattr_T *cellattr;
2532
2533 if (lnum > term->tl_scrollback.ga_len)
2534 cellattr = &term->tl_default_color;
2535 else
2536 {
2537 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2538 if (col < 0 || col >= line->sb_cols)
2539 cellattr = &line->sb_fill_attr;
2540 else
2541 cellattr = line->sb_cells + col;
2542 }
2543 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2544}
2545
2546static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002547 { 0, 0, 0, 1}, /* black */
2548 {224, 0, 0, 2}, /* dark red */
2549 { 0, 224, 0, 3}, /* dark green */
2550 {224, 224, 0, 4}, /* dark yellow / brown */
2551 { 0, 0, 224, 5}, /* dark blue */
2552 {224, 0, 224, 6}, /* dark magenta */
2553 { 0, 224, 224, 7}, /* dark cyan */
2554 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002555
Bram Moolenaar46359e12017-11-29 22:33:38 +01002556 {128, 128, 128, 9}, /* dark grey */
2557 {255, 64, 64, 10}, /* light red */
2558 { 64, 255, 64, 11}, /* light green */
2559 {255, 255, 64, 12}, /* yellow */
2560 { 64, 64, 255, 13}, /* light blue */
2561 {255, 64, 255, 14}, /* light magenta */
2562 { 64, 255, 255, 15}, /* light cyan */
2563 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002564};
2565
2566static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002567 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002568};
2569
2570static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002571 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2572 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002573};
2574
2575/*
2576 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002577 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002578 */
2579 static void
2580cterm_color2rgb(int nr, VTermColor *rgb)
2581{
2582 int idx;
2583
2584 if (nr < 16)
2585 {
2586 *rgb = ansi_table[nr];
2587 }
2588 else if (nr < 232)
2589 {
2590 /* 216 color cube */
2591 idx = nr - 16;
2592 rgb->blue = cube_value[idx % 6];
2593 rgb->green = cube_value[idx / 6 % 6];
2594 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002595 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002596 }
2597 else if (nr < 256)
2598 {
2599 /* 24 grey scale ramp */
2600 idx = nr - 232;
2601 rgb->blue = grey_ramp[idx];
2602 rgb->green = grey_ramp[idx];
2603 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002604 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002605 }
2606}
2607
2608/*
2609 * Create a new vterm and initialize it.
2610 */
2611 static void
2612create_vterm(term_T *term, int rows, int cols)
2613{
2614 VTerm *vterm;
2615 VTermScreen *screen;
2616 VTermValue value;
2617 VTermColor *fg, *bg;
2618 int fgval, bgval;
2619 int id;
2620
2621 vterm = vterm_new(rows, cols);
2622 term->tl_vterm = vterm;
2623 screen = vterm_obtain_screen(vterm);
2624 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2625 /* TODO: depends on 'encoding'. */
2626 vterm_set_utf8(vterm, 1);
2627
2628 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2629 term->tl_default_color.width = 1;
2630 fg = &term->tl_default_color.fg;
2631 bg = &term->tl_default_color.bg;
2632
2633 /* Vterm uses a default black background. Set it to white when
2634 * 'background' is "light". */
2635 if (*p_bg == 'l')
2636 {
2637 fgval = 0;
2638 bgval = 255;
2639 }
2640 else
2641 {
2642 fgval = 255;
2643 bgval = 0;
2644 }
2645 fg->red = fg->green = fg->blue = fgval;
2646 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002647 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002648
2649 /* The "Terminal" highlight group overrules the defaults. */
2650 id = syn_name2id((char_u *)"Terminal");
2651
Bram Moolenaar46359e12017-11-29 22:33:38 +01002652 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002653#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2654 if (0
2655# ifdef FEAT_GUI
2656 || gui.in_use
2657# endif
2658# ifdef FEAT_TERMGUICOLORS
2659 || p_tgc
2660# endif
2661 )
2662 {
2663 guicolor_T fg_rgb = INVALCOLOR;
2664 guicolor_T bg_rgb = INVALCOLOR;
2665
2666 if (id != 0)
2667 syn_id2colors(id, &fg_rgb, &bg_rgb);
2668
2669# ifdef FEAT_GUI
2670 if (gui.in_use)
2671 {
2672 if (fg_rgb == INVALCOLOR)
2673 fg_rgb = gui.norm_pixel;
2674 if (bg_rgb == INVALCOLOR)
2675 bg_rgb = gui.back_pixel;
2676 }
2677# ifdef FEAT_TERMGUICOLORS
2678 else
2679# endif
2680# endif
2681# ifdef FEAT_TERMGUICOLORS
2682 {
2683 if (fg_rgb == INVALCOLOR)
2684 fg_rgb = cterm_normal_fg_gui_color;
2685 if (bg_rgb == INVALCOLOR)
2686 bg_rgb = cterm_normal_bg_gui_color;
2687 }
2688# endif
2689 if (fg_rgb != INVALCOLOR)
2690 {
2691 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2692
2693 fg->red = (unsigned)(rgb >> 16);
2694 fg->green = (unsigned)(rgb >> 8) & 255;
2695 fg->blue = (unsigned)rgb & 255;
2696 }
2697 if (bg_rgb != INVALCOLOR)
2698 {
2699 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2700
2701 bg->red = (unsigned)(rgb >> 16);
2702 bg->green = (unsigned)(rgb >> 8) & 255;
2703 bg->blue = (unsigned)rgb & 255;
2704 }
2705 }
2706 else
2707#endif
2708 if (id != 0 && t_colors >= 16)
2709 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002710 if (term_default_cterm_fg >= 0)
2711 cterm_color2rgb(term_default_cterm_fg, fg);
2712 if (term_default_cterm_bg >= 0)
2713 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002714 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 else
2716 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002717#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002718 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002719#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002720
2721 /* In an MS-Windows console we know the normal colors. */
2722 if (cterm_normal_fg_color > 0)
2723 {
2724 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002725# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002726 tmp = fg->red;
2727 fg->red = fg->blue;
2728 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002729# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002730 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002731# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002732 else
2733 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002734# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002735
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002736 if (cterm_normal_bg_color > 0)
2737 {
2738 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002739# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002740 tmp = bg->red;
2741 bg->red = bg->blue;
2742 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002743# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002744 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002745# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002746 else
2747 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002748# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002749 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002750
2751 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2752
2753 /* Required to initialize most things. */
2754 vterm_screen_reset(screen, 1 /* hard */);
2755
2756 /* Allow using alternate screen. */
2757 vterm_screen_enable_altscreen(screen, 1);
2758
2759 /* For unix do not use a blinking cursor. In an xterm this causes the
2760 * cursor to blink if it's blinking in the xterm.
2761 * For Windows we respect the system wide setting. */
2762#ifdef WIN3264
2763 if (GetCaretBlinkTime() == INFINITE)
2764 value.boolean = 0;
2765 else
2766 value.boolean = 1;
2767#else
2768 value.boolean = 0;
2769#endif
2770 vterm_state_set_termprop(vterm_obtain_state(vterm),
2771 VTERM_PROP_CURSORBLINK, &value);
2772}
2773
2774/*
2775 * Return the text to show for the buffer name and status.
2776 */
2777 char_u *
2778term_get_status_text(term_T *term)
2779{
2780 if (term->tl_status_text == NULL)
2781 {
2782 char_u *txt;
2783 size_t len;
2784
2785 if (term->tl_normal_mode)
2786 {
2787 if (term_job_running(term))
2788 txt = (char_u *)_("Terminal");
2789 else
2790 txt = (char_u *)_("Terminal-finished");
2791 }
2792 else if (term->tl_title != NULL)
2793 txt = term->tl_title;
2794 else if (term_none_open(term))
2795 txt = (char_u *)_("active");
2796 else if (term_job_running(term))
2797 txt = (char_u *)_("running");
2798 else
2799 txt = (char_u *)_("finished");
2800 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2801 term->tl_status_text = alloc((int)len);
2802 if (term->tl_status_text != NULL)
2803 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2804 term->tl_buffer->b_fname, txt);
2805 }
2806 return term->tl_status_text;
2807}
2808
2809/*
2810 * Mark references in jobs of terminals.
2811 */
2812 int
2813set_ref_in_term(int copyID)
2814{
2815 int abort = FALSE;
2816 term_T *term;
2817 typval_T tv;
2818
2819 for (term = first_term; term != NULL; term = term->tl_next)
2820 if (term->tl_job != NULL)
2821 {
2822 tv.v_type = VAR_JOB;
2823 tv.vval.v_job = term->tl_job;
2824 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2825 }
2826 return abort;
2827}
2828
2829/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002830 * Cache "Terminal" highlight group colors.
2831 */
2832 void
2833set_terminal_default_colors(int cterm_fg, int cterm_bg)
2834{
2835 term_default_cterm_fg = cterm_fg - 1;
2836 term_default_cterm_bg = cterm_bg - 1;
2837}
2838
2839/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002840 * Get the buffer from the first argument in "argvars".
2841 * Returns NULL when the buffer is not for a terminal window.
2842 */
2843 static buf_T *
2844term_get_buf(typval_T *argvars)
2845{
2846 buf_T *buf;
2847
2848 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2849 ++emsg_off;
2850 buf = get_buf_tv(&argvars[0], FALSE);
2851 --emsg_off;
2852 if (buf == NULL || buf->b_term == NULL)
2853 return NULL;
2854 return buf;
2855}
2856
Bram Moolenaard96ff162018-02-18 22:13:29 +01002857 static int
2858same_color(VTermColor *a, VTermColor *b)
2859{
2860 return a->red == b->red
2861 && a->green == b->green
2862 && a->blue == b->blue
2863 && a->ansi_index == b->ansi_index;
2864}
2865
2866 static void
2867dump_term_color(FILE *fd, VTermColor *color)
2868{
2869 fprintf(fd, "%02x%02x%02x%d",
2870 (int)color->red, (int)color->green, (int)color->blue,
2871 (int)color->ansi_index);
2872}
2873
2874/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002875 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01002876 *
2877 * Each screen cell in full is:
2878 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
2879 * {characters} is a space for an empty cell
2880 * For a double-width character "+" is changed to "*" and the next cell is
2881 * skipped.
2882 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
2883 * when "&" use the same as the previous cell.
2884 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
2885 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
2886 * {color-idx} is a number from 0 to 255
2887 *
2888 * Screen cell with same width, attributes and color as the previous one:
2889 * |{characters}
2890 *
2891 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
2892 *
2893 * Repeating the previous screen cell:
2894 * @{count}
2895 */
2896 void
2897f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
2898{
2899 buf_T *buf = term_get_buf(argvars);
2900 term_T *term;
2901 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002902 int max_height = 0;
2903 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002904 stat_T st;
2905 FILE *fd;
2906 VTermPos pos;
2907 VTermScreen *screen;
2908 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01002909 VTermState *state;
2910 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002911
2912 if (check_restricted() || check_secure())
2913 return;
2914 if (buf == NULL)
2915 return;
2916 term = buf->b_term;
2917
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002918 if (argvars[2].v_type != VAR_UNKNOWN)
2919 {
2920 dict_T *d;
2921
2922 if (argvars[2].v_type != VAR_DICT)
2923 {
2924 EMSG(_(e_dictreq));
2925 return;
2926 }
2927 d = argvars[2].vval.v_dict;
2928 if (d != NULL)
2929 {
2930 max_height = get_dict_number(d, (char_u *)"rows");
2931 max_width = get_dict_number(d, (char_u *)"columns");
2932 }
2933 }
2934
Bram Moolenaard96ff162018-02-18 22:13:29 +01002935 fname = get_tv_string_chk(&argvars[1]);
2936 if (fname == NULL)
2937 return;
2938 if (mch_stat((char *)fname, &st) >= 0)
2939 {
2940 EMSG2(_("E953: File exists: %s"), fname);
2941 return;
2942 }
2943
Bram Moolenaard96ff162018-02-18 22:13:29 +01002944 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
2945 {
2946 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2947 return;
2948 }
2949
2950 vim_memset(&prev_cell, 0, sizeof(prev_cell));
2951
2952 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01002953 state = vterm_obtain_state(term->tl_vterm);
2954 vterm_state_get_cursorpos(state, &cursor_pos);
2955
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002956 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
2957 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002958 {
2959 int repeat = 0;
2960
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002961 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
2962 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002963 {
2964 VTermScreenCell cell;
2965 int same_attr;
2966 int same_chars = TRUE;
2967 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01002968 int is_cursor_pos = (pos.col == cursor_pos.col
2969 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002970
2971 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2972 vim_memset(&cell, 0, sizeof(cell));
2973
2974 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
2975 {
2976 if (cell.chars[i] != prev_cell.chars[i])
2977 same_chars = FALSE;
2978 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
2979 break;
2980 }
2981 same_attr = vtermAttr2hl(cell.attrs)
2982 == vtermAttr2hl(prev_cell.attrs)
2983 && same_color(&cell.fg, &prev_cell.fg)
2984 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01002985 if (same_chars && cell.width == prev_cell.width && same_attr
2986 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01002987 {
2988 ++repeat;
2989 }
2990 else
2991 {
2992 if (repeat > 0)
2993 {
2994 fprintf(fd, "@%d", repeat);
2995 repeat = 0;
2996 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01002997 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01002998
2999 if (cell.chars[0] == NUL)
3000 fputs(" ", fd);
3001 else
3002 {
3003 char_u charbuf[10];
3004 int len;
3005
3006 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3007 && cell.chars[i] != NUL; ++i)
3008 {
3009 len = utf_char2bytes(cell.chars[0], charbuf);
3010 fwrite(charbuf, len, 1, fd);
3011 }
3012 }
3013
3014 /* When only the characters differ we don't write anything, the
3015 * following "|", "@" or NL will indicate using the same
3016 * attributes. */
3017 if (cell.width != prev_cell.width || !same_attr)
3018 {
3019 if (cell.width == 2)
3020 {
3021 fputs("*", fd);
3022 ++pos.col;
3023 }
3024 else
3025 fputs("+", fd);
3026
3027 if (same_attr)
3028 {
3029 fputs("&", fd);
3030 }
3031 else
3032 {
3033 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3034 if (same_color(&cell.fg, &prev_cell.fg))
3035 fputs("&", fd);
3036 else
3037 {
3038 fputs("#", fd);
3039 dump_term_color(fd, &cell.fg);
3040 }
3041 if (same_color(&cell.bg, &prev_cell.bg))
3042 fputs("&", fd);
3043 else
3044 {
3045 fputs("#", fd);
3046 dump_term_color(fd, &cell.bg);
3047 }
3048 }
3049 }
3050
3051 prev_cell = cell;
3052 }
3053 }
3054 if (repeat > 0)
3055 fprintf(fd, "@%d", repeat);
3056 fputs("\n", fd);
3057 }
3058
3059 fclose(fd);
3060}
3061
3062/*
3063 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3064 */
3065 static void
3066dump_is_corrupt(garray_T *gap)
3067{
3068 ga_concat(gap, (char_u *)"CORRUPT");
3069}
3070
3071 static void
3072append_cell(garray_T *gap, cellattr_T *cell)
3073{
3074 if (ga_grow(gap, 1) == OK)
3075 {
3076 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3077 ++gap->ga_len;
3078 }
3079}
3080
3081/*
3082 * Read the dump file from "fd" and append lines to the current buffer.
3083 * Return the cell width of the longest line.
3084 */
3085 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003086read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003087{
3088 int c;
3089 garray_T ga_text;
3090 garray_T ga_cell;
3091 char_u *prev_char = NULL;
3092 int attr = 0;
3093 cellattr_T cell;
3094 term_T *term = curbuf->b_term;
3095 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003096 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003097
3098 ga_init2(&ga_text, 1, 90);
3099 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3100 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003101 cursor_pos->row = -1;
3102 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003103
3104 c = fgetc(fd);
3105 for (;;)
3106 {
3107 if (c == EOF)
3108 break;
3109 if (c == '\n')
3110 {
3111 /* End of a line: append it to the buffer. */
3112 if (ga_text.ga_data == NULL)
3113 dump_is_corrupt(&ga_text);
3114 if (ga_grow(&term->tl_scrollback, 1) == OK)
3115 {
3116 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3117 + term->tl_scrollback.ga_len;
3118
3119 if (max_cells < ga_cell.ga_len)
3120 max_cells = ga_cell.ga_len;
3121 line->sb_cols = ga_cell.ga_len;
3122 line->sb_cells = ga_cell.ga_data;
3123 line->sb_fill_attr = term->tl_default_color;
3124 ++term->tl_scrollback.ga_len;
3125 ga_init(&ga_cell);
3126
3127 ga_append(&ga_text, NUL);
3128 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3129 ga_text.ga_len, FALSE);
3130 }
3131 else
3132 ga_clear(&ga_cell);
3133 ga_text.ga_len = 0;
3134
3135 c = fgetc(fd);
3136 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003137 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003138 {
3139 int prev_len = ga_text.ga_len;
3140
Bram Moolenaar9271d052018-02-25 21:39:46 +01003141 if (c == '>')
3142 {
3143 if (cursor_pos->row != -1)
3144 dump_is_corrupt(&ga_text); /* duplicate cursor */
3145 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3146 cursor_pos->col = ga_cell.ga_len;
3147 }
3148
Bram Moolenaard96ff162018-02-18 22:13:29 +01003149 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3150 c = fgetc(fd);
3151 if (c != EOF)
3152 ga_append(&ga_text, c);
3153 for (;;)
3154 {
3155 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003156 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003157 || c == EOF || c == '\n')
3158 break;
3159 ga_append(&ga_text, c);
3160 }
3161
3162 /* save the character for repeating it */
3163 vim_free(prev_char);
3164 if (ga_text.ga_data != NULL)
3165 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3166 ga_text.ga_len - prev_len);
3167
Bram Moolenaar9271d052018-02-25 21:39:46 +01003168 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003169 {
3170 /* use all attributes from previous cell */
3171 }
3172 else if (c == '+' || c == '*')
3173 {
3174 int is_bg;
3175
3176 cell.width = c == '+' ? 1 : 2;
3177
3178 c = fgetc(fd);
3179 if (c == '&')
3180 {
3181 /* use same attr as previous cell */
3182 c = fgetc(fd);
3183 }
3184 else if (isdigit(c))
3185 {
3186 /* get the decimal attribute */
3187 attr = 0;
3188 while (isdigit(c))
3189 {
3190 attr = attr * 10 + (c - '0');
3191 c = fgetc(fd);
3192 }
3193 hl2vtermAttr(attr, &cell);
3194 }
3195 else
3196 dump_is_corrupt(&ga_text);
3197
3198 /* is_bg == 0: fg, is_bg == 1: bg */
3199 for (is_bg = 0; is_bg <= 1; ++is_bg)
3200 {
3201 if (c == '&')
3202 {
3203 /* use same color as previous cell */
3204 c = fgetc(fd);
3205 }
3206 else if (c == '#')
3207 {
3208 int red, green, blue, index = 0;
3209
3210 c = fgetc(fd);
3211 red = hex2nr(c);
3212 c = fgetc(fd);
3213 red = (red << 4) + hex2nr(c);
3214 c = fgetc(fd);
3215 green = hex2nr(c);
3216 c = fgetc(fd);
3217 green = (green << 4) + hex2nr(c);
3218 c = fgetc(fd);
3219 blue = hex2nr(c);
3220 c = fgetc(fd);
3221 blue = (blue << 4) + hex2nr(c);
3222 c = fgetc(fd);
3223 if (!isdigit(c))
3224 dump_is_corrupt(&ga_text);
3225 while (isdigit(c))
3226 {
3227 index = index * 10 + (c - '0');
3228 c = fgetc(fd);
3229 }
3230
3231 if (is_bg)
3232 {
3233 cell.bg.red = red;
3234 cell.bg.green = green;
3235 cell.bg.blue = blue;
3236 cell.bg.ansi_index = index;
3237 }
3238 else
3239 {
3240 cell.fg.red = red;
3241 cell.fg.green = green;
3242 cell.fg.blue = blue;
3243 cell.fg.ansi_index = index;
3244 }
3245 }
3246 else
3247 dump_is_corrupt(&ga_text);
3248 }
3249 }
3250 else
3251 dump_is_corrupt(&ga_text);
3252
3253 append_cell(&ga_cell, &cell);
3254 }
3255 else if (c == '@')
3256 {
3257 if (prev_char == NULL)
3258 dump_is_corrupt(&ga_text);
3259 else
3260 {
3261 int count = 0;
3262
3263 /* repeat previous character, get the count */
3264 for (;;)
3265 {
3266 c = fgetc(fd);
3267 if (!isdigit(c))
3268 break;
3269 count = count * 10 + (c - '0');
3270 }
3271
3272 while (count-- > 0)
3273 {
3274 ga_concat(&ga_text, prev_char);
3275 append_cell(&ga_cell, &cell);
3276 }
3277 }
3278 }
3279 else
3280 {
3281 dump_is_corrupt(&ga_text);
3282 c = fgetc(fd);
3283 }
3284 }
3285
3286 if (ga_text.ga_len > 0)
3287 {
3288 /* trailing characters after last NL */
3289 dump_is_corrupt(&ga_text);
3290 ga_append(&ga_text, NUL);
3291 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3292 ga_text.ga_len, FALSE);
3293 }
3294
3295 ga_clear(&ga_text);
3296 vim_free(prev_char);
3297
3298 return max_cells;
3299}
3300
3301/*
3302 * Common for "term_dumpdiff()" and "term_dumpload()".
3303 */
3304 static void
3305term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
3306{
3307 jobopt_T opt;
3308 buf_T *buf;
3309 char_u buf1[NUMBUFLEN];
3310 char_u buf2[NUMBUFLEN];
3311 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003312 char_u *fname2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003313 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003314 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003315 char_u *textline = NULL;
3316
3317 /* First open the files. If this fails bail out. */
3318 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
3319 if (do_diff)
3320 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
3321 if (fname1 == NULL || (do_diff && fname2 == NULL))
3322 {
3323 EMSG(_(e_invarg));
3324 return;
3325 }
3326 fd1 = mch_fopen((char *)fname1, READBIN);
3327 if (fd1 == NULL)
3328 {
3329 EMSG2(_(e_notread), fname1);
3330 return;
3331 }
3332 if (do_diff)
3333 {
3334 fd2 = mch_fopen((char *)fname2, READBIN);
3335 if (fd2 == NULL)
3336 {
3337 fclose(fd1);
3338 EMSG2(_(e_notread), fname2);
3339 return;
3340 }
3341 }
3342
3343 init_job_options(&opt);
3344 /* TODO: use the {options} argument */
3345
3346 /* TODO: use the file name arguments for the buffer name */
3347 opt.jo_term_name = (char_u *)"dump diff";
3348
3349 buf = term_start(&argvars[0], &opt, TRUE, FALSE);
3350 if (buf != NULL && buf->b_term != NULL)
3351 {
3352 int i;
3353 linenr_T bot_lnum;
3354 linenr_T lnum;
3355 term_T *term = buf->b_term;
3356 int width;
3357 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003358 VTermPos cursor_pos1;
3359 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003360
3361 rettv->vval.v_number = buf->b_fnum;
3362
3363 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01003364 width = read_dump_file(fd1, &cursor_pos1);
3365
3366 /* position the cursor */
3367 if (cursor_pos1.row >= 0)
3368 {
3369 curwin->w_cursor.lnum = cursor_pos1.row + 1;
3370 coladvance(cursor_pos1.col);
3371 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003372
3373 /* Delete the empty line that was in the empty buffer. */
3374 ml_delete(1, FALSE);
3375
3376 /* For term_dumpload() we are done here. */
3377 if (!do_diff)
3378 goto theend;
3379
3380 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
3381
3382 textline = alloc(width + 1);
3383 if (textline == NULL)
3384 goto theend;
3385 for (i = 0; i < width; ++i)
3386 textline[i] = '=';
3387 textline[width] = NUL;
3388 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3389 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3390 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3391 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3392
3393 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003394 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003395 if (width2 > width)
3396 {
3397 vim_free(textline);
3398 textline = alloc(width2 + 1);
3399 if (textline == NULL)
3400 goto theend;
3401 width = width2;
3402 textline[width] = NUL;
3403 }
3404 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
3405
3406 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
3407 {
3408 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
3409 {
3410 /* bottom part has fewer rows, fill with "-" */
3411 for (i = 0; i < width; ++i)
3412 textline[i] = '-';
3413 }
3414 else
3415 {
3416 char_u *line1;
3417 char_u *line2;
3418 char_u *p1;
3419 char_u *p2;
3420 int col;
3421 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3422 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
3423 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
3424 ->sb_cells;
3425
3426 /* Make a copy, getting the second line will invalidate it. */
3427 line1 = vim_strsave(ml_get(lnum));
3428 if (line1 == NULL)
3429 break;
3430 p1 = line1;
3431
3432 line2 = ml_get(lnum + bot_lnum);
3433 p2 = line2;
3434 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
3435 {
3436 int len1 = utfc_ptr2len(p1);
3437 int len2 = utfc_ptr2len(p2);
3438
3439 textline[col] = ' ';
3440 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01003441 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01003442 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01003443 else if (lnum == cursor_pos1.row + 1
3444 && col == cursor_pos1.col
3445 && (cursor_pos1.row != cursor_pos2.row
3446 || cursor_pos1.col != cursor_pos2.col))
3447 /* cursor in first but not in second */
3448 textline[col] = '>';
3449 else if (lnum == cursor_pos2.row + 1
3450 && col == cursor_pos2.col
3451 && (cursor_pos1.row != cursor_pos2.row
3452 || cursor_pos1.col != cursor_pos2.col))
3453 /* cursor in second but not in first */
3454 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01003455 else if (cellattr1 != NULL && cellattr2 != NULL)
3456 {
3457 if ((cellattr1 + col)->width
3458 != (cellattr2 + col)->width)
3459 textline[col] = 'w';
3460 else if (!same_color(&(cellattr1 + col)->fg,
3461 &(cellattr2 + col)->fg))
3462 textline[col] = 'f';
3463 else if (!same_color(&(cellattr1 + col)->bg,
3464 &(cellattr2 + col)->bg))
3465 textline[col] = 'b';
3466 else if (vtermAttr2hl((cellattr1 + col)->attrs)
3467 != vtermAttr2hl(((cellattr2 + col)->attrs)))
3468 textline[col] = 'a';
3469 }
3470 p1 += len1;
3471 p2 += len2;
3472 /* TODO: handle different width */
3473 }
3474 vim_free(line1);
3475
3476 while (col < width)
3477 {
3478 if (*p1 == NUL && *p2 == NUL)
3479 textline[col] = '?';
3480 else if (*p1 == NUL)
3481 {
3482 textline[col] = '+';
3483 p2 += utfc_ptr2len(p2);
3484 }
3485 else
3486 {
3487 textline[col] = '-';
3488 p1 += utfc_ptr2len(p1);
3489 }
3490 ++col;
3491 }
3492 }
3493 if (add_empty_scrollback(term, &term->tl_default_color,
3494 term->tl_top_diff_rows) == OK)
3495 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3496 ++bot_lnum;
3497 }
3498
3499 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
3500 {
3501 /* bottom part has more rows, fill with "+" */
3502 for (i = 0; i < width; ++i)
3503 textline[i] = '+';
3504 if (add_empty_scrollback(term, &term->tl_default_color,
3505 term->tl_top_diff_rows) == OK)
3506 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3507 ++lnum;
3508 ++bot_lnum;
3509 }
3510
3511 term->tl_cols = width;
3512 }
3513
3514theend:
3515 vim_free(textline);
3516 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003517 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003518 fclose(fd2);
3519}
3520
3521/*
3522 * If the current buffer shows the output of term_dumpdiff(), swap the top and
3523 * bottom files.
3524 * Return FAIL when this is not possible.
3525 */
3526 int
3527term_swap_diff()
3528{
3529 term_T *term = curbuf->b_term;
3530 linenr_T line_count;
3531 linenr_T top_rows;
3532 linenr_T bot_rows;
3533 linenr_T bot_start;
3534 linenr_T lnum;
3535 char_u *p;
3536 sb_line_T *sb_line;
3537
3538 if (term == NULL
3539 || !term_is_finished(curbuf)
3540 || term->tl_top_diff_rows == 0
3541 || term->tl_scrollback.ga_len == 0)
3542 return FAIL;
3543
3544 line_count = curbuf->b_ml.ml_line_count;
3545 top_rows = term->tl_top_diff_rows;
3546 bot_rows = term->tl_bot_diff_rows;
3547 bot_start = line_count - bot_rows;
3548 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3549
3550 /* move lines from top to above the bottom part */
3551 for (lnum = 1; lnum <= top_rows; ++lnum)
3552 {
3553 p = vim_strsave(ml_get(1));
3554 if (p == NULL)
3555 return OK;
3556 ml_append(bot_start, p, 0, FALSE);
3557 ml_delete(1, FALSE);
3558 vim_free(p);
3559 }
3560
3561 /* move lines from bottom to the top */
3562 for (lnum = 1; lnum <= bot_rows; ++lnum)
3563 {
3564 p = vim_strsave(ml_get(bot_start + lnum));
3565 if (p == NULL)
3566 return OK;
3567 ml_delete(bot_start + lnum, FALSE);
3568 ml_append(lnum - 1, p, 0, FALSE);
3569 vim_free(p);
3570 }
3571
3572 if (top_rows == bot_rows)
3573 {
3574 /* rows counts are equal, can swap cell properties */
3575 for (lnum = 0; lnum < top_rows; ++lnum)
3576 {
3577 sb_line_T temp;
3578
3579 temp = *(sb_line + lnum);
3580 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
3581 *(sb_line + bot_start + lnum) = temp;
3582 }
3583 }
3584 else
3585 {
3586 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
3587 sb_line_T *temp = (sb_line_T *)alloc((int)size);
3588
3589 /* need to copy cell properties into temp memory */
3590 if (temp != NULL)
3591 {
3592 mch_memmove(temp, term->tl_scrollback.ga_data, size);
3593 mch_memmove(term->tl_scrollback.ga_data,
3594 temp + bot_start,
3595 sizeof(sb_line_T) * bot_rows);
3596 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
3597 temp + top_rows,
3598 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
3599 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
3600 + line_count - top_rows,
3601 temp,
3602 sizeof(sb_line_T) * top_rows);
3603 vim_free(temp);
3604 }
3605 }
3606
3607 term->tl_top_diff_rows = bot_rows;
3608 term->tl_bot_diff_rows = top_rows;
3609
3610 update_screen(NOT_VALID);
3611 return OK;
3612}
3613
3614/*
3615 * "term_dumpdiff(filename, filename, options)" function
3616 */
3617 void
3618f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
3619{
3620 term_load_dump(argvars, rettv, TRUE);
3621}
3622
3623/*
3624 * "term_dumpload(filename, options)" function
3625 */
3626 void
3627f_term_dumpload(typval_T *argvars, typval_T *rettv)
3628{
3629 term_load_dump(argvars, rettv, FALSE);
3630}
3631
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003632/*
3633 * "term_getaltscreen(buf)" function
3634 */
3635 void
3636f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
3637{
3638 buf_T *buf = term_get_buf(argvars);
3639
3640 if (buf == NULL)
3641 return;
3642 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
3643}
3644
3645/*
3646 * "term_getattr(attr, name)" function
3647 */
3648 void
3649f_term_getattr(typval_T *argvars, typval_T *rettv)
3650{
3651 int attr;
3652 size_t i;
3653 char_u *name;
3654
3655 static struct {
3656 char *name;
3657 int attr;
3658 } attrs[] = {
3659 {"bold", HL_BOLD},
3660 {"italic", HL_ITALIC},
3661 {"underline", HL_UNDERLINE},
3662 {"strike", HL_STRIKETHROUGH},
3663 {"reverse", HL_INVERSE},
3664 };
3665
3666 attr = get_tv_number(&argvars[0]);
3667 name = get_tv_string_chk(&argvars[1]);
3668 if (name == NULL)
3669 return;
3670
3671 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
3672 if (STRCMP(name, attrs[i].name) == 0)
3673 {
3674 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
3675 break;
3676 }
3677}
3678
3679/*
3680 * "term_getcursor(buf)" function
3681 */
3682 void
3683f_term_getcursor(typval_T *argvars, typval_T *rettv)
3684{
3685 buf_T *buf = term_get_buf(argvars);
3686 term_T *term;
3687 list_T *l;
3688 dict_T *d;
3689
3690 if (rettv_list_alloc(rettv) == FAIL)
3691 return;
3692 if (buf == NULL)
3693 return;
3694 term = buf->b_term;
3695
3696 l = rettv->vval.v_list;
3697 list_append_number(l, term->tl_cursor_pos.row + 1);
3698 list_append_number(l, term->tl_cursor_pos.col + 1);
3699
3700 d = dict_alloc();
3701 if (d != NULL)
3702 {
3703 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
3704 dict_add_nr_str(d, "blink", blink_state_is_inverted()
3705 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
3706 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
3707 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
3708 ? (char_u *)"" : term->tl_cursor_color);
3709 list_append_dict(l, d);
3710 }
3711}
3712
3713/*
3714 * "term_getjob(buf)" function
3715 */
3716 void
3717f_term_getjob(typval_T *argvars, typval_T *rettv)
3718{
3719 buf_T *buf = term_get_buf(argvars);
3720
3721 rettv->v_type = VAR_JOB;
3722 rettv->vval.v_job = NULL;
3723 if (buf == NULL)
3724 return;
3725
3726 rettv->vval.v_job = buf->b_term->tl_job;
3727 if (rettv->vval.v_job != NULL)
3728 ++rettv->vval.v_job->jv_refcount;
3729}
3730
3731 static int
3732get_row_number(typval_T *tv, term_T *term)
3733{
3734 if (tv->v_type == VAR_STRING
3735 && tv->vval.v_string != NULL
3736 && STRCMP(tv->vval.v_string, ".") == 0)
3737 return term->tl_cursor_pos.row;
3738 return (int)get_tv_number(tv) - 1;
3739}
3740
3741/*
3742 * "term_getline(buf, row)" function
3743 */
3744 void
3745f_term_getline(typval_T *argvars, typval_T *rettv)
3746{
3747 buf_T *buf = term_get_buf(argvars);
3748 term_T *term;
3749 int row;
3750
3751 rettv->v_type = VAR_STRING;
3752 if (buf == NULL)
3753 return;
3754 term = buf->b_term;
3755 row = get_row_number(&argvars[1], term);
3756
3757 if (term->tl_vterm == NULL)
3758 {
3759 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
3760
3761 /* vterm is finished, get the text from the buffer */
3762 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
3763 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
3764 }
3765 else
3766 {
3767 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
3768 VTermRect rect;
3769 int len;
3770 char_u *p;
3771
3772 if (row < 0 || row >= term->tl_rows)
3773 return;
3774 len = term->tl_cols * MB_MAXBYTES + 1;
3775 p = alloc(len);
3776 if (p == NULL)
3777 return;
3778 rettv->vval.v_string = p;
3779
3780 rect.start_col = 0;
3781 rect.end_col = term->tl_cols;
3782 rect.start_row = row;
3783 rect.end_row = row + 1;
3784 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
3785 }
3786}
3787
3788/*
3789 * "term_getscrolled(buf)" function
3790 */
3791 void
3792f_term_getscrolled(typval_T *argvars, typval_T *rettv)
3793{
3794 buf_T *buf = term_get_buf(argvars);
3795
3796 if (buf == NULL)
3797 return;
3798 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
3799}
3800
3801/*
3802 * "term_getsize(buf)" function
3803 */
3804 void
3805f_term_getsize(typval_T *argvars, typval_T *rettv)
3806{
3807 buf_T *buf = term_get_buf(argvars);
3808 list_T *l;
3809
3810 if (rettv_list_alloc(rettv) == FAIL)
3811 return;
3812 if (buf == NULL)
3813 return;
3814
3815 l = rettv->vval.v_list;
3816 list_append_number(l, buf->b_term->tl_rows);
3817 list_append_number(l, buf->b_term->tl_cols);
3818}
3819
3820/*
3821 * "term_getstatus(buf)" function
3822 */
3823 void
3824f_term_getstatus(typval_T *argvars, typval_T *rettv)
3825{
3826 buf_T *buf = term_get_buf(argvars);
3827 term_T *term;
3828 char_u val[100];
3829
3830 rettv->v_type = VAR_STRING;
3831 if (buf == NULL)
3832 return;
3833 term = buf->b_term;
3834
3835 if (term_job_running(term))
3836 STRCPY(val, "running");
3837 else
3838 STRCPY(val, "finished");
3839 if (term->tl_normal_mode)
3840 STRCAT(val, ",normal");
3841 rettv->vval.v_string = vim_strsave(val);
3842}
3843
3844/*
3845 * "term_gettitle(buf)" function
3846 */
3847 void
3848f_term_gettitle(typval_T *argvars, typval_T *rettv)
3849{
3850 buf_T *buf = term_get_buf(argvars);
3851
3852 rettv->v_type = VAR_STRING;
3853 if (buf == NULL)
3854 return;
3855
3856 if (buf->b_term->tl_title != NULL)
3857 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
3858}
3859
3860/*
3861 * "term_gettty(buf)" function
3862 */
3863 void
3864f_term_gettty(typval_T *argvars, typval_T *rettv)
3865{
3866 buf_T *buf = term_get_buf(argvars);
3867 char_u *p;
3868 int num = 0;
3869
3870 rettv->v_type = VAR_STRING;
3871 if (buf == NULL)
3872 return;
3873 if (argvars[1].v_type != VAR_UNKNOWN)
3874 num = get_tv_number(&argvars[1]);
3875
3876 switch (num)
3877 {
3878 case 0:
3879 if (buf->b_term->tl_job != NULL)
3880 p = buf->b_term->tl_job->jv_tty_out;
3881 else
3882 p = buf->b_term->tl_tty_out;
3883 break;
3884 case 1:
3885 if (buf->b_term->tl_job != NULL)
3886 p = buf->b_term->tl_job->jv_tty_in;
3887 else
3888 p = buf->b_term->tl_tty_in;
3889 break;
3890 default:
3891 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
3892 return;
3893 }
3894 if (p != NULL)
3895 rettv->vval.v_string = vim_strsave(p);
3896}
3897
3898/*
3899 * "term_list()" function
3900 */
3901 void
3902f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3903{
3904 term_T *tp;
3905 list_T *l;
3906
3907 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3908 return;
3909
3910 l = rettv->vval.v_list;
3911 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3912 if (tp != NULL && tp->tl_buffer != NULL)
3913 if (list_append_number(l,
3914 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3915 return;
3916}
3917
3918/*
3919 * "term_scrape(buf, row)" function
3920 */
3921 void
3922f_term_scrape(typval_T *argvars, typval_T *rettv)
3923{
3924 buf_T *buf = term_get_buf(argvars);
3925 VTermScreen *screen = NULL;
3926 VTermPos pos;
3927 list_T *l;
3928 term_T *term;
3929 char_u *p;
3930 sb_line_T *line;
3931
3932 if (rettv_list_alloc(rettv) == FAIL)
3933 return;
3934 if (buf == NULL)
3935 return;
3936 term = buf->b_term;
3937
3938 l = rettv->vval.v_list;
3939 pos.row = get_row_number(&argvars[1], term);
3940
3941 if (term->tl_vterm != NULL)
3942 {
3943 screen = vterm_obtain_screen(term->tl_vterm);
3944 p = NULL;
3945 line = NULL;
3946 }
3947 else
3948 {
3949 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3950
3951 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3952 return;
3953 p = ml_get_buf(buf, lnum + 1, FALSE);
3954 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3955 }
3956
3957 for (pos.col = 0; pos.col < term->tl_cols; )
3958 {
3959 dict_T *dcell;
3960 int width;
3961 VTermScreenCellAttrs attrs;
3962 VTermColor fg, bg;
3963 char_u rgb[8];
3964 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3965 int off = 0;
3966 int i;
3967
3968 if (screen == NULL)
3969 {
3970 cellattr_T *cellattr;
3971 int len;
3972
3973 /* vterm has finished, get the cell from scrollback */
3974 if (pos.col >= line->sb_cols)
3975 break;
3976 cellattr = line->sb_cells + pos.col;
3977 width = cellattr->width;
3978 attrs = cellattr->attrs;
3979 fg = cellattr->fg;
3980 bg = cellattr->bg;
3981 len = MB_PTR2LEN(p);
3982 mch_memmove(mbs, p, len);
3983 mbs[len] = NUL;
3984 p += len;
3985 }
3986 else
3987 {
3988 VTermScreenCell cell;
3989 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3990 break;
3991 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3992 {
3993 if (cell.chars[i] == 0)
3994 break;
3995 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3996 }
3997 mbs[off] = NUL;
3998 width = cell.width;
3999 attrs = cell.attrs;
4000 fg = cell.fg;
4001 bg = cell.bg;
4002 }
4003 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004004 if (dcell == NULL)
4005 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004006 list_append_dict(l, dcell);
4007
4008 dict_add_nr_str(dcell, "chars", 0, mbs);
4009
4010 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4011 fg.red, fg.green, fg.blue);
4012 dict_add_nr_str(dcell, "fg", 0, rgb);
4013 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4014 bg.red, bg.green, bg.blue);
4015 dict_add_nr_str(dcell, "bg", 0, rgb);
4016
4017 dict_add_nr_str(dcell, "attr",
4018 cell2attr(attrs, fg, bg), NULL);
4019 dict_add_nr_str(dcell, "width", width, NULL);
4020
4021 ++pos.col;
4022 if (width == 2)
4023 ++pos.col;
4024 }
4025}
4026
4027/*
4028 * "term_sendkeys(buf, keys)" function
4029 */
4030 void
4031f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4032{
4033 buf_T *buf = term_get_buf(argvars);
4034 char_u *msg;
4035 term_T *term;
4036
4037 rettv->v_type = VAR_UNKNOWN;
4038 if (buf == NULL)
4039 return;
4040
4041 msg = get_tv_string_chk(&argvars[1]);
4042 if (msg == NULL)
4043 return;
4044 term = buf->b_term;
4045 if (term->tl_vterm == NULL)
4046 return;
4047
4048 while (*msg != NUL)
4049 {
4050 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004051 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004052 }
4053}
4054
4055/*
4056 * "term_start(command, options)" function
4057 */
4058 void
4059f_term_start(typval_T *argvars, typval_T *rettv)
4060{
4061 jobopt_T opt;
4062 buf_T *buf;
4063
4064 init_job_options(&opt);
4065 if (argvars[1].v_type != VAR_UNKNOWN
4066 && get_job_options(&argvars[1], &opt,
4067 JO_TIMEOUT_ALL + JO_STOPONEXIT
4068 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4069 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4070 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4071 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
4072 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
4073 return;
4074
4075 if (opt.jo_vertical)
4076 cmdmod.split = WSP_VERT;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004077 buf = term_start(&argvars[0], &opt, FALSE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004078
4079 if (buf != NULL && buf->b_term != NULL)
4080 rettv->vval.v_number = buf->b_fnum;
4081}
4082
4083/*
4084 * "term_wait" function
4085 */
4086 void
4087f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4088{
4089 buf_T *buf = term_get_buf(argvars);
4090
4091 if (buf == NULL)
4092 {
4093 ch_log(NULL, "term_wait(): invalid argument");
4094 return;
4095 }
4096 if (buf->b_term->tl_job == NULL)
4097 {
4098 ch_log(NULL, "term_wait(): no job to wait for");
4099 return;
4100 }
4101 if (buf->b_term->tl_job->jv_channel == NULL)
4102 /* channel is closed, nothing to do */
4103 return;
4104
4105 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004106 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004107 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4108 {
4109 /* The job is dead, keep reading channel I/O until the channel is
4110 * closed. buf->b_term may become NULL if the terminal was closed while
4111 * waiting. */
4112 ch_log(NULL, "term_wait(): waiting for channel to close");
4113 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4114 {
4115 mch_check_messages();
4116 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01004117 if (!buf_valid(buf))
4118 /* If the terminal is closed when the channel is closed the
4119 * buffer disappears. */
4120 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004121 ui_delay(10L, FALSE);
4122 }
4123 mch_check_messages();
4124 parse_queued_messages();
4125 }
4126 else
4127 {
4128 long wait = 10L;
4129
4130 mch_check_messages();
4131 parse_queued_messages();
4132
4133 /* Wait for some time for any channel I/O. */
4134 if (argvars[1].v_type != VAR_UNKNOWN)
4135 wait = get_tv_number(&argvars[1]);
4136 ui_delay(wait, TRUE);
4137 mch_check_messages();
4138
4139 /* Flushing messages on channels is hopefully sufficient.
4140 * TODO: is there a better way? */
4141 parse_queued_messages();
4142 }
4143}
4144
4145/*
4146 * Called when a channel has sent all the lines to a terminal.
4147 * Send a CTRL-D to mark the end of the text.
4148 */
4149 void
4150term_send_eof(channel_T *ch)
4151{
4152 term_T *term;
4153
4154 for (term = first_term; term != NULL; term = term->tl_next)
4155 if (term->tl_job == ch->ch_job)
4156 {
4157 if (term->tl_eof_chars != NULL)
4158 {
4159 channel_send(ch, PART_IN, term->tl_eof_chars,
4160 (int)STRLEN(term->tl_eof_chars), NULL);
4161 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
4162 }
4163# ifdef WIN3264
4164 else
4165 /* Default: CTRL-D */
4166 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
4167# endif
4168 }
4169}
4170
4171# if defined(WIN3264) || defined(PROTO)
4172
4173/**************************************
4174 * 2. MS-Windows implementation.
4175 */
4176
4177# ifndef PROTO
4178
4179#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
4180#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01004181#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004182
4183void* (*winpty_config_new)(UINT64, void*);
4184void* (*winpty_open)(void*, void*);
4185void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
4186BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
4187void (*winpty_config_set_mouse_mode)(void*, int);
4188void (*winpty_config_set_initial_size)(void*, int, int);
4189LPCWSTR (*winpty_conin_name)(void*);
4190LPCWSTR (*winpty_conout_name)(void*);
4191LPCWSTR (*winpty_conerr_name)(void*);
4192void (*winpty_free)(void*);
4193void (*winpty_config_free)(void*);
4194void (*winpty_spawn_config_free)(void*);
4195void (*winpty_error_free)(void*);
4196LPCWSTR (*winpty_error_msg)(void*);
4197BOOL (*winpty_set_size)(void*, int, int, void*);
4198HANDLE (*winpty_agent_process)(void*);
4199
4200#define WINPTY_DLL "winpty.dll"
4201
4202static HINSTANCE hWinPtyDLL = NULL;
4203# endif
4204
4205 static int
4206dyn_winpty_init(int verbose)
4207{
4208 int i;
4209 static struct
4210 {
4211 char *name;
4212 FARPROC *ptr;
4213 } winpty_entry[] =
4214 {
4215 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
4216 {"winpty_config_free", (FARPROC*)&winpty_config_free},
4217 {"winpty_config_new", (FARPROC*)&winpty_config_new},
4218 {"winpty_config_set_mouse_mode",
4219 (FARPROC*)&winpty_config_set_mouse_mode},
4220 {"winpty_config_set_initial_size",
4221 (FARPROC*)&winpty_config_set_initial_size},
4222 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
4223 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
4224 {"winpty_error_free", (FARPROC*)&winpty_error_free},
4225 {"winpty_free", (FARPROC*)&winpty_free},
4226 {"winpty_open", (FARPROC*)&winpty_open},
4227 {"winpty_spawn", (FARPROC*)&winpty_spawn},
4228 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
4229 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
4230 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
4231 {"winpty_set_size", (FARPROC*)&winpty_set_size},
4232 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
4233 {NULL, NULL}
4234 };
4235
4236 /* No need to initialize twice. */
4237 if (hWinPtyDLL)
4238 return OK;
4239 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
4240 * winpty.dll. */
4241 if (*p_winptydll != NUL)
4242 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
4243 if (!hWinPtyDLL)
4244 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
4245 if (!hWinPtyDLL)
4246 {
4247 if (verbose)
4248 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
4249 : (char_u *)WINPTY_DLL);
4250 return FAIL;
4251 }
4252 for (i = 0; winpty_entry[i].name != NULL
4253 && winpty_entry[i].ptr != NULL; ++i)
4254 {
4255 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
4256 winpty_entry[i].name)) == NULL)
4257 {
4258 if (verbose)
4259 EMSG2(_(e_loadfunc), winpty_entry[i].name);
4260 return FAIL;
4261 }
4262 }
4263
4264 return OK;
4265}
4266
4267/*
4268 * Create a new terminal of "rows" by "cols" cells.
4269 * Store a reference in "term".
4270 * Return OK or FAIL.
4271 */
4272 static int
4273term_and_job_init(
4274 term_T *term,
4275 typval_T *argvar,
4276 jobopt_T *opt)
4277{
4278 WCHAR *cmd_wchar = NULL;
4279 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004280 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004281 channel_T *channel = NULL;
4282 job_T *job = NULL;
4283 DWORD error;
4284 HANDLE jo = NULL;
4285 HANDLE child_process_handle;
4286 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01004287 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004288 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004289 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004290 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004291
4292 if (dyn_winpty_init(TRUE) == FAIL)
4293 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004294 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
4295 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004296
4297 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004298 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004299 cmd = argvar->vval.v_string;
4300 }
4301 else if (argvar->v_type == VAR_LIST)
4302 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004303 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004304 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004305 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004306 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004307 if (cmd == NULL || *cmd == NUL)
4308 {
4309 EMSG(_(e_invarg));
4310 goto failed;
4311 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004312
4313 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004314 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004315 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004316 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004317 if (opt->jo_cwd != NULL)
4318 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004319
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004320 win32_build_env(opt->jo_env, &ga_env, TRUE);
4321 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004322
4323 job = job_alloc();
4324 if (job == NULL)
4325 goto failed;
4326
4327 channel = add_channel();
4328 if (channel == NULL)
4329 goto failed;
4330
4331 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
4332 if (term->tl_winpty_config == NULL)
4333 goto failed;
4334
4335 winpty_config_set_mouse_mode(term->tl_winpty_config,
4336 WINPTY_MOUSE_MODE_FORCE);
4337 winpty_config_set_initial_size(term->tl_winpty_config,
4338 term->tl_cols, term->tl_rows);
4339 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
4340 if (term->tl_winpty == NULL)
4341 goto failed;
4342
4343 spawn_config = winpty_spawn_config_new(
4344 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
4345 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
4346 NULL,
4347 cmd_wchar,
4348 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004349 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004350 &winpty_err);
4351 if (spawn_config == NULL)
4352 goto failed;
4353
4354 channel = add_channel();
4355 if (channel == NULL)
4356 goto failed;
4357
4358 job = job_alloc();
4359 if (job == NULL)
4360 goto failed;
4361
4362 if (opt->jo_set & JO_IN_BUF)
4363 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
4364
4365 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
4366 &child_thread_handle, &error, &winpty_err))
4367 goto failed;
4368
4369 channel_set_pipes(channel,
4370 (sock_T)CreateFileW(
4371 winpty_conin_name(term->tl_winpty),
4372 GENERIC_WRITE, 0, NULL,
4373 OPEN_EXISTING, 0, NULL),
4374 (sock_T)CreateFileW(
4375 winpty_conout_name(term->tl_winpty),
4376 GENERIC_READ, 0, NULL,
4377 OPEN_EXISTING, 0, NULL),
4378 (sock_T)CreateFileW(
4379 winpty_conerr_name(term->tl_winpty),
4380 GENERIC_READ, 0, NULL,
4381 OPEN_EXISTING, 0, NULL));
4382
4383 /* Write lines with CR instead of NL. */
4384 channel->ch_write_text_mode = TRUE;
4385
4386 jo = CreateJobObject(NULL, NULL);
4387 if (jo == NULL)
4388 goto failed;
4389
4390 if (!AssignProcessToJobObject(jo, child_process_handle))
4391 {
4392 /* Failed, switch the way to terminate process with TerminateProcess. */
4393 CloseHandle(jo);
4394 jo = NULL;
4395 }
4396
4397 winpty_spawn_config_free(spawn_config);
4398 vim_free(cmd_wchar);
4399 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004400 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004401
4402 create_vterm(term, term->tl_rows, term->tl_cols);
4403
4404 channel_set_job(channel, job, opt);
4405 job_set_options(job, opt);
4406
4407 job->jv_channel = channel;
4408 job->jv_proc_info.hProcess = child_process_handle;
4409 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
4410 job->jv_job_object = jo;
4411 job->jv_status = JOB_STARTED;
4412 job->jv_tty_in = utf16_to_enc(
4413 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
4414 job->jv_tty_out = utf16_to_enc(
4415 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
4416 ++job->jv_refcount;
4417 term->tl_job = job;
4418
4419 return OK;
4420
4421failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004422 ga_clear(&ga_cmd);
4423 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004424 vim_free(cmd_wchar);
4425 vim_free(cwd_wchar);
4426 if (spawn_config != NULL)
4427 winpty_spawn_config_free(spawn_config);
4428 if (channel != NULL)
4429 channel_clear(channel);
4430 if (job != NULL)
4431 {
4432 job->jv_channel = NULL;
4433 job_cleanup(job);
4434 }
4435 term->tl_job = NULL;
4436 if (jo != NULL)
4437 CloseHandle(jo);
4438 if (term->tl_winpty != NULL)
4439 winpty_free(term->tl_winpty);
4440 term->tl_winpty = NULL;
4441 if (term->tl_winpty_config != NULL)
4442 winpty_config_free(term->tl_winpty_config);
4443 term->tl_winpty_config = NULL;
4444 if (winpty_err != NULL)
4445 {
4446 char_u *msg = utf16_to_enc(
4447 (short_u *)winpty_error_msg(winpty_err), NULL);
4448
4449 EMSG(msg);
4450 winpty_error_free(winpty_err);
4451 }
4452 return FAIL;
4453}
4454
4455 static int
4456create_pty_only(term_T *term, jobopt_T *options)
4457{
4458 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
4459 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
4460 char in_name[80], out_name[80];
4461 channel_T *channel = NULL;
4462
4463 create_vterm(term, term->tl_rows, term->tl_cols);
4464
4465 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
4466 GetCurrentProcessId(),
4467 curbuf->b_fnum);
4468 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
4469 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4470 PIPE_UNLIMITED_INSTANCES,
4471 0, 0, NMPWAIT_NOWAIT, NULL);
4472 if (hPipeIn == INVALID_HANDLE_VALUE)
4473 goto failed;
4474
4475 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
4476 GetCurrentProcessId(),
4477 curbuf->b_fnum);
4478 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
4479 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4480 PIPE_UNLIMITED_INSTANCES,
4481 0, 0, 0, NULL);
4482 if (hPipeOut == INVALID_HANDLE_VALUE)
4483 goto failed;
4484
4485 ConnectNamedPipe(hPipeIn, NULL);
4486 ConnectNamedPipe(hPipeOut, NULL);
4487
4488 term->tl_job = job_alloc();
4489 if (term->tl_job == NULL)
4490 goto failed;
4491 ++term->tl_job->jv_refcount;
4492
4493 /* behave like the job is already finished */
4494 term->tl_job->jv_status = JOB_FINISHED;
4495
4496 channel = add_channel();
4497 if (channel == NULL)
4498 goto failed;
4499 term->tl_job->jv_channel = channel;
4500 channel->ch_keep_open = TRUE;
4501 channel->ch_named_pipe = TRUE;
4502
4503 channel_set_pipes(channel,
4504 (sock_T)hPipeIn,
4505 (sock_T)hPipeOut,
4506 (sock_T)hPipeOut);
4507 channel_set_job(channel, term->tl_job, options);
4508 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
4509 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
4510
4511 return OK;
4512
4513failed:
4514 if (hPipeIn != NULL)
4515 CloseHandle(hPipeIn);
4516 if (hPipeOut != NULL)
4517 CloseHandle(hPipeOut);
4518 return FAIL;
4519}
4520
4521/*
4522 * Free the terminal emulator part of "term".
4523 */
4524 static void
4525term_free_vterm(term_T *term)
4526{
4527 if (term->tl_winpty != NULL)
4528 winpty_free(term->tl_winpty);
4529 term->tl_winpty = NULL;
4530 if (term->tl_winpty_config != NULL)
4531 winpty_config_free(term->tl_winpty_config);
4532 term->tl_winpty_config = NULL;
4533 if (term->tl_vterm != NULL)
4534 vterm_free(term->tl_vterm);
4535 term->tl_vterm = NULL;
4536}
4537
4538/*
4539 * Request size to terminal.
4540 */
4541 static void
4542term_report_winsize(term_T *term, int rows, int cols)
4543{
4544 if (term->tl_winpty)
4545 winpty_set_size(term->tl_winpty, cols, rows, NULL);
4546}
4547
4548 int
4549terminal_enabled(void)
4550{
4551 return dyn_winpty_init(FALSE) == OK;
4552}
4553
4554# else
4555
4556/**************************************
4557 * 3. Unix-like implementation.
4558 */
4559
4560/*
4561 * Create a new terminal of "rows" by "cols" cells.
4562 * Start job for "cmd".
4563 * Store the pointers in "term".
4564 * Return OK or FAIL.
4565 */
4566 static int
4567term_and_job_init(
4568 term_T *term,
4569 typval_T *argvar,
4570 jobopt_T *opt)
4571{
4572 create_vterm(term, term->tl_rows, term->tl_cols);
4573
4574 term->tl_job = job_start(argvar, opt);
4575 if (term->tl_job != NULL)
4576 ++term->tl_job->jv_refcount;
4577
4578 return term->tl_job != NULL
4579 && term->tl_job->jv_channel != NULL
4580 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
4581}
4582
4583 static int
4584create_pty_only(term_T *term, jobopt_T *opt)
4585{
4586 create_vterm(term, term->tl_rows, term->tl_cols);
4587
4588 term->tl_job = job_alloc();
4589 if (term->tl_job == NULL)
4590 return FAIL;
4591 ++term->tl_job->jv_refcount;
4592
4593 /* behave like the job is already finished */
4594 term->tl_job->jv_status = JOB_FINISHED;
4595
4596 return mch_create_pty_channel(term->tl_job, opt);
4597}
4598
4599/*
4600 * Free the terminal emulator part of "term".
4601 */
4602 static void
4603term_free_vterm(term_T *term)
4604{
4605 if (term->tl_vterm != NULL)
4606 vterm_free(term->tl_vterm);
4607 term->tl_vterm = NULL;
4608}
4609
4610/*
4611 * Request size to terminal.
4612 */
4613 static void
4614term_report_winsize(term_T *term, int rows, int cols)
4615{
4616 /* Use an ioctl() to report the new window size to the job. */
4617 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
4618 {
4619 int fd = -1;
4620 int part;
4621
4622 for (part = PART_OUT; part < PART_COUNT; ++part)
4623 {
4624 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
4625 if (isatty(fd))
4626 break;
4627 }
4628 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
4629 mch_signal_job(term->tl_job, (char_u *)"winch");
4630 }
4631}
4632
4633# endif
4634
4635#endif /* FEAT_TERMINAL */