blob: bcdc70025fe4116a4a3a2ee77236bffe1fa30b8c [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 {
413 /* only one size was taken care of with :new, do the other one */
414 if (opt->jo_term_rows > 0 && (cmdmod.split & WSP_VERT))
415 win_setheight(opt->jo_term_rows);
416 if (opt->jo_term_cols > 0 && !(cmdmod.split & WSP_VERT))
417 win_setwidth(opt->jo_term_cols);
418 }
419
420 /* Link the new terminal in the list of active terminals. */
421 term->tl_next = first_term;
422 first_term = term;
423
424 if (opt->jo_term_name != NULL)
425 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
426 else
427 {
428 int i;
429 size_t len;
430 char_u *cmd, *p;
431
432 if (argvar->v_type == VAR_STRING)
433 {
434 cmd = argvar->vval.v_string;
435 if (cmd == NULL)
436 cmd = (char_u *)"";
437 else if (STRCMP(cmd, "NONE") == 0)
438 cmd = (char_u *)"pty";
439 }
440 else if (argvar->v_type != VAR_LIST
441 || argvar->vval.v_list == NULL
442 || argvar->vval.v_list->lv_len < 1
443 || (cmd = get_tv_string_chk(
444 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
445 cmd = (char_u*)"";
446
447 len = STRLEN(cmd) + 10;
448 p = alloc((int)len);
449
450 for (i = 0; p != NULL; ++i)
451 {
452 /* Prepend a ! to the command name to avoid the buffer name equals
453 * the executable, otherwise ":w!" would overwrite it. */
454 if (i == 0)
455 vim_snprintf((char *)p, len, "!%s", cmd);
456 else
457 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
458 if (buflist_findname(p) == NULL)
459 {
460 vim_free(curbuf->b_ffname);
461 curbuf->b_ffname = p;
462 break;
463 }
464 }
465 }
466 curbuf->b_fname = curbuf->b_ffname;
467
468 if (opt->jo_term_opencmd != NULL)
469 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
470
471 if (opt->jo_eof_chars != NULL)
472 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
473
474 set_string_option_direct((char_u *)"buftype", -1,
475 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
476
477 /* Mark the buffer as not modifiable. It can only be made modifiable after
478 * the job finished. */
479 curbuf->b_p_ma = FALSE;
480
481 set_term_and_win_size(term);
482 setup_job_options(opt, term->tl_rows, term->tl_cols);
483
Bram Moolenaard96ff162018-02-18 22:13:29 +0100484 if (without_job)
485 return curbuf;
486
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200487 /* System dependent: setup the vterm and maybe start the job in it. */
488 if (argvar->v_type == VAR_STRING
489 && argvar->vval.v_string != NULL
490 && STRCMP(argvar->vval.v_string, "NONE") == 0)
491 res = create_pty_only(term, opt);
492 else
493 res = term_and_job_init(term, argvar, opt);
494
495 newbuf = curbuf;
496 if (res == OK)
497 {
498 /* Get and remember the size we ended up with. Update the pty. */
499 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
500 term_report_winsize(term, term->tl_rows, term->tl_cols);
501
502 /* Make sure we don't get stuck on sending keys to the job, it leads to
503 * a deadlock if the job is waiting for Vim to read. */
504 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
505
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200506#ifdef FEAT_AUTOCMD
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100507 if (!opt->jo_hidden)
508 {
509 ++curbuf->b_locked;
510 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
511 --curbuf->b_locked;
512 }
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200513#endif
514
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200515 if (old_curbuf != NULL)
516 {
517 --curbuf->b_nwindows;
518 curbuf = old_curbuf;
519 curwin->w_buffer = curbuf;
520 ++curbuf->b_nwindows;
521 }
522 }
523 else
524 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100525 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200526 return NULL;
527 }
528 return newbuf;
529}
530
531/*
532 * ":terminal": open a terminal window and execute a job in it.
533 */
534 void
535ex_terminal(exarg_T *eap)
536{
537 typval_T argvar[2];
538 jobopt_T opt;
539 char_u *cmd;
540 char_u *tofree = NULL;
541
542 init_job_options(&opt);
543
544 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100545 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200546 {
547 char_u *p, *ep;
548
549 cmd += 2;
550 p = skiptowhite(cmd);
551 ep = vim_strchr(cmd, '=');
552 if (ep != NULL && ep < p)
553 p = ep;
554
555 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
556 opt.jo_term_finish = 'c';
557 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
558 opt.jo_term_finish = 'o';
559 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
560 opt.jo_curwin = 1;
561 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
562 opt.jo_hidden = 1;
563 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
564 && ep != NULL && isdigit(ep[1]))
565 {
566 opt.jo_set2 |= JO2_TERM_ROWS;
567 opt.jo_term_rows = atoi((char *)ep + 1);
568 p = skiptowhite(cmd);
569 }
570 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
571 && ep != NULL && isdigit(ep[1]))
572 {
573 opt.jo_set2 |= JO2_TERM_COLS;
574 opt.jo_term_cols = atoi((char *)ep + 1);
575 p = skiptowhite(cmd);
576 }
577 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
578 && ep != NULL)
579 {
580 char_u *buf = NULL;
581 char_u *keys;
582
583 p = skiptowhite(cmd);
584 *p = NUL;
585 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
586 opt.jo_set2 |= JO2_EOF_CHARS;
587 opt.jo_eof_chars = vim_strsave(keys);
588 vim_free(buf);
589 *p = ' ';
590 }
591 else
592 {
593 if (*p)
594 *p = NUL;
595 EMSG2(_("E181: Invalid attribute: %s"), cmd);
596 return;
597 }
598 cmd = skipwhite(p);
599 }
600 if (*cmd == NUL)
601 /* Make a copy of 'shell', an autocommand may change the option. */
602 tofree = cmd = vim_strsave(p_sh);
603
604 if (eap->addr_count > 0)
605 {
606 /* Write lines from current buffer to the job. */
607 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
608 opt.jo_io[PART_IN] = JIO_BUFFER;
609 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
610 opt.jo_in_top = eap->line1;
611 opt.jo_in_bot = eap->line2;
612 }
613
614 argvar[0].v_type = VAR_STRING;
615 argvar[0].vval.v_string = cmd;
616 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100617 term_start(argvar, &opt, FALSE, eap->forceit);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200618 vim_free(tofree);
619 vim_free(opt.jo_eof_chars);
620}
621
622/*
623 * Free the scrollback buffer for "term".
624 */
625 static void
626free_scrollback(term_T *term)
627{
628 int i;
629
630 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
631 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
632 ga_clear(&term->tl_scrollback);
633}
634
635/*
636 * Free a terminal and everything it refers to.
637 * Kills the job if there is one.
638 * Called when wiping out a buffer.
639 */
640 void
641free_terminal(buf_T *buf)
642{
643 term_T *term = buf->b_term;
644 term_T *tp;
645
646 if (term == NULL)
647 return;
648 if (first_term == term)
649 first_term = term->tl_next;
650 else
651 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
652 if (tp->tl_next == term)
653 {
654 tp->tl_next = term->tl_next;
655 break;
656 }
657
658 if (term->tl_job != NULL)
659 {
660 if (term->tl_job->jv_status != JOB_ENDED
661 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100662 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200663 job_stop(term->tl_job, NULL, "kill");
664 job_unref(term->tl_job);
665 }
666
667 free_scrollback(term);
668
669 term_free_vterm(term);
670 vim_free(term->tl_title);
671 vim_free(term->tl_status_text);
672 vim_free(term->tl_opencmd);
673 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100674 if (desired_cursor_color == term->tl_cursor_color)
675 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200676 vim_free(term->tl_cursor_color);
677 vim_free(term);
678 buf->b_term = NULL;
679 if (in_terminal_loop == term)
680 in_terminal_loop = NULL;
681}
682
683/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100684 * Get the part that is connected to the tty. Normally this is PART_IN, but
685 * when writing buffer lines to the job it can be another. This makes it
686 * possible to do "1,5term vim -".
687 */
688 static ch_part_T
689get_tty_part(term_T *term)
690{
691#ifdef UNIX
692 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
693 int i;
694
695 for (i = 0; i < 3; ++i)
696 {
697 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
698
699 if (isatty(fd))
700 return parts[i];
701 }
702#endif
703 return PART_IN;
704}
705
706/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200707 * Write job output "msg[len]" to the vterm.
708 */
709 static void
710term_write_job_output(term_T *term, char_u *msg, size_t len)
711{
712 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100713 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200714
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100715 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200716
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100717 /* flush vterm buffer when vterm responded to control sequence */
718 if (prevlen != vterm_output_get_buffer_current(vterm))
719 {
720 char buf[KEY_BUF_LEN];
721 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
722
723 if (curlen > 0)
724 channel_send(term->tl_job->jv_channel, get_tty_part(term),
725 (char_u *)buf, (int)curlen, NULL);
726 }
727
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200728 /* this invokes the damage callbacks */
729 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
730}
731
732 static void
733update_cursor(term_T *term, int redraw)
734{
735 if (term->tl_normal_mode)
736 return;
737 setcursor();
738 if (redraw)
739 {
740 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
741 cursor_on();
742 out_flush();
743#ifdef FEAT_GUI
744 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100745 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200746 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100747 gui_mch_flush();
748 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200749#endif
750 }
751}
752
753/*
754 * Invoked when "msg" output from a job was received. Write it to the terminal
755 * of "buffer".
756 */
757 void
758write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
759{
760 size_t len = STRLEN(msg);
761 term_T *term = buffer->b_term;
762
763 if (term->tl_vterm == NULL)
764 {
765 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
766 return;
767 }
768 ch_log(channel, "writing %d bytes to terminal", (int)len);
769 term_write_job_output(term, msg, len);
770
771 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
772 * contents, thus no screen update is needed. */
773 if (!term->tl_normal_mode)
774 {
775 /* TODO: only update once in a while. */
776 ch_log(term->tl_job->jv_channel, "updating screen");
777 if (buffer == curbuf)
778 {
779 update_screen(0);
780 update_cursor(term, TRUE);
781 }
782 else
783 redraw_after_callback(TRUE);
784 }
785}
786
787/*
788 * Send a mouse position and click to the vterm
789 */
790 static int
791term_send_mouse(VTerm *vterm, int button, int pressed)
792{
793 VTermModifier mod = VTERM_MOD_NONE;
794
795 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200796 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100797 if (button != 0)
798 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200799 return TRUE;
800}
801
802/*
803 * Convert typed key "c" into bytes to send to the job.
804 * Return the number of bytes in "buf".
805 */
806 static int
807term_convert_key(term_T *term, int c, char *buf)
808{
809 VTerm *vterm = term->tl_vterm;
810 VTermKey key = VTERM_KEY_NONE;
811 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100812 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813
814 switch (c)
815 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100816 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
817
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818 /* don't use VTERM_KEY_BACKSPACE, it always
819 * becomes 0x7f DEL */
820 case K_BS: c = term_backspace_char; break;
821
822 case ESC: key = VTERM_KEY_ESCAPE; break;
823 case K_DEL: key = VTERM_KEY_DEL; break;
824 case K_DOWN: key = VTERM_KEY_DOWN; break;
825 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
826 key = VTERM_KEY_DOWN; break;
827 case K_END: key = VTERM_KEY_END; break;
828 case K_S_END: mod = VTERM_MOD_SHIFT;
829 key = VTERM_KEY_END; break;
830 case K_C_END: mod = VTERM_MOD_CTRL;
831 key = VTERM_KEY_END; break;
832 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
833 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
834 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
835 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
836 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
837 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
838 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
839 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
840 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
841 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
842 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
843 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
844 case K_HOME: key = VTERM_KEY_HOME; break;
845 case K_S_HOME: mod = VTERM_MOD_SHIFT;
846 key = VTERM_KEY_HOME; break;
847 case K_C_HOME: mod = VTERM_MOD_CTRL;
848 key = VTERM_KEY_HOME; break;
849 case K_INS: key = VTERM_KEY_INS; break;
850 case K_K0: key = VTERM_KEY_KP_0; break;
851 case K_K1: key = VTERM_KEY_KP_1; break;
852 case K_K2: key = VTERM_KEY_KP_2; break;
853 case K_K3: key = VTERM_KEY_KP_3; break;
854 case K_K4: key = VTERM_KEY_KP_4; break;
855 case K_K5: key = VTERM_KEY_KP_5; break;
856 case K_K6: key = VTERM_KEY_KP_6; break;
857 case K_K7: key = VTERM_KEY_KP_7; break;
858 case K_K8: key = VTERM_KEY_KP_8; break;
859 case K_K9: key = VTERM_KEY_KP_9; break;
860 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
861 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
862 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
863 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
864 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
865 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
866 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
867 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
868 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
869 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
870 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
871 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
872 case K_LEFT: key = VTERM_KEY_LEFT; break;
873 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
874 key = VTERM_KEY_LEFT; break;
875 case K_C_LEFT: mod = VTERM_MOD_CTRL;
876 key = VTERM_KEY_LEFT; break;
877 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
878 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
879 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
880 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
881 key = VTERM_KEY_RIGHT; break;
882 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
883 key = VTERM_KEY_RIGHT; break;
884 case K_UP: key = VTERM_KEY_UP; break;
885 case K_S_UP: mod = VTERM_MOD_SHIFT;
886 key = VTERM_KEY_UP; break;
887 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +0100888 case K_S_TAB: mod = VTERM_MOD_SHIFT;
889 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200890
Bram Moolenaara42ad572017-11-16 13:08:04 +0100891 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
892 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200893 case K_MOUSELEFT: /* TODO */ return 0;
894 case K_MOUSERIGHT: /* TODO */ return 0;
895
896 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100897 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
898 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200899 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100900 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100901 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100902 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
903 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
904 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
905 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
906 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
907 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200908 case K_X1MOUSE: /* TODO */ return 0;
909 case K_X1DRAG: /* TODO */ return 0;
910 case K_X1RELEASE: /* TODO */ return 0;
911 case K_X2MOUSE: /* TODO */ return 0;
912 case K_X2DRAG: /* TODO */ return 0;
913 case K_X2RELEASE: /* TODO */ return 0;
914
915 case K_IGNORE: return 0;
916 case K_NOP: return 0;
917 case K_UNDO: return 0;
918 case K_HELP: return 0;
919 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
920 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
921 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
922 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
923 case K_SELECT: return 0;
924#ifdef FEAT_GUI
925 case K_VER_SCROLLBAR: return 0;
926 case K_HOR_SCROLLBAR: return 0;
927#endif
928#ifdef FEAT_GUI_TABLINE
929 case K_TABLINE: return 0;
930 case K_TABMENU: return 0;
931#endif
932#ifdef FEAT_NETBEANS_INTG
933 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
934#endif
935#ifdef FEAT_DND
936 case K_DROP: return 0;
937#endif
938#ifdef FEAT_AUTOCMD
939 case K_CURSORHOLD: return 0;
940#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100941 case K_PS: vterm_keyboard_start_paste(vterm);
942 other = TRUE;
943 break;
944 case K_PE: vterm_keyboard_end_paste(vterm);
945 other = TRUE;
946 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200947 }
948
949 /*
950 * Convert special keys to vterm keys:
951 * - Write keys to vterm: vterm_keyboard_key()
952 * - Write output to channel.
953 * TODO: use mod_mask
954 */
955 if (key != VTERM_KEY_NONE)
956 /* Special key, let vterm convert it. */
957 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100958 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200959 /* Normal character, let vterm convert it. */
960 vterm_keyboard_unichar(vterm, c, mod);
961
962 /* Read back the converted escape sequence. */
963 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
964}
965
966/*
967 * Return TRUE if the job for "term" is still running.
968 */
969 int
970term_job_running(term_T *term)
971{
972 /* Also consider the job finished when the channel is closed, to avoid a
973 * race condition when updating the title. */
974 return term != NULL
975 && term->tl_job != NULL
976 && channel_is_open(term->tl_job->jv_channel)
977 && (term->tl_job->jv_status == JOB_STARTED
978 || term->tl_job->jv_channel->ch_keep_open);
979}
980
981/*
982 * Return TRUE if "term" has an active channel and used ":term NONE".
983 */
984 int
985term_none_open(term_T *term)
986{
987 /* Also consider the job finished when the channel is closed, to avoid a
988 * race condition when updating the title. */
989 return term != NULL
990 && term->tl_job != NULL
991 && channel_is_open(term->tl_job->jv_channel)
992 && term->tl_job->jv_channel->ch_keep_open;
993}
994
995/*
996 * Add the last line of the scrollback buffer to the buffer in the window.
997 */
998 static void
999add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1000{
1001 buf_T *buf = term->tl_buffer;
1002 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1003 linenr_T lnum = buf->b_ml.ml_line_count;
1004
1005#ifdef WIN3264
1006 if (!enc_utf8 && enc_codepage > 0)
1007 {
1008 WCHAR *ret = NULL;
1009 int length = 0;
1010
1011 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1012 &ret, &length);
1013 if (ret != NULL)
1014 {
1015 WideCharToMultiByte_alloc(enc_codepage, 0,
1016 ret, length, (char **)&text, &len, 0, 0);
1017 vim_free(ret);
1018 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1019 vim_free(text);
1020 }
1021 }
1022 else
1023#endif
1024 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1025 if (empty)
1026 {
1027 /* Delete the empty line that was in the empty buffer. */
1028 curbuf = buf;
1029 ml_delete(1, FALSE);
1030 curbuf = curwin->w_buffer;
1031 }
1032}
1033
1034 static void
1035cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1036{
1037 attr->width = cell->width;
1038 attr->attrs = cell->attrs;
1039 attr->fg = cell->fg;
1040 attr->bg = cell->bg;
1041}
1042
1043 static int
1044equal_celattr(cellattr_T *a, cellattr_T *b)
1045{
1046 /* Comparing the colors should be sufficient. */
1047 return a->fg.red == b->fg.red
1048 && a->fg.green == b->fg.green
1049 && a->fg.blue == b->fg.blue
1050 && a->bg.red == b->bg.red
1051 && a->bg.green == b->bg.green
1052 && a->bg.blue == b->bg.blue;
1053}
1054
Bram Moolenaard96ff162018-02-18 22:13:29 +01001055/*
1056 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1057 * line at this position. Otherwise at the end.
1058 */
1059 static int
1060add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1061{
1062 if (ga_grow(&term->tl_scrollback, 1) == OK)
1063 {
1064 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1065 + term->tl_scrollback.ga_len;
1066
1067 if (lnum > 0)
1068 {
1069 int i;
1070
1071 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1072 {
1073 *line = *(line - 1);
1074 --line;
1075 }
1076 }
1077 line->sb_cols = 0;
1078 line->sb_cells = NULL;
1079 line->sb_fill_attr = *fill_attr;
1080 ++term->tl_scrollback.ga_len;
1081 return OK;
1082 }
1083 return FALSE;
1084}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001085
1086/*
1087 * Add the current lines of the terminal to scrollback and to the buffer.
1088 * Called after the job has ended and when switching to Terminal-Normal mode.
1089 */
1090 static void
1091move_terminal_to_buffer(term_T *term)
1092{
1093 win_T *wp;
1094 int len;
1095 int lines_skipped = 0;
1096 VTermPos pos;
1097 VTermScreenCell cell;
1098 cellattr_T fill_attr, new_fill_attr;
1099 cellattr_T *p;
1100 VTermScreen *screen;
1101
1102 if (term->tl_vterm == NULL)
1103 return;
1104 screen = vterm_obtain_screen(term->tl_vterm);
1105 fill_attr = new_fill_attr = term->tl_default_color;
1106
1107 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1108 {
1109 len = 0;
1110 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1111 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1112 && cell.chars[0] != NUL)
1113 {
1114 len = pos.col + 1;
1115 new_fill_attr = term->tl_default_color;
1116 }
1117 else
1118 /* Assume the last attr is the filler attr. */
1119 cell2cellattr(&cell, &new_fill_attr);
1120
1121 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1122 ++lines_skipped;
1123 else
1124 {
1125 while (lines_skipped > 0)
1126 {
1127 /* Line was skipped, add an empty line. */
1128 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001129 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001130 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001131 }
1132
1133 if (len == 0)
1134 p = NULL;
1135 else
1136 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1137 if ((p != NULL || len == 0)
1138 && ga_grow(&term->tl_scrollback, 1) == OK)
1139 {
1140 garray_T ga;
1141 int width;
1142 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1143 + term->tl_scrollback.ga_len;
1144
1145 ga_init2(&ga, 1, 100);
1146 for (pos.col = 0; pos.col < len; pos.col += width)
1147 {
1148 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1149 {
1150 width = 1;
1151 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1152 if (ga_grow(&ga, 1) == OK)
1153 ga.ga_len += utf_char2bytes(' ',
1154 (char_u *)ga.ga_data + ga.ga_len);
1155 }
1156 else
1157 {
1158 width = cell.width;
1159
1160 cell2cellattr(&cell, &p[pos.col]);
1161
1162 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1163 {
1164 int i;
1165 int c;
1166
1167 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1168 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1169 (char_u *)ga.ga_data + ga.ga_len);
1170 }
1171 }
1172 }
1173 line->sb_cols = len;
1174 line->sb_cells = p;
1175 line->sb_fill_attr = new_fill_attr;
1176 fill_attr = new_fill_attr;
1177 ++term->tl_scrollback.ga_len;
1178
1179 if (ga_grow(&ga, 1) == FAIL)
1180 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1181 else
1182 {
1183 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1184 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1185 }
1186 ga_clear(&ga);
1187 }
1188 else
1189 vim_free(p);
1190 }
1191 }
1192
1193 /* Obtain the current background color. */
1194 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1195 &term->tl_default_color.fg, &term->tl_default_color.bg);
1196
1197 FOR_ALL_WINDOWS(wp)
1198 {
1199 if (wp->w_buffer == term->tl_buffer)
1200 {
1201 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1202 wp->w_cursor.col = 0;
1203 wp->w_valid = 0;
1204 if (wp->w_cursor.lnum >= wp->w_height)
1205 {
1206 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1207
1208 if (wp->w_topline < min_topline)
1209 wp->w_topline = min_topline;
1210 }
1211 redraw_win_later(wp, NOT_VALID);
1212 }
1213 }
1214}
1215
1216 static void
1217set_terminal_mode(term_T *term, int normal_mode)
1218{
1219 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001220 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001221 if (term->tl_buffer == curbuf)
1222 maketitle();
1223}
1224
1225/*
1226 * Called after the job if finished and Terminal mode is not active:
1227 * Move the vterm contents into the scrollback buffer and free the vterm.
1228 */
1229 static void
1230cleanup_vterm(term_T *term)
1231{
1232 if (term->tl_finish != 'c')
1233 move_terminal_to_buffer(term);
1234 term_free_vterm(term);
1235 set_terminal_mode(term, FALSE);
1236}
1237
1238/*
1239 * Switch from Terminal-Job mode to Terminal-Normal mode.
1240 * Suspends updating the terminal window.
1241 */
1242 static void
1243term_enter_normal_mode(void)
1244{
1245 term_T *term = curbuf->b_term;
1246
1247 /* Append the current terminal contents to the buffer. */
1248 move_terminal_to_buffer(term);
1249
1250 set_terminal_mode(term, TRUE);
1251
1252 /* Move the window cursor to the position of the cursor in the
1253 * terminal. */
1254 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1255 + term->tl_cursor_pos.row + 1;
1256 check_cursor();
1257 coladvance(term->tl_cursor_pos.col);
1258
1259 /* Display the same lines as in the terminal. */
1260 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1261}
1262
1263/*
1264 * Returns TRUE if the current window contains a terminal and we are in
1265 * Terminal-Normal mode.
1266 */
1267 int
1268term_in_normal_mode(void)
1269{
1270 term_T *term = curbuf->b_term;
1271
1272 return term != NULL && term->tl_normal_mode;
1273}
1274
1275/*
1276 * Switch from Terminal-Normal mode to Terminal-Job mode.
1277 * Restores updating the terminal window.
1278 */
1279 void
1280term_enter_job_mode()
1281{
1282 term_T *term = curbuf->b_term;
1283 sb_line_T *line;
1284 garray_T *gap;
1285
1286 /* Remove the terminal contents from the scrollback and the buffer. */
1287 gap = &term->tl_scrollback;
1288 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1289 && gap->ga_len > 0)
1290 {
1291 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1292 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1293 vim_free(line->sb_cells);
1294 --gap->ga_len;
1295 }
1296 check_cursor();
1297
1298 set_terminal_mode(term, FALSE);
1299
1300 if (term->tl_channel_closed)
1301 cleanup_vterm(term);
1302 redraw_buf_and_status_later(curbuf, NOT_VALID);
1303}
1304
1305/*
1306 * Get a key from the user without mapping.
1307 * Note: while waiting a terminal may be closed and freed if the channel is
1308 * closed and ++close was used.
1309 * Uses terminal mode mappings.
1310 */
1311 static int
1312term_vgetc()
1313{
1314 int c;
1315 int save_State = State;
1316
1317 State = TERMINAL;
1318 got_int = FALSE;
1319#ifdef WIN3264
1320 ctrl_break_was_pressed = FALSE;
1321#endif
1322 c = vgetc();
1323 got_int = FALSE;
1324 State = save_State;
1325 return c;
1326}
1327
1328/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001329 * Send keys to terminal.
1330 * Return FAIL when the key needs to be handled in Normal mode.
1331 * Return OK when the key was dropped or sent to the terminal.
1332 */
1333 int
1334send_keys_to_term(term_T *term, int c, int typed)
1335{
1336 char msg[KEY_BUF_LEN];
1337 size_t len;
1338 static int mouse_was_outside = FALSE;
1339 int dragging_outside = FALSE;
1340
1341 /* Catch keys that need to be handled as in Normal mode. */
1342 switch (c)
1343 {
1344 case NUL:
1345 case K_ZERO:
1346 if (typed)
1347 stuffcharReadbuff(c);
1348 return FAIL;
1349
1350 case K_IGNORE:
1351 return FAIL;
1352
1353 case K_LEFTDRAG:
1354 case K_MIDDLEDRAG:
1355 case K_RIGHTDRAG:
1356 case K_X1DRAG:
1357 case K_X2DRAG:
1358 dragging_outside = mouse_was_outside;
1359 /* FALLTHROUGH */
1360 case K_LEFTMOUSE:
1361 case K_LEFTMOUSE_NM:
1362 case K_LEFTRELEASE:
1363 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001364 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001365 case K_MIDDLEMOUSE:
1366 case K_MIDDLERELEASE:
1367 case K_RIGHTMOUSE:
1368 case K_RIGHTRELEASE:
1369 case K_X1MOUSE:
1370 case K_X1RELEASE:
1371 case K_X2MOUSE:
1372 case K_X2RELEASE:
1373
1374 case K_MOUSEUP:
1375 case K_MOUSEDOWN:
1376 case K_MOUSELEFT:
1377 case K_MOUSERIGHT:
1378 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001379 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001380 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001381 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001382 || dragging_outside)
1383 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001384 /* click or scroll outside the current window or on status line
1385 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001386 if (typed)
1387 {
1388 stuffcharReadbuff(c);
1389 mouse_was_outside = TRUE;
1390 }
1391 return FAIL;
1392 }
1393 }
1394 if (typed)
1395 mouse_was_outside = FALSE;
1396
1397 /* Convert the typed key to a sequence of bytes for the job. */
1398 len = term_convert_key(term, c, msg);
1399 if (len > 0)
1400 /* TODO: if FAIL is returned, stop? */
1401 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1402 (char_u *)msg, (int)len, NULL);
1403
1404 return OK;
1405}
1406
1407 static void
1408position_cursor(win_T *wp, VTermPos *pos)
1409{
1410 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1411 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1412 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1413}
1414
1415/*
1416 * Handle CTRL-W "": send register contents to the job.
1417 */
1418 static void
1419term_paste_register(int prev_c UNUSED)
1420{
1421 int c;
1422 list_T *l;
1423 listitem_T *item;
1424 long reglen = 0;
1425 int type;
1426
1427#ifdef FEAT_CMDL_INFO
1428 if (add_to_showcmd(prev_c))
1429 if (add_to_showcmd('"'))
1430 out_flush();
1431#endif
1432 c = term_vgetc();
1433#ifdef FEAT_CMDL_INFO
1434 clear_showcmd();
1435#endif
1436 if (!term_use_loop())
1437 /* job finished while waiting for a character */
1438 return;
1439
1440 /* CTRL-W "= prompt for expression to evaluate. */
1441 if (c == '=' && get_expr_register() != '=')
1442 return;
1443 if (!term_use_loop())
1444 /* job finished while waiting for a character */
1445 return;
1446
1447 l = (list_T *)get_reg_contents(c, GREG_LIST);
1448 if (l != NULL)
1449 {
1450 type = get_reg_type(c, &reglen);
1451 for (item = l->lv_first; item != NULL; item = item->li_next)
1452 {
1453 char_u *s = get_tv_string(&item->li_tv);
1454#ifdef WIN3264
1455 char_u *tmp = s;
1456
1457 if (!enc_utf8 && enc_codepage > 0)
1458 {
1459 WCHAR *ret = NULL;
1460 int length = 0;
1461
1462 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1463 (int)STRLEN(s), &ret, &length);
1464 if (ret != NULL)
1465 {
1466 WideCharToMultiByte_alloc(CP_UTF8, 0,
1467 ret, length, (char **)&s, &length, 0, 0);
1468 vim_free(ret);
1469 }
1470 }
1471#endif
1472 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1473 s, (int)STRLEN(s), NULL);
1474#ifdef WIN3264
1475 if (tmp != s)
1476 vim_free(s);
1477#endif
1478
1479 if (item->li_next != NULL || type == MLINE)
1480 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1481 (char_u *)"\r", 1, NULL);
1482 }
1483 list_free(l);
1484 }
1485}
1486
1487#if defined(FEAT_GUI) || defined(PROTO)
1488/*
1489 * Return TRUE when the cursor of the terminal should be displayed.
1490 */
1491 int
1492terminal_is_active()
1493{
1494 return in_terminal_loop != NULL;
1495}
1496
1497 cursorentry_T *
1498term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1499{
1500 term_T *term = in_terminal_loop;
1501 static cursorentry_T entry;
1502
1503 vim_memset(&entry, 0, sizeof(entry));
1504 entry.shape = entry.mshape =
1505 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1506 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1507 SHAPE_BLOCK;
1508 entry.percentage = 20;
1509 if (term->tl_cursor_blink)
1510 {
1511 entry.blinkwait = 700;
1512 entry.blinkon = 400;
1513 entry.blinkoff = 250;
1514 }
1515 *fg = gui.back_pixel;
1516 if (term->tl_cursor_color == NULL)
1517 *bg = gui.norm_pixel;
1518 else
1519 *bg = color_name2handle(term->tl_cursor_color);
1520 entry.name = "n";
1521 entry.used_for = SHAPE_CURSOR;
1522
1523 return &entry;
1524}
1525#endif
1526
Bram Moolenaard317b382018-02-08 22:33:31 +01001527 static void
1528may_output_cursor_props(void)
1529{
1530 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1531 || last_set_cursor_shape != desired_cursor_shape
1532 || last_set_cursor_blink != desired_cursor_blink)
1533 {
1534 last_set_cursor_color = desired_cursor_color;
1535 last_set_cursor_shape = desired_cursor_shape;
1536 last_set_cursor_blink = desired_cursor_blink;
1537 term_cursor_color(desired_cursor_color);
1538 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1539 /* this will restore the initial cursor style, if possible */
1540 ui_cursor_shape_forced(TRUE);
1541 else
1542 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1543 }
1544}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001545
Bram Moolenaard317b382018-02-08 22:33:31 +01001546/*
1547 * Set the cursor color and shape, if not last set to these.
1548 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001549 static void
1550may_set_cursor_props(term_T *term)
1551{
1552#ifdef FEAT_GUI
1553 /* For the GUI the cursor properties are obtained with
1554 * term_get_cursor_shape(). */
1555 if (gui.in_use)
1556 return;
1557#endif
1558 if (in_terminal_loop == term)
1559 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001560 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001561 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001562 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001563 desired_cursor_color = (char_u *)"";
1564 desired_cursor_shape = term->tl_cursor_shape;
1565 desired_cursor_blink = term->tl_cursor_blink;
1566 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001567 }
1568}
1569
Bram Moolenaard317b382018-02-08 22:33:31 +01001570/*
1571 * Reset the desired cursor properties and restore them when needed.
1572 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001573 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001574prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001575{
1576#ifdef FEAT_GUI
1577 if (gui.in_use)
1578 return;
1579#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001580 desired_cursor_color = (char_u *)"";
1581 desired_cursor_shape = -1;
1582 desired_cursor_blink = -1;
1583 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584}
1585
1586/*
1587 * Returns TRUE if the current window contains a terminal and we are sending
1588 * keys to the job.
1589 */
1590 int
1591term_use_loop(void)
1592{
1593 term_T *term = curbuf->b_term;
1594
1595 return term != NULL
1596 && !term->tl_normal_mode
1597 && term->tl_vterm != NULL
1598 && term_job_running(term);
1599}
1600
1601/*
1602 * Wait for input and send it to the job.
1603 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1604 * when there is no more typahead.
1605 * Return when the start of a CTRL-W command is typed or anything else that
1606 * should be handled as a Normal mode command.
1607 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1608 * the terminal was closed.
1609 */
1610 int
1611terminal_loop(int blocking)
1612{
1613 int c;
1614 int termkey = 0;
1615 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001616#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001617 int tty_fd = curbuf->b_term->tl_job->jv_channel
1618 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001619#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001620 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001621
1622 /* Remember the terminal we are sending keys to. However, the terminal
1623 * might be closed while waiting for a character, e.g. typing "exit" in a
1624 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1625 * stored reference. */
1626 in_terminal_loop = curbuf->b_term;
1627
1628 if (*curwin->w_p_tk != NUL)
1629 termkey = string_to_key(curwin->w_p_tk, TRUE);
1630 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1631 may_set_cursor_props(curbuf->b_term);
1632
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001633 while (blocking || vpeekc() != NUL)
1634 {
1635 /* TODO: skip screen update when handling a sequence of keys. */
1636 /* Repeat redrawing in case a message is received while redrawing. */
1637 while (must_redraw != 0)
1638 if (update_screen(0) == FAIL)
1639 break;
1640 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001641 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001642
1643 c = term_vgetc();
1644 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001645 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001646 /* Job finished while waiting for a character. Push back the
1647 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001648 if (c != K_IGNORE)
1649 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001650 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001651 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001652 if (c == K_IGNORE)
1653 continue;
1654
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001655#ifdef UNIX
1656 /*
1657 * The shell or another program may change the tty settings. Getting
1658 * them for every typed character is a bit of overhead, but it's needed
1659 * for the first character typed, e.g. when Vim starts in a shell.
1660 */
1661 if (isatty(tty_fd))
1662 {
1663 ttyinfo_T info;
1664
1665 /* Get the current backspace character of the pty. */
1666 if (get_tty_info(tty_fd, &info) == OK)
1667 term_backspace_char = info.backspace;
1668 }
1669#endif
1670
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001671#ifdef WIN3264
1672 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1673 * Use CTRL-BREAK to kill the job. */
1674 if (ctrl_break_was_pressed)
1675 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1676#endif
1677 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1678 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1679 {
1680 int prev_c = c;
1681
1682#ifdef FEAT_CMDL_INFO
1683 if (add_to_showcmd(c))
1684 out_flush();
1685#endif
1686 c = term_vgetc();
1687#ifdef FEAT_CMDL_INFO
1688 clear_showcmd();
1689#endif
1690 if (!term_use_loop())
1691 /* job finished while waiting for a character */
1692 break;
1693
1694 if (prev_c == Ctrl_BSL)
1695 {
1696 if (c == Ctrl_N)
1697 {
1698 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1699 term_enter_normal_mode();
1700 ret = FAIL;
1701 goto theend;
1702 }
1703 /* Send both keys to the terminal. */
1704 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1705 }
1706 else if (c == Ctrl_C)
1707 {
1708 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1709 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1710 }
1711 else if (termkey == 0 && c == '.')
1712 {
1713 /* "CTRL-W .": send CTRL-W to the job */
1714 c = Ctrl_W;
1715 }
1716 else if (c == 'N')
1717 {
1718 /* CTRL-W N : go to Terminal-Normal mode. */
1719 term_enter_normal_mode();
1720 ret = FAIL;
1721 goto theend;
1722 }
1723 else if (c == '"')
1724 {
1725 term_paste_register(prev_c);
1726 continue;
1727 }
1728 else if (termkey == 0 || c != termkey)
1729 {
1730 stuffcharReadbuff(Ctrl_W);
1731 stuffcharReadbuff(c);
1732 ret = OK;
1733 goto theend;
1734 }
1735 }
1736# ifdef WIN3264
1737 if (!enc_utf8 && has_mbyte && c >= 0x80)
1738 {
1739 WCHAR wc;
1740 char_u mb[3];
1741
1742 mb[0] = (unsigned)c >> 8;
1743 mb[1] = c;
1744 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1745 c = wc;
1746 }
1747# endif
1748 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1749 {
Bram Moolenaard317b382018-02-08 22:33:31 +01001750 if (c == K_MOUSEMOVE)
1751 /* We are sure to come back here, don't reset the cursor color
1752 * and shape to avoid flickering. */
1753 restore_cursor = FALSE;
1754
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001755 ret = OK;
1756 goto theend;
1757 }
1758 }
1759 ret = FAIL;
1760
1761theend:
1762 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01001763 if (restore_cursor)
1764 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001765 return ret;
1766}
1767
1768/*
1769 * Called when a job has finished.
1770 * This updates the title and status, but does not close the vterm, because
1771 * there might still be pending output in the channel.
1772 */
1773 void
1774term_job_ended(job_T *job)
1775{
1776 term_T *term;
1777 int did_one = FALSE;
1778
1779 for (term = first_term; term != NULL; term = term->tl_next)
1780 if (term->tl_job == job)
1781 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01001782 VIM_CLEAR(term->tl_title);
1783 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001784 redraw_buf_and_status_later(term->tl_buffer, VALID);
1785 did_one = TRUE;
1786 }
1787 if (did_one)
1788 redraw_statuslines();
1789 if (curbuf->b_term != NULL)
1790 {
1791 if (curbuf->b_term->tl_job == job)
1792 maketitle();
1793 update_cursor(curbuf->b_term, TRUE);
1794 }
1795}
1796
1797 static void
1798may_toggle_cursor(term_T *term)
1799{
1800 if (in_terminal_loop == term)
1801 {
1802 if (term->tl_cursor_visible)
1803 cursor_on();
1804 else
1805 cursor_off();
1806 }
1807}
1808
1809/*
1810 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001811 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 */
1813 static int
1814color2index(VTermColor *color, int fg, int *boldp)
1815{
1816 int red = color->red;
1817 int blue = color->blue;
1818 int green = color->green;
1819
Bram Moolenaar46359e12017-11-29 22:33:38 +01001820 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001821 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001822 /* First 16 colors and default: use the ANSI index, because these
1823 * colors can be redefined. */
1824 if (t_colors >= 16)
1825 return color->ansi_index;
1826 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001827 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001828 case 0: return 0;
1829 case 1: return lookup_color( 0, fg, boldp) + 1;
1830 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1831 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1832 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1833 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1834 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1835 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1836 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1837 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1838 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1839 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1840 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1841 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1842 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1843 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1844 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001845 }
1846 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001847
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001848 if (t_colors >= 256)
1849 {
1850 if (red == blue && red == green)
1851 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001852 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001853 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001854 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1855 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1856 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001857 int i;
1858
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001859 if (red < 5)
1860 return 17; /* 00/00/00 */
1861 if (red > 245) /* ff/ff/ff */
1862 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001863 for (i = 0; i < 23; ++i)
1864 if (red < cutoff[i])
1865 return i + 233;
1866 return 256;
1867 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001868 {
1869 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1870 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001871
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001872 /* 216-color cube */
1873 for (ri = 0; ri < 5; ++ri)
1874 if (red < cutoff[ri])
1875 break;
1876 for (gi = 0; gi < 5; ++gi)
1877 if (green < cutoff[gi])
1878 break;
1879 for (bi = 0; bi < 5; ++bi)
1880 if (blue < cutoff[bi])
1881 break;
1882 return 17 + ri * 36 + gi * 6 + bi;
1883 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001884 }
1885 return 0;
1886}
1887
1888/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01001889 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001890 */
1891 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01001892vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001893{
1894 int attr = 0;
1895
1896 if (cellattrs.bold)
1897 attr |= HL_BOLD;
1898 if (cellattrs.underline)
1899 attr |= HL_UNDERLINE;
1900 if (cellattrs.italic)
1901 attr |= HL_ITALIC;
1902 if (cellattrs.strike)
1903 attr |= HL_STRIKETHROUGH;
1904 if (cellattrs.reverse)
1905 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001906 return attr;
1907}
1908
1909/*
1910 * Store Vterm attributes in "cell" from highlight flags.
1911 */
1912 static void
1913hl2vtermAttr(int attr, cellattr_T *cell)
1914{
1915 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
1916 if (attr & HL_BOLD)
1917 cell->attrs.bold = 1;
1918 if (attr & HL_UNDERLINE)
1919 cell->attrs.underline = 1;
1920 if (attr & HL_ITALIC)
1921 cell->attrs.italic = 1;
1922 if (attr & HL_STRIKETHROUGH)
1923 cell->attrs.strike = 1;
1924 if (attr & HL_INVERSE)
1925 cell->attrs.reverse = 1;
1926}
1927
1928/*
1929 * Convert the attributes of a vterm cell into an attribute index.
1930 */
1931 static int
1932cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1933{
1934 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001935
1936#ifdef FEAT_GUI
1937 if (gui.in_use)
1938 {
1939 guicolor_T fg, bg;
1940
1941 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1942 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1943 return get_gui_attr_idx(attr, fg, bg);
1944 }
1945 else
1946#endif
1947#ifdef FEAT_TERMGUICOLORS
1948 if (p_tgc)
1949 {
1950 guicolor_T fg, bg;
1951
1952 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1953 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1954
1955 return get_tgc_attr_idx(attr, fg, bg);
1956 }
1957 else
1958#endif
1959 {
1960 int bold = MAYBE;
1961 int fg = color2index(&cellfg, TRUE, &bold);
1962 int bg = color2index(&cellbg, FALSE, &bold);
1963
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001964 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001965 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001966 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001967 if (fg == 0 && term_default_cterm_fg >= 0)
1968 fg = term_default_cterm_fg + 1;
1969 if (bg == 0 && term_default_cterm_bg >= 0)
1970 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001971 }
1972
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001973 /* with 8 colors set the bold attribute to get a bright foreground */
1974 if (bold == TRUE)
1975 attr |= HL_BOLD;
1976 return get_cterm_attr_idx(attr, fg, bg);
1977 }
1978 return 0;
1979}
1980
1981 static int
1982handle_damage(VTermRect rect, void *user)
1983{
1984 term_T *term = (term_T *)user;
1985
1986 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1987 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1988 redraw_buf_later(term->tl_buffer, NOT_VALID);
1989 return 1;
1990}
1991
1992 static int
1993handle_moverect(VTermRect dest, VTermRect src, void *user)
1994{
1995 term_T *term = (term_T *)user;
1996
1997 /* Scrolling up is done much more efficiently by deleting lines instead of
1998 * redrawing the text. */
1999 if (dest.start_col == src.start_col
2000 && dest.end_col == src.end_col
2001 && dest.start_row < src.start_row)
2002 {
2003 win_T *wp;
2004 VTermColor fg, bg;
2005 VTermScreenCellAttrs attr;
2006 int clear_attr;
2007
2008 /* Set the color to clear lines with. */
2009 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2010 &fg, &bg);
2011 vim_memset(&attr, 0, sizeof(attr));
2012 clear_attr = cell2attr(attr, fg, bg);
2013
2014 FOR_ALL_WINDOWS(wp)
2015 {
2016 if (wp->w_buffer == term->tl_buffer)
2017 win_del_lines(wp, dest.start_row,
2018 src.start_row - dest.start_row, FALSE, FALSE,
2019 clear_attr);
2020 }
2021 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002022
2023 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2024 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2025
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002026 redraw_buf_later(term->tl_buffer, NOT_VALID);
2027 return 1;
2028}
2029
2030 static int
2031handle_movecursor(
2032 VTermPos pos,
2033 VTermPos oldpos UNUSED,
2034 int visible,
2035 void *user)
2036{
2037 term_T *term = (term_T *)user;
2038 win_T *wp;
2039
2040 term->tl_cursor_pos = pos;
2041 term->tl_cursor_visible = visible;
2042
2043 FOR_ALL_WINDOWS(wp)
2044 {
2045 if (wp->w_buffer == term->tl_buffer)
2046 position_cursor(wp, &pos);
2047 }
2048 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2049 {
2050 may_toggle_cursor(term);
2051 update_cursor(term, term->tl_cursor_visible);
2052 }
2053
2054 return 1;
2055}
2056
2057 static int
2058handle_settermprop(
2059 VTermProp prop,
2060 VTermValue *value,
2061 void *user)
2062{
2063 term_T *term = (term_T *)user;
2064
2065 switch (prop)
2066 {
2067 case VTERM_PROP_TITLE:
2068 vim_free(term->tl_title);
2069 /* a blank title isn't useful, make it empty, so that "running" is
2070 * displayed */
2071 if (*skipwhite((char_u *)value->string) == NUL)
2072 term->tl_title = NULL;
2073#ifdef WIN3264
2074 else if (!enc_utf8 && enc_codepage > 0)
2075 {
2076 WCHAR *ret = NULL;
2077 int length = 0;
2078
2079 MultiByteToWideChar_alloc(CP_UTF8, 0,
2080 (char*)value->string, (int)STRLEN(value->string),
2081 &ret, &length);
2082 if (ret != NULL)
2083 {
2084 WideCharToMultiByte_alloc(enc_codepage, 0,
2085 ret, length, (char**)&term->tl_title,
2086 &length, 0, 0);
2087 vim_free(ret);
2088 }
2089 }
2090#endif
2091 else
2092 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002093 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002094 if (term == curbuf->b_term)
2095 maketitle();
2096 break;
2097
2098 case VTERM_PROP_CURSORVISIBLE:
2099 term->tl_cursor_visible = value->boolean;
2100 may_toggle_cursor(term);
2101 out_flush();
2102 break;
2103
2104 case VTERM_PROP_CURSORBLINK:
2105 term->tl_cursor_blink = value->boolean;
2106 may_set_cursor_props(term);
2107 break;
2108
2109 case VTERM_PROP_CURSORSHAPE:
2110 term->tl_cursor_shape = value->number;
2111 may_set_cursor_props(term);
2112 break;
2113
2114 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002115 if (desired_cursor_color == term->tl_cursor_color)
2116 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002117 vim_free(term->tl_cursor_color);
2118 if (*value->string == NUL)
2119 term->tl_cursor_color = NULL;
2120 else
2121 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2122 may_set_cursor_props(term);
2123 break;
2124
2125 case VTERM_PROP_ALTSCREEN:
2126 /* TODO: do anything else? */
2127 term->tl_using_altscreen = value->boolean;
2128 break;
2129
2130 default:
2131 break;
2132 }
2133 /* Always return 1, otherwise vterm doesn't store the value internally. */
2134 return 1;
2135}
2136
2137/*
2138 * The job running in the terminal resized the terminal.
2139 */
2140 static int
2141handle_resize(int rows, int cols, void *user)
2142{
2143 term_T *term = (term_T *)user;
2144 win_T *wp;
2145
2146 term->tl_rows = rows;
2147 term->tl_cols = cols;
2148 if (term->tl_vterm_size_changed)
2149 /* Size was set by vterm_set_size(), don't set the window size. */
2150 term->tl_vterm_size_changed = FALSE;
2151 else
2152 {
2153 FOR_ALL_WINDOWS(wp)
2154 {
2155 if (wp->w_buffer == term->tl_buffer)
2156 {
2157 win_setheight_win(rows, wp);
2158 win_setwidth_win(cols, wp);
2159 }
2160 }
2161 redraw_buf_later(term->tl_buffer, NOT_VALID);
2162 }
2163 return 1;
2164}
2165
2166/*
2167 * Handle a line that is pushed off the top of the screen.
2168 */
2169 static int
2170handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2171{
2172 term_T *term = (term_T *)user;
2173
2174 /* TODO: Limit the number of lines that are stored. */
2175 if (ga_grow(&term->tl_scrollback, 1) == OK)
2176 {
2177 cellattr_T *p = NULL;
2178 int len = 0;
2179 int i;
2180 int c;
2181 int col;
2182 sb_line_T *line;
2183 garray_T ga;
2184 cellattr_T fill_attr = term->tl_default_color;
2185
2186 /* do not store empty cells at the end */
2187 for (i = 0; i < cols; ++i)
2188 if (cells[i].chars[0] != 0)
2189 len = i + 1;
2190 else
2191 cell2cellattr(&cells[i], &fill_attr);
2192
2193 ga_init2(&ga, 1, 100);
2194 if (len > 0)
2195 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2196 if (p != NULL)
2197 {
2198 for (col = 0; col < len; col += cells[col].width)
2199 {
2200 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2201 {
2202 ga.ga_len = 0;
2203 break;
2204 }
2205 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2206 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2207 (char_u *)ga.ga_data + ga.ga_len);
2208 cell2cellattr(&cells[col], &p[col]);
2209 }
2210 }
2211 if (ga_grow(&ga, 1) == FAIL)
2212 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2213 else
2214 {
2215 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2216 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2217 }
2218 ga_clear(&ga);
2219
2220 line = (sb_line_T *)term->tl_scrollback.ga_data
2221 + term->tl_scrollback.ga_len;
2222 line->sb_cols = len;
2223 line->sb_cells = p;
2224 line->sb_fill_attr = fill_attr;
2225 ++term->tl_scrollback.ga_len;
2226 ++term->tl_scrollback_scrolled;
2227 }
2228 return 0; /* ignored */
2229}
2230
2231static VTermScreenCallbacks screen_callbacks = {
2232 handle_damage, /* damage */
2233 handle_moverect, /* moverect */
2234 handle_movecursor, /* movecursor */
2235 handle_settermprop, /* settermprop */
2236 NULL, /* bell */
2237 handle_resize, /* resize */
2238 handle_pushline, /* sb_pushline */
2239 NULL /* sb_popline */
2240};
2241
2242/*
2243 * Called when a channel has been closed.
2244 * If this was a channel for a terminal window then finish it up.
2245 */
2246 void
2247term_channel_closed(channel_T *ch)
2248{
2249 term_T *term;
2250 int did_one = FALSE;
2251
2252 for (term = first_term; term != NULL; term = term->tl_next)
2253 if (term->tl_job == ch->ch_job)
2254 {
2255 term->tl_channel_closed = TRUE;
2256 did_one = TRUE;
2257
Bram Moolenaard23a8232018-02-10 18:45:26 +01002258 VIM_CLEAR(term->tl_title);
2259 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260
2261 /* Unless in Terminal-Normal mode: clear the vterm. */
2262 if (!term->tl_normal_mode)
2263 {
2264 int fnum = term->tl_buffer->b_fnum;
2265
2266 cleanup_vterm(term);
2267
2268 if (term->tl_finish == 'c')
2269 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002270 aco_save_T aco;
2271
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002272 /* ++close or term_finish == "close" */
2273 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002274 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002275 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002276 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002277 break;
2278 }
2279 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2280 {
2281 char buf[50];
2282
2283 /* TODO: use term_opencmd */
2284 ch_log(NULL, "terminal job finished, opening window");
2285 vim_snprintf(buf, sizeof(buf),
2286 term->tl_opencmd == NULL
2287 ? "botright sbuf %d"
2288 : (char *)term->tl_opencmd, fnum);
2289 do_cmdline_cmd((char_u *)buf);
2290 }
2291 else
2292 ch_log(NULL, "terminal job finished");
2293 }
2294
2295 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2296 }
2297 if (did_one)
2298 {
2299 redraw_statuslines();
2300
2301 /* Need to break out of vgetc(). */
2302 ins_char_typebuf(K_IGNORE);
2303 typebuf_was_filled = TRUE;
2304
2305 term = curbuf->b_term;
2306 if (term != NULL)
2307 {
2308 if (term->tl_job == ch->ch_job)
2309 maketitle();
2310 update_cursor(term, term->tl_cursor_visible);
2311 }
2312 }
2313}
2314
2315/*
2316 * Called to update a window that contains an active terminal.
2317 * Returns FAIL when there is no terminal running in this window or in
2318 * Terminal-Normal mode.
2319 */
2320 int
2321term_update_window(win_T *wp)
2322{
2323 term_T *term = wp->w_buffer->b_term;
2324 VTerm *vterm;
2325 VTermScreen *screen;
2326 VTermState *state;
2327 VTermPos pos;
2328
2329 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2330 return FAIL;
2331
2332 vterm = term->tl_vterm;
2333 screen = vterm_obtain_screen(vterm);
2334 state = vterm_obtain_state(vterm);
2335
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002336 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002337 {
2338 term->tl_dirty_row_start = 0;
2339 term->tl_dirty_row_end = MAX_ROW;
2340 }
2341
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002342 /*
2343 * If the window was resized a redraw will be triggered and we get here.
2344 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2345 */
2346 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2347 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2348 {
2349 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2350 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2351 win_T *twp;
2352
2353 FOR_ALL_WINDOWS(twp)
2354 {
2355 /* When more than one window shows the same terminal, use the
2356 * smallest size. */
2357 if (twp->w_buffer == term->tl_buffer)
2358 {
2359 if (!term->tl_rows_fixed && rows > twp->w_height)
2360 rows = twp->w_height;
2361 if (!term->tl_cols_fixed && cols > twp->w_width)
2362 cols = twp->w_width;
2363 }
2364 }
2365
2366 term->tl_vterm_size_changed = TRUE;
2367 vterm_set_size(vterm, rows, cols);
2368 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2369 rows);
2370 term_report_winsize(term, rows, cols);
2371 }
2372
2373 /* The cursor may have been moved when resizing. */
2374 vterm_state_get_cursorpos(state, &pos);
2375 position_cursor(wp, &pos);
2376
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002377 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2378 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002379 {
2380 int off = screen_get_current_line_off();
2381 int max_col = MIN(wp->w_width, term->tl_cols);
2382
2383 if (pos.row < term->tl_rows)
2384 {
2385 for (pos.col = 0; pos.col < max_col; )
2386 {
2387 VTermScreenCell cell;
2388 int c;
2389
2390 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2391 vim_memset(&cell, 0, sizeof(cell));
2392
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002393 c = cell.chars[0];
2394 if (c == NUL)
2395 {
2396 ScreenLines[off] = ' ';
2397 if (enc_utf8)
2398 ScreenLinesUC[off] = NUL;
2399 }
2400 else
2401 {
2402 if (enc_utf8)
2403 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002404 int i;
2405
2406 /* composing chars */
2407 for (i = 0; i < Screen_mco
2408 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2409 {
2410 ScreenLinesC[i][off] = cell.chars[i + 1];
2411 if (cell.chars[i + 1] == 0)
2412 break;
2413 }
2414 if (c >= 0x80 || (Screen_mco > 0
2415 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002416 {
2417 ScreenLines[off] = ' ';
2418 ScreenLinesUC[off] = c;
2419 }
2420 else
2421 {
2422 ScreenLines[off] = c;
2423 ScreenLinesUC[off] = NUL;
2424 }
2425 }
2426#ifdef WIN3264
2427 else if (has_mbyte && c >= 0x80)
2428 {
2429 char_u mb[MB_MAXBYTES+1];
2430 WCHAR wc = c;
2431
2432 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2433 (char*)mb, 2, 0, 0) > 1)
2434 {
2435 ScreenLines[off] = mb[0];
2436 ScreenLines[off + 1] = mb[1];
2437 cell.width = mb_ptr2cells(mb);
2438 }
2439 else
2440 ScreenLines[off] = c;
2441 }
2442#endif
2443 else
2444 ScreenLines[off] = c;
2445 }
2446 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2447
2448 ++pos.col;
2449 ++off;
2450 if (cell.width == 2)
2451 {
2452 if (enc_utf8)
2453 ScreenLinesUC[off] = NUL;
2454
2455 /* don't set the second byte to NUL for a DBCS encoding, it
2456 * has been set above */
2457 if (enc_utf8 || !has_mbyte)
2458 ScreenLines[off] = NUL;
2459
2460 ++pos.col;
2461 ++off;
2462 }
2463 }
2464 }
2465 else
2466 pos.col = 0;
2467
Bram Moolenaar181ca992018-02-13 21:19:21 +01002468 screen_line(wp->w_winrow + pos.row + winbar_height(wp),
2469 wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002471 term->tl_dirty_row_start = MAX_ROW;
2472 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002473
2474 return OK;
2475}
2476
2477/*
2478 * Return TRUE if "wp" is a terminal window where the job has finished.
2479 */
2480 int
2481term_is_finished(buf_T *buf)
2482{
2483 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2484}
2485
2486/*
2487 * Return TRUE if "wp" is a terminal window where the job has finished or we
2488 * are in Terminal-Normal mode, thus we show the buffer contents.
2489 */
2490 int
2491term_show_buffer(buf_T *buf)
2492{
2493 term_T *term = buf->b_term;
2494
2495 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2496}
2497
2498/*
2499 * The current buffer is going to be changed. If there is terminal
2500 * highlighting remove it now.
2501 */
2502 void
2503term_change_in_curbuf(void)
2504{
2505 term_T *term = curbuf->b_term;
2506
2507 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2508 {
2509 free_scrollback(term);
2510 redraw_buf_later(term->tl_buffer, NOT_VALID);
2511
2512 /* The buffer is now like a normal buffer, it cannot be easily
2513 * abandoned when changed. */
2514 set_string_option_direct((char_u *)"buftype", -1,
2515 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2516 }
2517}
2518
2519/*
2520 * Get the screen attribute for a position in the buffer.
2521 * Use a negative "col" to get the filler background color.
2522 */
2523 int
2524term_get_attr(buf_T *buf, linenr_T lnum, int col)
2525{
2526 term_T *term = buf->b_term;
2527 sb_line_T *line;
2528 cellattr_T *cellattr;
2529
2530 if (lnum > term->tl_scrollback.ga_len)
2531 cellattr = &term->tl_default_color;
2532 else
2533 {
2534 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2535 if (col < 0 || col >= line->sb_cols)
2536 cellattr = &line->sb_fill_attr;
2537 else
2538 cellattr = line->sb_cells + col;
2539 }
2540 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2541}
2542
2543static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002544 { 0, 0, 0, 1}, /* black */
2545 {224, 0, 0, 2}, /* dark red */
2546 { 0, 224, 0, 3}, /* dark green */
2547 {224, 224, 0, 4}, /* dark yellow / brown */
2548 { 0, 0, 224, 5}, /* dark blue */
2549 {224, 0, 224, 6}, /* dark magenta */
2550 { 0, 224, 224, 7}, /* dark cyan */
2551 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002552
Bram Moolenaar46359e12017-11-29 22:33:38 +01002553 {128, 128, 128, 9}, /* dark grey */
2554 {255, 64, 64, 10}, /* light red */
2555 { 64, 255, 64, 11}, /* light green */
2556 {255, 255, 64, 12}, /* yellow */
2557 { 64, 64, 255, 13}, /* light blue */
2558 {255, 64, 255, 14}, /* light magenta */
2559 { 64, 255, 255, 15}, /* light cyan */
2560 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002561};
2562
2563static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002564 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002565};
2566
2567static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002568 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2569 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002570};
2571
2572/*
2573 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002574 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002575 */
2576 static void
2577cterm_color2rgb(int nr, VTermColor *rgb)
2578{
2579 int idx;
2580
2581 if (nr < 16)
2582 {
2583 *rgb = ansi_table[nr];
2584 }
2585 else if (nr < 232)
2586 {
2587 /* 216 color cube */
2588 idx = nr - 16;
2589 rgb->blue = cube_value[idx % 6];
2590 rgb->green = cube_value[idx / 6 % 6];
2591 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002592 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 }
2594 else if (nr < 256)
2595 {
2596 /* 24 grey scale ramp */
2597 idx = nr - 232;
2598 rgb->blue = grey_ramp[idx];
2599 rgb->green = grey_ramp[idx];
2600 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002601 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002602 }
2603}
2604
2605/*
2606 * Create a new vterm and initialize it.
2607 */
2608 static void
2609create_vterm(term_T *term, int rows, int cols)
2610{
2611 VTerm *vterm;
2612 VTermScreen *screen;
2613 VTermValue value;
2614 VTermColor *fg, *bg;
2615 int fgval, bgval;
2616 int id;
2617
2618 vterm = vterm_new(rows, cols);
2619 term->tl_vterm = vterm;
2620 screen = vterm_obtain_screen(vterm);
2621 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2622 /* TODO: depends on 'encoding'. */
2623 vterm_set_utf8(vterm, 1);
2624
2625 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2626 term->tl_default_color.width = 1;
2627 fg = &term->tl_default_color.fg;
2628 bg = &term->tl_default_color.bg;
2629
2630 /* Vterm uses a default black background. Set it to white when
2631 * 'background' is "light". */
2632 if (*p_bg == 'l')
2633 {
2634 fgval = 0;
2635 bgval = 255;
2636 }
2637 else
2638 {
2639 fgval = 255;
2640 bgval = 0;
2641 }
2642 fg->red = fg->green = fg->blue = fgval;
2643 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002644 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002645
2646 /* The "Terminal" highlight group overrules the defaults. */
2647 id = syn_name2id((char_u *)"Terminal");
2648
Bram Moolenaar46359e12017-11-29 22:33:38 +01002649 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002650#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2651 if (0
2652# ifdef FEAT_GUI
2653 || gui.in_use
2654# endif
2655# ifdef FEAT_TERMGUICOLORS
2656 || p_tgc
2657# endif
2658 )
2659 {
2660 guicolor_T fg_rgb = INVALCOLOR;
2661 guicolor_T bg_rgb = INVALCOLOR;
2662
2663 if (id != 0)
2664 syn_id2colors(id, &fg_rgb, &bg_rgb);
2665
2666# ifdef FEAT_GUI
2667 if (gui.in_use)
2668 {
2669 if (fg_rgb == INVALCOLOR)
2670 fg_rgb = gui.norm_pixel;
2671 if (bg_rgb == INVALCOLOR)
2672 bg_rgb = gui.back_pixel;
2673 }
2674# ifdef FEAT_TERMGUICOLORS
2675 else
2676# endif
2677# endif
2678# ifdef FEAT_TERMGUICOLORS
2679 {
2680 if (fg_rgb == INVALCOLOR)
2681 fg_rgb = cterm_normal_fg_gui_color;
2682 if (bg_rgb == INVALCOLOR)
2683 bg_rgb = cterm_normal_bg_gui_color;
2684 }
2685# endif
2686 if (fg_rgb != INVALCOLOR)
2687 {
2688 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2689
2690 fg->red = (unsigned)(rgb >> 16);
2691 fg->green = (unsigned)(rgb >> 8) & 255;
2692 fg->blue = (unsigned)rgb & 255;
2693 }
2694 if (bg_rgb != INVALCOLOR)
2695 {
2696 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2697
2698 bg->red = (unsigned)(rgb >> 16);
2699 bg->green = (unsigned)(rgb >> 8) & 255;
2700 bg->blue = (unsigned)rgb & 255;
2701 }
2702 }
2703 else
2704#endif
2705 if (id != 0 && t_colors >= 16)
2706 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002707 if (term_default_cterm_fg >= 0)
2708 cterm_color2rgb(term_default_cterm_fg, fg);
2709 if (term_default_cterm_bg >= 0)
2710 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002711 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002712 else
2713 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002714#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002715 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002716#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002717
2718 /* In an MS-Windows console we know the normal colors. */
2719 if (cterm_normal_fg_color > 0)
2720 {
2721 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002722# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002723 tmp = fg->red;
2724 fg->red = fg->blue;
2725 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002726# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002727 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002728# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002729 else
2730 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002731# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002732
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002733 if (cterm_normal_bg_color > 0)
2734 {
2735 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002736# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002737 tmp = bg->red;
2738 bg->red = bg->blue;
2739 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002740# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002741 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002742# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002743 else
2744 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002745# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002746 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002747
2748 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2749
2750 /* Required to initialize most things. */
2751 vterm_screen_reset(screen, 1 /* hard */);
2752
2753 /* Allow using alternate screen. */
2754 vterm_screen_enable_altscreen(screen, 1);
2755
2756 /* For unix do not use a blinking cursor. In an xterm this causes the
2757 * cursor to blink if it's blinking in the xterm.
2758 * For Windows we respect the system wide setting. */
2759#ifdef WIN3264
2760 if (GetCaretBlinkTime() == INFINITE)
2761 value.boolean = 0;
2762 else
2763 value.boolean = 1;
2764#else
2765 value.boolean = 0;
2766#endif
2767 vterm_state_set_termprop(vterm_obtain_state(vterm),
2768 VTERM_PROP_CURSORBLINK, &value);
2769}
2770
2771/*
2772 * Return the text to show for the buffer name and status.
2773 */
2774 char_u *
2775term_get_status_text(term_T *term)
2776{
2777 if (term->tl_status_text == NULL)
2778 {
2779 char_u *txt;
2780 size_t len;
2781
2782 if (term->tl_normal_mode)
2783 {
2784 if (term_job_running(term))
2785 txt = (char_u *)_("Terminal");
2786 else
2787 txt = (char_u *)_("Terminal-finished");
2788 }
2789 else if (term->tl_title != NULL)
2790 txt = term->tl_title;
2791 else if (term_none_open(term))
2792 txt = (char_u *)_("active");
2793 else if (term_job_running(term))
2794 txt = (char_u *)_("running");
2795 else
2796 txt = (char_u *)_("finished");
2797 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2798 term->tl_status_text = alloc((int)len);
2799 if (term->tl_status_text != NULL)
2800 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2801 term->tl_buffer->b_fname, txt);
2802 }
2803 return term->tl_status_text;
2804}
2805
2806/*
2807 * Mark references in jobs of terminals.
2808 */
2809 int
2810set_ref_in_term(int copyID)
2811{
2812 int abort = FALSE;
2813 term_T *term;
2814 typval_T tv;
2815
2816 for (term = first_term; term != NULL; term = term->tl_next)
2817 if (term->tl_job != NULL)
2818 {
2819 tv.v_type = VAR_JOB;
2820 tv.vval.v_job = term->tl_job;
2821 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2822 }
2823 return abort;
2824}
2825
2826/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002827 * Cache "Terminal" highlight group colors.
2828 */
2829 void
2830set_terminal_default_colors(int cterm_fg, int cterm_bg)
2831{
2832 term_default_cterm_fg = cterm_fg - 1;
2833 term_default_cterm_bg = cterm_bg - 1;
2834}
2835
2836/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002837 * Get the buffer from the first argument in "argvars".
2838 * Returns NULL when the buffer is not for a terminal window.
2839 */
2840 static buf_T *
2841term_get_buf(typval_T *argvars)
2842{
2843 buf_T *buf;
2844
2845 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2846 ++emsg_off;
2847 buf = get_buf_tv(&argvars[0], FALSE);
2848 --emsg_off;
2849 if (buf == NULL || buf->b_term == NULL)
2850 return NULL;
2851 return buf;
2852}
2853
Bram Moolenaard96ff162018-02-18 22:13:29 +01002854 static int
2855same_color(VTermColor *a, VTermColor *b)
2856{
2857 return a->red == b->red
2858 && a->green == b->green
2859 && a->blue == b->blue
2860 && a->ansi_index == b->ansi_index;
2861}
2862
2863 static void
2864dump_term_color(FILE *fd, VTermColor *color)
2865{
2866 fprintf(fd, "%02x%02x%02x%d",
2867 (int)color->red, (int)color->green, (int)color->blue,
2868 (int)color->ansi_index);
2869}
2870
2871/*
2872 * "term_dumpwrite(buf, filename, max-height, max-width)" function
2873 *
2874 * Each screen cell in full is:
2875 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
2876 * {characters} is a space for an empty cell
2877 * For a double-width character "+" is changed to "*" and the next cell is
2878 * skipped.
2879 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
2880 * when "&" use the same as the previous cell.
2881 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
2882 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
2883 * {color-idx} is a number from 0 to 255
2884 *
2885 * Screen cell with same width, attributes and color as the previous one:
2886 * |{characters}
2887 *
2888 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
2889 *
2890 * Repeating the previous screen cell:
2891 * @{count}
2892 */
2893 void
2894f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
2895{
2896 buf_T *buf = term_get_buf(argvars);
2897 term_T *term;
2898 char_u *fname;
2899 int max_height = 99999;
2900 int max_width = 99999;
2901 stat_T st;
2902 FILE *fd;
2903 VTermPos pos;
2904 VTermScreen *screen;
2905 VTermScreenCell prev_cell;
2906
2907 if (check_restricted() || check_secure())
2908 return;
2909 if (buf == NULL)
2910 return;
2911 term = buf->b_term;
2912
2913 fname = get_tv_string_chk(&argvars[1]);
2914 if (fname == NULL)
2915 return;
2916 if (mch_stat((char *)fname, &st) >= 0)
2917 {
2918 EMSG2(_("E953: File exists: %s"), fname);
2919 return;
2920 }
2921
2922 if (argvars[2].v_type != VAR_UNKNOWN)
2923 {
2924 max_height = get_tv_number(&argvars[2]);
2925 if (argvars[3].v_type != VAR_UNKNOWN)
2926 max_width = get_tv_number(&argvars[3]);
2927 }
2928
2929 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
2930 {
2931 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
2932 return;
2933 }
2934
2935 vim_memset(&prev_cell, 0, sizeof(prev_cell));
2936
2937 screen = vterm_obtain_screen(term->tl_vterm);
2938 for (pos.row = 0; pos.row < max_height && pos.row < term->tl_rows;
2939 ++pos.row)
2940 {
2941 int repeat = 0;
2942
2943 for (pos.col = 0; pos.col < max_width && pos.col < term->tl_cols;
2944 ++pos.col)
2945 {
2946 VTermScreenCell cell;
2947 int same_attr;
2948 int same_chars = TRUE;
2949 int i;
2950
2951 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2952 vim_memset(&cell, 0, sizeof(cell));
2953
2954 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
2955 {
2956 if (cell.chars[i] != prev_cell.chars[i])
2957 same_chars = FALSE;
2958 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
2959 break;
2960 }
2961 same_attr = vtermAttr2hl(cell.attrs)
2962 == vtermAttr2hl(prev_cell.attrs)
2963 && same_color(&cell.fg, &prev_cell.fg)
2964 && same_color(&cell.bg, &prev_cell.bg);
2965 if (same_chars && cell.width == prev_cell.width && same_attr)
2966 {
2967 ++repeat;
2968 }
2969 else
2970 {
2971 if (repeat > 0)
2972 {
2973 fprintf(fd, "@%d", repeat);
2974 repeat = 0;
2975 }
2976 fputs("|", fd);
2977
2978 if (cell.chars[0] == NUL)
2979 fputs(" ", fd);
2980 else
2981 {
2982 char_u charbuf[10];
2983 int len;
2984
2985 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
2986 && cell.chars[i] != NUL; ++i)
2987 {
2988 len = utf_char2bytes(cell.chars[0], charbuf);
2989 fwrite(charbuf, len, 1, fd);
2990 }
2991 }
2992
2993 /* When only the characters differ we don't write anything, the
2994 * following "|", "@" or NL will indicate using the same
2995 * attributes. */
2996 if (cell.width != prev_cell.width || !same_attr)
2997 {
2998 if (cell.width == 2)
2999 {
3000 fputs("*", fd);
3001 ++pos.col;
3002 }
3003 else
3004 fputs("+", fd);
3005
3006 if (same_attr)
3007 {
3008 fputs("&", fd);
3009 }
3010 else
3011 {
3012 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3013 if (same_color(&cell.fg, &prev_cell.fg))
3014 fputs("&", fd);
3015 else
3016 {
3017 fputs("#", fd);
3018 dump_term_color(fd, &cell.fg);
3019 }
3020 if (same_color(&cell.bg, &prev_cell.bg))
3021 fputs("&", fd);
3022 else
3023 {
3024 fputs("#", fd);
3025 dump_term_color(fd, &cell.bg);
3026 }
3027 }
3028 }
3029
3030 prev_cell = cell;
3031 }
3032 }
3033 if (repeat > 0)
3034 fprintf(fd, "@%d", repeat);
3035 fputs("\n", fd);
3036 }
3037
3038 fclose(fd);
3039}
3040
3041/*
3042 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3043 */
3044 static void
3045dump_is_corrupt(garray_T *gap)
3046{
3047 ga_concat(gap, (char_u *)"CORRUPT");
3048}
3049
3050 static void
3051append_cell(garray_T *gap, cellattr_T *cell)
3052{
3053 if (ga_grow(gap, 1) == OK)
3054 {
3055 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3056 ++gap->ga_len;
3057 }
3058}
3059
3060/*
3061 * Read the dump file from "fd" and append lines to the current buffer.
3062 * Return the cell width of the longest line.
3063 */
3064 static int
3065read_dump_file(FILE *fd)
3066{
3067 int c;
3068 garray_T ga_text;
3069 garray_T ga_cell;
3070 char_u *prev_char = NULL;
3071 int attr = 0;
3072 cellattr_T cell;
3073 term_T *term = curbuf->b_term;
3074 int max_cells = 0;
3075
3076 ga_init2(&ga_text, 1, 90);
3077 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3078 vim_memset(&cell, 0, sizeof(cell));
3079
3080 c = fgetc(fd);
3081 for (;;)
3082 {
3083 if (c == EOF)
3084 break;
3085 if (c == '\n')
3086 {
3087 /* End of a line: append it to the buffer. */
3088 if (ga_text.ga_data == NULL)
3089 dump_is_corrupt(&ga_text);
3090 if (ga_grow(&term->tl_scrollback, 1) == OK)
3091 {
3092 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3093 + term->tl_scrollback.ga_len;
3094
3095 if (max_cells < ga_cell.ga_len)
3096 max_cells = ga_cell.ga_len;
3097 line->sb_cols = ga_cell.ga_len;
3098 line->sb_cells = ga_cell.ga_data;
3099 line->sb_fill_attr = term->tl_default_color;
3100 ++term->tl_scrollback.ga_len;
3101 ga_init(&ga_cell);
3102
3103 ga_append(&ga_text, NUL);
3104 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3105 ga_text.ga_len, FALSE);
3106 }
3107 else
3108 ga_clear(&ga_cell);
3109 ga_text.ga_len = 0;
3110
3111 c = fgetc(fd);
3112 }
3113 else if (c == '|')
3114 {
3115 int prev_len = ga_text.ga_len;
3116
3117 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3118 c = fgetc(fd);
3119 if (c != EOF)
3120 ga_append(&ga_text, c);
3121 for (;;)
3122 {
3123 c = fgetc(fd);
3124 if (c == '+' || c == '*' || c == '|' || c == '@'
3125 || c == EOF || c == '\n')
3126 break;
3127 ga_append(&ga_text, c);
3128 }
3129
3130 /* save the character for repeating it */
3131 vim_free(prev_char);
3132 if (ga_text.ga_data != NULL)
3133 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3134 ga_text.ga_len - prev_len);
3135
3136 if (c == '@' || c == '|' || c == '\n')
3137 {
3138 /* use all attributes from previous cell */
3139 }
3140 else if (c == '+' || c == '*')
3141 {
3142 int is_bg;
3143
3144 cell.width = c == '+' ? 1 : 2;
3145
3146 c = fgetc(fd);
3147 if (c == '&')
3148 {
3149 /* use same attr as previous cell */
3150 c = fgetc(fd);
3151 }
3152 else if (isdigit(c))
3153 {
3154 /* get the decimal attribute */
3155 attr = 0;
3156 while (isdigit(c))
3157 {
3158 attr = attr * 10 + (c - '0');
3159 c = fgetc(fd);
3160 }
3161 hl2vtermAttr(attr, &cell);
3162 }
3163 else
3164 dump_is_corrupt(&ga_text);
3165
3166 /* is_bg == 0: fg, is_bg == 1: bg */
3167 for (is_bg = 0; is_bg <= 1; ++is_bg)
3168 {
3169 if (c == '&')
3170 {
3171 /* use same color as previous cell */
3172 c = fgetc(fd);
3173 }
3174 else if (c == '#')
3175 {
3176 int red, green, blue, index = 0;
3177
3178 c = fgetc(fd);
3179 red = hex2nr(c);
3180 c = fgetc(fd);
3181 red = (red << 4) + hex2nr(c);
3182 c = fgetc(fd);
3183 green = hex2nr(c);
3184 c = fgetc(fd);
3185 green = (green << 4) + hex2nr(c);
3186 c = fgetc(fd);
3187 blue = hex2nr(c);
3188 c = fgetc(fd);
3189 blue = (blue << 4) + hex2nr(c);
3190 c = fgetc(fd);
3191 if (!isdigit(c))
3192 dump_is_corrupt(&ga_text);
3193 while (isdigit(c))
3194 {
3195 index = index * 10 + (c - '0');
3196 c = fgetc(fd);
3197 }
3198
3199 if (is_bg)
3200 {
3201 cell.bg.red = red;
3202 cell.bg.green = green;
3203 cell.bg.blue = blue;
3204 cell.bg.ansi_index = index;
3205 }
3206 else
3207 {
3208 cell.fg.red = red;
3209 cell.fg.green = green;
3210 cell.fg.blue = blue;
3211 cell.fg.ansi_index = index;
3212 }
3213 }
3214 else
3215 dump_is_corrupt(&ga_text);
3216 }
3217 }
3218 else
3219 dump_is_corrupt(&ga_text);
3220
3221 append_cell(&ga_cell, &cell);
3222 }
3223 else if (c == '@')
3224 {
3225 if (prev_char == NULL)
3226 dump_is_corrupt(&ga_text);
3227 else
3228 {
3229 int count = 0;
3230
3231 /* repeat previous character, get the count */
3232 for (;;)
3233 {
3234 c = fgetc(fd);
3235 if (!isdigit(c))
3236 break;
3237 count = count * 10 + (c - '0');
3238 }
3239
3240 while (count-- > 0)
3241 {
3242 ga_concat(&ga_text, prev_char);
3243 append_cell(&ga_cell, &cell);
3244 }
3245 }
3246 }
3247 else
3248 {
3249 dump_is_corrupt(&ga_text);
3250 c = fgetc(fd);
3251 }
3252 }
3253
3254 if (ga_text.ga_len > 0)
3255 {
3256 /* trailing characters after last NL */
3257 dump_is_corrupt(&ga_text);
3258 ga_append(&ga_text, NUL);
3259 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3260 ga_text.ga_len, FALSE);
3261 }
3262
3263 ga_clear(&ga_text);
3264 vim_free(prev_char);
3265
3266 return max_cells;
3267}
3268
3269/*
3270 * Common for "term_dumpdiff()" and "term_dumpload()".
3271 */
3272 static void
3273term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
3274{
3275 jobopt_T opt;
3276 buf_T *buf;
3277 char_u buf1[NUMBUFLEN];
3278 char_u buf2[NUMBUFLEN];
3279 char_u *fname1;
3280 char_u *fname2;
3281 FILE *fd1;
3282 FILE *fd2;
3283 char_u *textline = NULL;
3284
3285 /* First open the files. If this fails bail out. */
3286 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
3287 if (do_diff)
3288 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
3289 if (fname1 == NULL || (do_diff && fname2 == NULL))
3290 {
3291 EMSG(_(e_invarg));
3292 return;
3293 }
3294 fd1 = mch_fopen((char *)fname1, READBIN);
3295 if (fd1 == NULL)
3296 {
3297 EMSG2(_(e_notread), fname1);
3298 return;
3299 }
3300 if (do_diff)
3301 {
3302 fd2 = mch_fopen((char *)fname2, READBIN);
3303 if (fd2 == NULL)
3304 {
3305 fclose(fd1);
3306 EMSG2(_(e_notread), fname2);
3307 return;
3308 }
3309 }
3310
3311 init_job_options(&opt);
3312 /* TODO: use the {options} argument */
3313
3314 /* TODO: use the file name arguments for the buffer name */
3315 opt.jo_term_name = (char_u *)"dump diff";
3316
3317 buf = term_start(&argvars[0], &opt, TRUE, FALSE);
3318 if (buf != NULL && buf->b_term != NULL)
3319 {
3320 int i;
3321 linenr_T bot_lnum;
3322 linenr_T lnum;
3323 term_T *term = buf->b_term;
3324 int width;
3325 int width2;
3326
3327 rettv->vval.v_number = buf->b_fnum;
3328
3329 /* read the files, fill the buffer with the diff */
3330 width = read_dump_file(fd1);
3331
3332 /* Delete the empty line that was in the empty buffer. */
3333 ml_delete(1, FALSE);
3334
3335 /* For term_dumpload() we are done here. */
3336 if (!do_diff)
3337 goto theend;
3338
3339 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
3340
3341 textline = alloc(width + 1);
3342 if (textline == NULL)
3343 goto theend;
3344 for (i = 0; i < width; ++i)
3345 textline[i] = '=';
3346 textline[width] = NUL;
3347 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3348 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3349 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3350 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3351
3352 bot_lnum = curbuf->b_ml.ml_line_count;
3353 width2 = read_dump_file(fd2);
3354 if (width2 > width)
3355 {
3356 vim_free(textline);
3357 textline = alloc(width2 + 1);
3358 if (textline == NULL)
3359 goto theend;
3360 width = width2;
3361 textline[width] = NUL;
3362 }
3363 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
3364
3365 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
3366 {
3367 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
3368 {
3369 /* bottom part has fewer rows, fill with "-" */
3370 for (i = 0; i < width; ++i)
3371 textline[i] = '-';
3372 }
3373 else
3374 {
3375 char_u *line1;
3376 char_u *line2;
3377 char_u *p1;
3378 char_u *p2;
3379 int col;
3380 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3381 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
3382 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
3383 ->sb_cells;
3384
3385 /* Make a copy, getting the second line will invalidate it. */
3386 line1 = vim_strsave(ml_get(lnum));
3387 if (line1 == NULL)
3388 break;
3389 p1 = line1;
3390
3391 line2 = ml_get(lnum + bot_lnum);
3392 p2 = line2;
3393 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
3394 {
3395 int len1 = utfc_ptr2len(p1);
3396 int len2 = utfc_ptr2len(p2);
3397
3398 textline[col] = ' ';
3399 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
3400 textline[col] = 'X';
3401 else if (cellattr1 != NULL && cellattr2 != NULL)
3402 {
3403 if ((cellattr1 + col)->width
3404 != (cellattr2 + col)->width)
3405 textline[col] = 'w';
3406 else if (!same_color(&(cellattr1 + col)->fg,
3407 &(cellattr2 + col)->fg))
3408 textline[col] = 'f';
3409 else if (!same_color(&(cellattr1 + col)->bg,
3410 &(cellattr2 + col)->bg))
3411 textline[col] = 'b';
3412 else if (vtermAttr2hl((cellattr1 + col)->attrs)
3413 != vtermAttr2hl(((cellattr2 + col)->attrs)))
3414 textline[col] = 'a';
3415 }
3416 p1 += len1;
3417 p2 += len2;
3418 /* TODO: handle different width */
3419 }
3420 vim_free(line1);
3421
3422 while (col < width)
3423 {
3424 if (*p1 == NUL && *p2 == NUL)
3425 textline[col] = '?';
3426 else if (*p1 == NUL)
3427 {
3428 textline[col] = '+';
3429 p2 += utfc_ptr2len(p2);
3430 }
3431 else
3432 {
3433 textline[col] = '-';
3434 p1 += utfc_ptr2len(p1);
3435 }
3436 ++col;
3437 }
3438 }
3439 if (add_empty_scrollback(term, &term->tl_default_color,
3440 term->tl_top_diff_rows) == OK)
3441 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3442 ++bot_lnum;
3443 }
3444
3445 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
3446 {
3447 /* bottom part has more rows, fill with "+" */
3448 for (i = 0; i < width; ++i)
3449 textline[i] = '+';
3450 if (add_empty_scrollback(term, &term->tl_default_color,
3451 term->tl_top_diff_rows) == OK)
3452 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3453 ++lnum;
3454 ++bot_lnum;
3455 }
3456
3457 term->tl_cols = width;
3458 }
3459
3460theend:
3461 vim_free(textline);
3462 fclose(fd1);
3463 if (do_diff)
3464 fclose(fd2);
3465}
3466
3467/*
3468 * If the current buffer shows the output of term_dumpdiff(), swap the top and
3469 * bottom files.
3470 * Return FAIL when this is not possible.
3471 */
3472 int
3473term_swap_diff()
3474{
3475 term_T *term = curbuf->b_term;
3476 linenr_T line_count;
3477 linenr_T top_rows;
3478 linenr_T bot_rows;
3479 linenr_T bot_start;
3480 linenr_T lnum;
3481 char_u *p;
3482 sb_line_T *sb_line;
3483
3484 if (term == NULL
3485 || !term_is_finished(curbuf)
3486 || term->tl_top_diff_rows == 0
3487 || term->tl_scrollback.ga_len == 0)
3488 return FAIL;
3489
3490 line_count = curbuf->b_ml.ml_line_count;
3491 top_rows = term->tl_top_diff_rows;
3492 bot_rows = term->tl_bot_diff_rows;
3493 bot_start = line_count - bot_rows;
3494 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3495
3496 /* move lines from top to above the bottom part */
3497 for (lnum = 1; lnum <= top_rows; ++lnum)
3498 {
3499 p = vim_strsave(ml_get(1));
3500 if (p == NULL)
3501 return OK;
3502 ml_append(bot_start, p, 0, FALSE);
3503 ml_delete(1, FALSE);
3504 vim_free(p);
3505 }
3506
3507 /* move lines from bottom to the top */
3508 for (lnum = 1; lnum <= bot_rows; ++lnum)
3509 {
3510 p = vim_strsave(ml_get(bot_start + lnum));
3511 if (p == NULL)
3512 return OK;
3513 ml_delete(bot_start + lnum, FALSE);
3514 ml_append(lnum - 1, p, 0, FALSE);
3515 vim_free(p);
3516 }
3517
3518 if (top_rows == bot_rows)
3519 {
3520 /* rows counts are equal, can swap cell properties */
3521 for (lnum = 0; lnum < top_rows; ++lnum)
3522 {
3523 sb_line_T temp;
3524
3525 temp = *(sb_line + lnum);
3526 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
3527 *(sb_line + bot_start + lnum) = temp;
3528 }
3529 }
3530 else
3531 {
3532 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
3533 sb_line_T *temp = (sb_line_T *)alloc((int)size);
3534
3535 /* need to copy cell properties into temp memory */
3536 if (temp != NULL)
3537 {
3538 mch_memmove(temp, term->tl_scrollback.ga_data, size);
3539 mch_memmove(term->tl_scrollback.ga_data,
3540 temp + bot_start,
3541 sizeof(sb_line_T) * bot_rows);
3542 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
3543 temp + top_rows,
3544 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
3545 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
3546 + line_count - top_rows,
3547 temp,
3548 sizeof(sb_line_T) * top_rows);
3549 vim_free(temp);
3550 }
3551 }
3552
3553 term->tl_top_diff_rows = bot_rows;
3554 term->tl_bot_diff_rows = top_rows;
3555
3556 update_screen(NOT_VALID);
3557 return OK;
3558}
3559
3560/*
3561 * "term_dumpdiff(filename, filename, options)" function
3562 */
3563 void
3564f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
3565{
3566 term_load_dump(argvars, rettv, TRUE);
3567}
3568
3569/*
3570 * "term_dumpload(filename, options)" function
3571 */
3572 void
3573f_term_dumpload(typval_T *argvars, typval_T *rettv)
3574{
3575 term_load_dump(argvars, rettv, FALSE);
3576}
3577
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003578/*
3579 * "term_getaltscreen(buf)" function
3580 */
3581 void
3582f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
3583{
3584 buf_T *buf = term_get_buf(argvars);
3585
3586 if (buf == NULL)
3587 return;
3588 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
3589}
3590
3591/*
3592 * "term_getattr(attr, name)" function
3593 */
3594 void
3595f_term_getattr(typval_T *argvars, typval_T *rettv)
3596{
3597 int attr;
3598 size_t i;
3599 char_u *name;
3600
3601 static struct {
3602 char *name;
3603 int attr;
3604 } attrs[] = {
3605 {"bold", HL_BOLD},
3606 {"italic", HL_ITALIC},
3607 {"underline", HL_UNDERLINE},
3608 {"strike", HL_STRIKETHROUGH},
3609 {"reverse", HL_INVERSE},
3610 };
3611
3612 attr = get_tv_number(&argvars[0]);
3613 name = get_tv_string_chk(&argvars[1]);
3614 if (name == NULL)
3615 return;
3616
3617 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
3618 if (STRCMP(name, attrs[i].name) == 0)
3619 {
3620 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
3621 break;
3622 }
3623}
3624
3625/*
3626 * "term_getcursor(buf)" function
3627 */
3628 void
3629f_term_getcursor(typval_T *argvars, typval_T *rettv)
3630{
3631 buf_T *buf = term_get_buf(argvars);
3632 term_T *term;
3633 list_T *l;
3634 dict_T *d;
3635
3636 if (rettv_list_alloc(rettv) == FAIL)
3637 return;
3638 if (buf == NULL)
3639 return;
3640 term = buf->b_term;
3641
3642 l = rettv->vval.v_list;
3643 list_append_number(l, term->tl_cursor_pos.row + 1);
3644 list_append_number(l, term->tl_cursor_pos.col + 1);
3645
3646 d = dict_alloc();
3647 if (d != NULL)
3648 {
3649 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
3650 dict_add_nr_str(d, "blink", blink_state_is_inverted()
3651 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
3652 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
3653 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
3654 ? (char_u *)"" : term->tl_cursor_color);
3655 list_append_dict(l, d);
3656 }
3657}
3658
3659/*
3660 * "term_getjob(buf)" function
3661 */
3662 void
3663f_term_getjob(typval_T *argvars, typval_T *rettv)
3664{
3665 buf_T *buf = term_get_buf(argvars);
3666
3667 rettv->v_type = VAR_JOB;
3668 rettv->vval.v_job = NULL;
3669 if (buf == NULL)
3670 return;
3671
3672 rettv->vval.v_job = buf->b_term->tl_job;
3673 if (rettv->vval.v_job != NULL)
3674 ++rettv->vval.v_job->jv_refcount;
3675}
3676
3677 static int
3678get_row_number(typval_T *tv, term_T *term)
3679{
3680 if (tv->v_type == VAR_STRING
3681 && tv->vval.v_string != NULL
3682 && STRCMP(tv->vval.v_string, ".") == 0)
3683 return term->tl_cursor_pos.row;
3684 return (int)get_tv_number(tv) - 1;
3685}
3686
3687/*
3688 * "term_getline(buf, row)" function
3689 */
3690 void
3691f_term_getline(typval_T *argvars, typval_T *rettv)
3692{
3693 buf_T *buf = term_get_buf(argvars);
3694 term_T *term;
3695 int row;
3696
3697 rettv->v_type = VAR_STRING;
3698 if (buf == NULL)
3699 return;
3700 term = buf->b_term;
3701 row = get_row_number(&argvars[1], term);
3702
3703 if (term->tl_vterm == NULL)
3704 {
3705 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
3706
3707 /* vterm is finished, get the text from the buffer */
3708 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
3709 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
3710 }
3711 else
3712 {
3713 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
3714 VTermRect rect;
3715 int len;
3716 char_u *p;
3717
3718 if (row < 0 || row >= term->tl_rows)
3719 return;
3720 len = term->tl_cols * MB_MAXBYTES + 1;
3721 p = alloc(len);
3722 if (p == NULL)
3723 return;
3724 rettv->vval.v_string = p;
3725
3726 rect.start_col = 0;
3727 rect.end_col = term->tl_cols;
3728 rect.start_row = row;
3729 rect.end_row = row + 1;
3730 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
3731 }
3732}
3733
3734/*
3735 * "term_getscrolled(buf)" function
3736 */
3737 void
3738f_term_getscrolled(typval_T *argvars, typval_T *rettv)
3739{
3740 buf_T *buf = term_get_buf(argvars);
3741
3742 if (buf == NULL)
3743 return;
3744 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
3745}
3746
3747/*
3748 * "term_getsize(buf)" function
3749 */
3750 void
3751f_term_getsize(typval_T *argvars, typval_T *rettv)
3752{
3753 buf_T *buf = term_get_buf(argvars);
3754 list_T *l;
3755
3756 if (rettv_list_alloc(rettv) == FAIL)
3757 return;
3758 if (buf == NULL)
3759 return;
3760
3761 l = rettv->vval.v_list;
3762 list_append_number(l, buf->b_term->tl_rows);
3763 list_append_number(l, buf->b_term->tl_cols);
3764}
3765
3766/*
3767 * "term_getstatus(buf)" function
3768 */
3769 void
3770f_term_getstatus(typval_T *argvars, typval_T *rettv)
3771{
3772 buf_T *buf = term_get_buf(argvars);
3773 term_T *term;
3774 char_u val[100];
3775
3776 rettv->v_type = VAR_STRING;
3777 if (buf == NULL)
3778 return;
3779 term = buf->b_term;
3780
3781 if (term_job_running(term))
3782 STRCPY(val, "running");
3783 else
3784 STRCPY(val, "finished");
3785 if (term->tl_normal_mode)
3786 STRCAT(val, ",normal");
3787 rettv->vval.v_string = vim_strsave(val);
3788}
3789
3790/*
3791 * "term_gettitle(buf)" function
3792 */
3793 void
3794f_term_gettitle(typval_T *argvars, typval_T *rettv)
3795{
3796 buf_T *buf = term_get_buf(argvars);
3797
3798 rettv->v_type = VAR_STRING;
3799 if (buf == NULL)
3800 return;
3801
3802 if (buf->b_term->tl_title != NULL)
3803 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
3804}
3805
3806/*
3807 * "term_gettty(buf)" function
3808 */
3809 void
3810f_term_gettty(typval_T *argvars, typval_T *rettv)
3811{
3812 buf_T *buf = term_get_buf(argvars);
3813 char_u *p;
3814 int num = 0;
3815
3816 rettv->v_type = VAR_STRING;
3817 if (buf == NULL)
3818 return;
3819 if (argvars[1].v_type != VAR_UNKNOWN)
3820 num = get_tv_number(&argvars[1]);
3821
3822 switch (num)
3823 {
3824 case 0:
3825 if (buf->b_term->tl_job != NULL)
3826 p = buf->b_term->tl_job->jv_tty_out;
3827 else
3828 p = buf->b_term->tl_tty_out;
3829 break;
3830 case 1:
3831 if (buf->b_term->tl_job != NULL)
3832 p = buf->b_term->tl_job->jv_tty_in;
3833 else
3834 p = buf->b_term->tl_tty_in;
3835 break;
3836 default:
3837 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
3838 return;
3839 }
3840 if (p != NULL)
3841 rettv->vval.v_string = vim_strsave(p);
3842}
3843
3844/*
3845 * "term_list()" function
3846 */
3847 void
3848f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3849{
3850 term_T *tp;
3851 list_T *l;
3852
3853 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3854 return;
3855
3856 l = rettv->vval.v_list;
3857 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3858 if (tp != NULL && tp->tl_buffer != NULL)
3859 if (list_append_number(l,
3860 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3861 return;
3862}
3863
3864/*
3865 * "term_scrape(buf, row)" function
3866 */
3867 void
3868f_term_scrape(typval_T *argvars, typval_T *rettv)
3869{
3870 buf_T *buf = term_get_buf(argvars);
3871 VTermScreen *screen = NULL;
3872 VTermPos pos;
3873 list_T *l;
3874 term_T *term;
3875 char_u *p;
3876 sb_line_T *line;
3877
3878 if (rettv_list_alloc(rettv) == FAIL)
3879 return;
3880 if (buf == NULL)
3881 return;
3882 term = buf->b_term;
3883
3884 l = rettv->vval.v_list;
3885 pos.row = get_row_number(&argvars[1], term);
3886
3887 if (term->tl_vterm != NULL)
3888 {
3889 screen = vterm_obtain_screen(term->tl_vterm);
3890 p = NULL;
3891 line = NULL;
3892 }
3893 else
3894 {
3895 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3896
3897 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3898 return;
3899 p = ml_get_buf(buf, lnum + 1, FALSE);
3900 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3901 }
3902
3903 for (pos.col = 0; pos.col < term->tl_cols; )
3904 {
3905 dict_T *dcell;
3906 int width;
3907 VTermScreenCellAttrs attrs;
3908 VTermColor fg, bg;
3909 char_u rgb[8];
3910 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3911 int off = 0;
3912 int i;
3913
3914 if (screen == NULL)
3915 {
3916 cellattr_T *cellattr;
3917 int len;
3918
3919 /* vterm has finished, get the cell from scrollback */
3920 if (pos.col >= line->sb_cols)
3921 break;
3922 cellattr = line->sb_cells + pos.col;
3923 width = cellattr->width;
3924 attrs = cellattr->attrs;
3925 fg = cellattr->fg;
3926 bg = cellattr->bg;
3927 len = MB_PTR2LEN(p);
3928 mch_memmove(mbs, p, len);
3929 mbs[len] = NUL;
3930 p += len;
3931 }
3932 else
3933 {
3934 VTermScreenCell cell;
3935 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3936 break;
3937 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3938 {
3939 if (cell.chars[i] == 0)
3940 break;
3941 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3942 }
3943 mbs[off] = NUL;
3944 width = cell.width;
3945 attrs = cell.attrs;
3946 fg = cell.fg;
3947 bg = cell.bg;
3948 }
3949 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01003950 if (dcell == NULL)
3951 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003952 list_append_dict(l, dcell);
3953
3954 dict_add_nr_str(dcell, "chars", 0, mbs);
3955
3956 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3957 fg.red, fg.green, fg.blue);
3958 dict_add_nr_str(dcell, "fg", 0, rgb);
3959 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3960 bg.red, bg.green, bg.blue);
3961 dict_add_nr_str(dcell, "bg", 0, rgb);
3962
3963 dict_add_nr_str(dcell, "attr",
3964 cell2attr(attrs, fg, bg), NULL);
3965 dict_add_nr_str(dcell, "width", width, NULL);
3966
3967 ++pos.col;
3968 if (width == 2)
3969 ++pos.col;
3970 }
3971}
3972
3973/*
3974 * "term_sendkeys(buf, keys)" function
3975 */
3976 void
3977f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3978{
3979 buf_T *buf = term_get_buf(argvars);
3980 char_u *msg;
3981 term_T *term;
3982
3983 rettv->v_type = VAR_UNKNOWN;
3984 if (buf == NULL)
3985 return;
3986
3987 msg = get_tv_string_chk(&argvars[1]);
3988 if (msg == NULL)
3989 return;
3990 term = buf->b_term;
3991 if (term->tl_vterm == NULL)
3992 return;
3993
3994 while (*msg != NUL)
3995 {
3996 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003997 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003998 }
3999}
4000
4001/*
4002 * "term_start(command, options)" function
4003 */
4004 void
4005f_term_start(typval_T *argvars, typval_T *rettv)
4006{
4007 jobopt_T opt;
4008 buf_T *buf;
4009
4010 init_job_options(&opt);
4011 if (argvars[1].v_type != VAR_UNKNOWN
4012 && get_job_options(&argvars[1], &opt,
4013 JO_TIMEOUT_ALL + JO_STOPONEXIT
4014 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4015 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4016 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4017 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
4018 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
4019 return;
4020
4021 if (opt.jo_vertical)
4022 cmdmod.split = WSP_VERT;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004023 buf = term_start(&argvars[0], &opt, FALSE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004024
4025 if (buf != NULL && buf->b_term != NULL)
4026 rettv->vval.v_number = buf->b_fnum;
4027}
4028
4029/*
4030 * "term_wait" function
4031 */
4032 void
4033f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4034{
4035 buf_T *buf = term_get_buf(argvars);
4036
4037 if (buf == NULL)
4038 {
4039 ch_log(NULL, "term_wait(): invalid argument");
4040 return;
4041 }
4042 if (buf->b_term->tl_job == NULL)
4043 {
4044 ch_log(NULL, "term_wait(): no job to wait for");
4045 return;
4046 }
4047 if (buf->b_term->tl_job->jv_channel == NULL)
4048 /* channel is closed, nothing to do */
4049 return;
4050
4051 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004052 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004053 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4054 {
4055 /* The job is dead, keep reading channel I/O until the channel is
4056 * closed. buf->b_term may become NULL if the terminal was closed while
4057 * waiting. */
4058 ch_log(NULL, "term_wait(): waiting for channel to close");
4059 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4060 {
4061 mch_check_messages();
4062 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01004063 if (!buf_valid(buf))
4064 /* If the terminal is closed when the channel is closed the
4065 * buffer disappears. */
4066 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004067 ui_delay(10L, FALSE);
4068 }
4069 mch_check_messages();
4070 parse_queued_messages();
4071 }
4072 else
4073 {
4074 long wait = 10L;
4075
4076 mch_check_messages();
4077 parse_queued_messages();
4078
4079 /* Wait for some time for any channel I/O. */
4080 if (argvars[1].v_type != VAR_UNKNOWN)
4081 wait = get_tv_number(&argvars[1]);
4082 ui_delay(wait, TRUE);
4083 mch_check_messages();
4084
4085 /* Flushing messages on channels is hopefully sufficient.
4086 * TODO: is there a better way? */
4087 parse_queued_messages();
4088 }
4089}
4090
4091/*
4092 * Called when a channel has sent all the lines to a terminal.
4093 * Send a CTRL-D to mark the end of the text.
4094 */
4095 void
4096term_send_eof(channel_T *ch)
4097{
4098 term_T *term;
4099
4100 for (term = first_term; term != NULL; term = term->tl_next)
4101 if (term->tl_job == ch->ch_job)
4102 {
4103 if (term->tl_eof_chars != NULL)
4104 {
4105 channel_send(ch, PART_IN, term->tl_eof_chars,
4106 (int)STRLEN(term->tl_eof_chars), NULL);
4107 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
4108 }
4109# ifdef WIN3264
4110 else
4111 /* Default: CTRL-D */
4112 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
4113# endif
4114 }
4115}
4116
4117# if defined(WIN3264) || defined(PROTO)
4118
4119/**************************************
4120 * 2. MS-Windows implementation.
4121 */
4122
4123# ifndef PROTO
4124
4125#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
4126#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01004127#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004128
4129void* (*winpty_config_new)(UINT64, void*);
4130void* (*winpty_open)(void*, void*);
4131void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
4132BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
4133void (*winpty_config_set_mouse_mode)(void*, int);
4134void (*winpty_config_set_initial_size)(void*, int, int);
4135LPCWSTR (*winpty_conin_name)(void*);
4136LPCWSTR (*winpty_conout_name)(void*);
4137LPCWSTR (*winpty_conerr_name)(void*);
4138void (*winpty_free)(void*);
4139void (*winpty_config_free)(void*);
4140void (*winpty_spawn_config_free)(void*);
4141void (*winpty_error_free)(void*);
4142LPCWSTR (*winpty_error_msg)(void*);
4143BOOL (*winpty_set_size)(void*, int, int, void*);
4144HANDLE (*winpty_agent_process)(void*);
4145
4146#define WINPTY_DLL "winpty.dll"
4147
4148static HINSTANCE hWinPtyDLL = NULL;
4149# endif
4150
4151 static int
4152dyn_winpty_init(int verbose)
4153{
4154 int i;
4155 static struct
4156 {
4157 char *name;
4158 FARPROC *ptr;
4159 } winpty_entry[] =
4160 {
4161 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
4162 {"winpty_config_free", (FARPROC*)&winpty_config_free},
4163 {"winpty_config_new", (FARPROC*)&winpty_config_new},
4164 {"winpty_config_set_mouse_mode",
4165 (FARPROC*)&winpty_config_set_mouse_mode},
4166 {"winpty_config_set_initial_size",
4167 (FARPROC*)&winpty_config_set_initial_size},
4168 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
4169 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
4170 {"winpty_error_free", (FARPROC*)&winpty_error_free},
4171 {"winpty_free", (FARPROC*)&winpty_free},
4172 {"winpty_open", (FARPROC*)&winpty_open},
4173 {"winpty_spawn", (FARPROC*)&winpty_spawn},
4174 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
4175 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
4176 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
4177 {"winpty_set_size", (FARPROC*)&winpty_set_size},
4178 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
4179 {NULL, NULL}
4180 };
4181
4182 /* No need to initialize twice. */
4183 if (hWinPtyDLL)
4184 return OK;
4185 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
4186 * winpty.dll. */
4187 if (*p_winptydll != NUL)
4188 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
4189 if (!hWinPtyDLL)
4190 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
4191 if (!hWinPtyDLL)
4192 {
4193 if (verbose)
4194 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
4195 : (char_u *)WINPTY_DLL);
4196 return FAIL;
4197 }
4198 for (i = 0; winpty_entry[i].name != NULL
4199 && winpty_entry[i].ptr != NULL; ++i)
4200 {
4201 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
4202 winpty_entry[i].name)) == NULL)
4203 {
4204 if (verbose)
4205 EMSG2(_(e_loadfunc), winpty_entry[i].name);
4206 return FAIL;
4207 }
4208 }
4209
4210 return OK;
4211}
4212
4213/*
4214 * Create a new terminal of "rows" by "cols" cells.
4215 * Store a reference in "term".
4216 * Return OK or FAIL.
4217 */
4218 static int
4219term_and_job_init(
4220 term_T *term,
4221 typval_T *argvar,
4222 jobopt_T *opt)
4223{
4224 WCHAR *cmd_wchar = NULL;
4225 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004226 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004227 channel_T *channel = NULL;
4228 job_T *job = NULL;
4229 DWORD error;
4230 HANDLE jo = NULL;
4231 HANDLE child_process_handle;
4232 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01004233 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004234 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004235 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004236 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004237
4238 if (dyn_winpty_init(TRUE) == FAIL)
4239 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004240 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
4241 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004242
4243 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004244 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004245 cmd = argvar->vval.v_string;
4246 }
4247 else if (argvar->v_type == VAR_LIST)
4248 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004249 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004250 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004251 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004252 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004253 if (cmd == NULL || *cmd == NUL)
4254 {
4255 EMSG(_(e_invarg));
4256 goto failed;
4257 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004258
4259 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004260 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004261 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004262 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004263 if (opt->jo_cwd != NULL)
4264 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004265
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004266 win32_build_env(opt->jo_env, &ga_env, TRUE);
4267 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004268
4269 job = job_alloc();
4270 if (job == NULL)
4271 goto failed;
4272
4273 channel = add_channel();
4274 if (channel == NULL)
4275 goto failed;
4276
4277 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
4278 if (term->tl_winpty_config == NULL)
4279 goto failed;
4280
4281 winpty_config_set_mouse_mode(term->tl_winpty_config,
4282 WINPTY_MOUSE_MODE_FORCE);
4283 winpty_config_set_initial_size(term->tl_winpty_config,
4284 term->tl_cols, term->tl_rows);
4285 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
4286 if (term->tl_winpty == NULL)
4287 goto failed;
4288
4289 spawn_config = winpty_spawn_config_new(
4290 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
4291 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
4292 NULL,
4293 cmd_wchar,
4294 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004295 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004296 &winpty_err);
4297 if (spawn_config == NULL)
4298 goto failed;
4299
4300 channel = add_channel();
4301 if (channel == NULL)
4302 goto failed;
4303
4304 job = job_alloc();
4305 if (job == NULL)
4306 goto failed;
4307
4308 if (opt->jo_set & JO_IN_BUF)
4309 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
4310
4311 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
4312 &child_thread_handle, &error, &winpty_err))
4313 goto failed;
4314
4315 channel_set_pipes(channel,
4316 (sock_T)CreateFileW(
4317 winpty_conin_name(term->tl_winpty),
4318 GENERIC_WRITE, 0, NULL,
4319 OPEN_EXISTING, 0, NULL),
4320 (sock_T)CreateFileW(
4321 winpty_conout_name(term->tl_winpty),
4322 GENERIC_READ, 0, NULL,
4323 OPEN_EXISTING, 0, NULL),
4324 (sock_T)CreateFileW(
4325 winpty_conerr_name(term->tl_winpty),
4326 GENERIC_READ, 0, NULL,
4327 OPEN_EXISTING, 0, NULL));
4328
4329 /* Write lines with CR instead of NL. */
4330 channel->ch_write_text_mode = TRUE;
4331
4332 jo = CreateJobObject(NULL, NULL);
4333 if (jo == NULL)
4334 goto failed;
4335
4336 if (!AssignProcessToJobObject(jo, child_process_handle))
4337 {
4338 /* Failed, switch the way to terminate process with TerminateProcess. */
4339 CloseHandle(jo);
4340 jo = NULL;
4341 }
4342
4343 winpty_spawn_config_free(spawn_config);
4344 vim_free(cmd_wchar);
4345 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004346 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004347
4348 create_vterm(term, term->tl_rows, term->tl_cols);
4349
4350 channel_set_job(channel, job, opt);
4351 job_set_options(job, opt);
4352
4353 job->jv_channel = channel;
4354 job->jv_proc_info.hProcess = child_process_handle;
4355 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
4356 job->jv_job_object = jo;
4357 job->jv_status = JOB_STARTED;
4358 job->jv_tty_in = utf16_to_enc(
4359 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
4360 job->jv_tty_out = utf16_to_enc(
4361 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
4362 ++job->jv_refcount;
4363 term->tl_job = job;
4364
4365 return OK;
4366
4367failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004368 ga_clear(&ga_cmd);
4369 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004370 vim_free(cmd_wchar);
4371 vim_free(cwd_wchar);
4372 if (spawn_config != NULL)
4373 winpty_spawn_config_free(spawn_config);
4374 if (channel != NULL)
4375 channel_clear(channel);
4376 if (job != NULL)
4377 {
4378 job->jv_channel = NULL;
4379 job_cleanup(job);
4380 }
4381 term->tl_job = NULL;
4382 if (jo != NULL)
4383 CloseHandle(jo);
4384 if (term->tl_winpty != NULL)
4385 winpty_free(term->tl_winpty);
4386 term->tl_winpty = NULL;
4387 if (term->tl_winpty_config != NULL)
4388 winpty_config_free(term->tl_winpty_config);
4389 term->tl_winpty_config = NULL;
4390 if (winpty_err != NULL)
4391 {
4392 char_u *msg = utf16_to_enc(
4393 (short_u *)winpty_error_msg(winpty_err), NULL);
4394
4395 EMSG(msg);
4396 winpty_error_free(winpty_err);
4397 }
4398 return FAIL;
4399}
4400
4401 static int
4402create_pty_only(term_T *term, jobopt_T *options)
4403{
4404 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
4405 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
4406 char in_name[80], out_name[80];
4407 channel_T *channel = NULL;
4408
4409 create_vterm(term, term->tl_rows, term->tl_cols);
4410
4411 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
4412 GetCurrentProcessId(),
4413 curbuf->b_fnum);
4414 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
4415 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4416 PIPE_UNLIMITED_INSTANCES,
4417 0, 0, NMPWAIT_NOWAIT, NULL);
4418 if (hPipeIn == INVALID_HANDLE_VALUE)
4419 goto failed;
4420
4421 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
4422 GetCurrentProcessId(),
4423 curbuf->b_fnum);
4424 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
4425 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4426 PIPE_UNLIMITED_INSTANCES,
4427 0, 0, 0, NULL);
4428 if (hPipeOut == INVALID_HANDLE_VALUE)
4429 goto failed;
4430
4431 ConnectNamedPipe(hPipeIn, NULL);
4432 ConnectNamedPipe(hPipeOut, NULL);
4433
4434 term->tl_job = job_alloc();
4435 if (term->tl_job == NULL)
4436 goto failed;
4437 ++term->tl_job->jv_refcount;
4438
4439 /* behave like the job is already finished */
4440 term->tl_job->jv_status = JOB_FINISHED;
4441
4442 channel = add_channel();
4443 if (channel == NULL)
4444 goto failed;
4445 term->tl_job->jv_channel = channel;
4446 channel->ch_keep_open = TRUE;
4447 channel->ch_named_pipe = TRUE;
4448
4449 channel_set_pipes(channel,
4450 (sock_T)hPipeIn,
4451 (sock_T)hPipeOut,
4452 (sock_T)hPipeOut);
4453 channel_set_job(channel, term->tl_job, options);
4454 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
4455 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
4456
4457 return OK;
4458
4459failed:
4460 if (hPipeIn != NULL)
4461 CloseHandle(hPipeIn);
4462 if (hPipeOut != NULL)
4463 CloseHandle(hPipeOut);
4464 return FAIL;
4465}
4466
4467/*
4468 * Free the terminal emulator part of "term".
4469 */
4470 static void
4471term_free_vterm(term_T *term)
4472{
4473 if (term->tl_winpty != NULL)
4474 winpty_free(term->tl_winpty);
4475 term->tl_winpty = NULL;
4476 if (term->tl_winpty_config != NULL)
4477 winpty_config_free(term->tl_winpty_config);
4478 term->tl_winpty_config = NULL;
4479 if (term->tl_vterm != NULL)
4480 vterm_free(term->tl_vterm);
4481 term->tl_vterm = NULL;
4482}
4483
4484/*
4485 * Request size to terminal.
4486 */
4487 static void
4488term_report_winsize(term_T *term, int rows, int cols)
4489{
4490 if (term->tl_winpty)
4491 winpty_set_size(term->tl_winpty, cols, rows, NULL);
4492}
4493
4494 int
4495terminal_enabled(void)
4496{
4497 return dyn_winpty_init(FALSE) == OK;
4498}
4499
4500# else
4501
4502/**************************************
4503 * 3. Unix-like implementation.
4504 */
4505
4506/*
4507 * Create a new terminal of "rows" by "cols" cells.
4508 * Start job for "cmd".
4509 * Store the pointers in "term".
4510 * Return OK or FAIL.
4511 */
4512 static int
4513term_and_job_init(
4514 term_T *term,
4515 typval_T *argvar,
4516 jobopt_T *opt)
4517{
4518 create_vterm(term, term->tl_rows, term->tl_cols);
4519
4520 term->tl_job = job_start(argvar, opt);
4521 if (term->tl_job != NULL)
4522 ++term->tl_job->jv_refcount;
4523
4524 return term->tl_job != NULL
4525 && term->tl_job->jv_channel != NULL
4526 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
4527}
4528
4529 static int
4530create_pty_only(term_T *term, jobopt_T *opt)
4531{
4532 create_vterm(term, term->tl_rows, term->tl_cols);
4533
4534 term->tl_job = job_alloc();
4535 if (term->tl_job == NULL)
4536 return FAIL;
4537 ++term->tl_job->jv_refcount;
4538
4539 /* behave like the job is already finished */
4540 term->tl_job->jv_status = JOB_FINISHED;
4541
4542 return mch_create_pty_channel(term->tl_job, opt);
4543}
4544
4545/*
4546 * Free the terminal emulator part of "term".
4547 */
4548 static void
4549term_free_vterm(term_T *term)
4550{
4551 if (term->tl_vterm != NULL)
4552 vterm_free(term->tl_vterm);
4553 term->tl_vterm = NULL;
4554}
4555
4556/*
4557 * Request size to terminal.
4558 */
4559 static void
4560term_report_winsize(term_T *term, int rows, int cols)
4561{
4562 /* Use an ioctl() to report the new window size to the job. */
4563 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
4564 {
4565 int fd = -1;
4566 int part;
4567
4568 for (part = PART_OUT; part < PART_COUNT; ++part)
4569 {
4570 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
4571 if (isatty(fd))
4572 break;
4573 }
4574 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
4575 mch_signal_job(term->tl_job, (char_u *)"winch");
4576 }
4577}
4578
4579# endif
4580
4581#endif /* FEAT_TERMINAL */