blob: 0d6a9571b407a7c37f991b4a2794bb80217aee32 [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 Moolenaar2e6ab182017-09-20 10:03:07 +020046 * - Shift-Tab does not work.
Bram Moolenaar3a497e12017-09-30 20:40:27 +020047 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020048 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
49 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020050 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010051 * - When closing gvim with an active terminal buffer, the dialog suggests
52 * saving the buffer. Should say something else. (Manas Thakur, #2215)
53 * Also: #2223
Bram Moolenaarba6febd2017-10-30 21:56:23 +010054 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020055 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaarff546792017-11-21 14:47:57 +010056 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020057 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010058 * - After executing a shell command the status line isn't redraw.
Bram Moolenaarba6febd2017-10-30 21:56:23 +010059 * - What to store in a session file? Shell at the prompt would be OK to
60 * restore, but others may not. Open the window and let the user start the
61 * command?
Bram Moolenaar46359e12017-11-29 22:33:38 +010062 * - implement term_setsize()
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020063 * - add test for giving error for invalid 'termsize' value.
64 * - support minimal size when 'termsize' is "rows*cols".
65 * - support minimal size when 'termsize' is empty?
Bram Moolenaarede35bb2018-01-26 20:05:18 +010066 * - if the job in the terminal does not support the mouse, we can use the
67 * mouse in the Terminal window for copy/paste and scrolling.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020068 * - GUI: when using tabs, focus in terminal, click on tab does not work.
69 * - GUI: when 'confirm' is set and trying to exit Vim, dialog offers to save
70 * changes to "!shell".
71 * (justrajdeep, 2017 Aug 22)
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020072 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020073 * - For the GUI fill termios with default values, perhaps like pangoterm:
74 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020075 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
76 * conversions.
77 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
78 * the window and position it higher up when it gets filled, so it looks like
79 * the text scrolls up.
80 * - Copy text in the vterm to the Vim buffer once in a while, so that
81 * completion works.
82 * - add an optional limit for the scrollback size. When reaching it remove
83 * 10% at the start.
84 */
85
86#include "vim.h"
87
88#if defined(FEAT_TERMINAL) || defined(PROTO)
89
90#ifndef MIN
91# define MIN(x,y) ((x) < (y) ? (x) : (y))
92#endif
93#ifndef MAX
94# define MAX(x,y) ((x) > (y) ? (x) : (y))
95#endif
96
97#include "libvterm/include/vterm.h"
98
99/* This is VTermScreenCell without the characters, thus much smaller. */
100typedef struct {
101 VTermScreenCellAttrs attrs;
102 char width;
103 VTermColor fg, bg;
104} 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
157 VTermPos tl_cursor_pos;
158 int tl_cursor_visible;
159 int tl_cursor_blink;
160 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
161 char_u *tl_cursor_color; /* NULL or allocated */
162
163 int tl_using_altscreen;
164};
165
166#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
167#define TMODE_LOOP 2 /* CTRL-W N used */
168
169/*
170 * List of all active terminals.
171 */
172static term_T *first_term = NULL;
173
174/* Terminal active in terminal_loop(). */
175static term_T *in_terminal_loop = NULL;
176
177#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
178#define KEY_BUF_LEN 200
179
180/*
181 * Functions with separate implementation for MS-Windows and Unix-like systems.
182 */
183static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
184static int create_pty_only(term_T *term, jobopt_T *opt);
185static void term_report_winsize(term_T *term, int rows, int cols);
186static void term_free_vterm(term_T *term);
187
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100188/* The character that we know (or assume) that the terminal expects for the
189 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200191
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100192/* "Terminal" highlight group colors. */
193static int term_default_cterm_fg = -1;
194static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200195
196/**************************************
197 * 1. Generic code for all systems.
198 */
199
200/*
201 * Determine the terminal size from 'termsize' and the current window.
202 * Assumes term->tl_rows and term->tl_cols are zero.
203 */
204 static void
205set_term_and_win_size(term_T *term)
206{
207 if (*curwin->w_p_tms != NUL)
208 {
209 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
210
211 term->tl_rows = atoi((char *)curwin->w_p_tms);
212 term->tl_cols = atoi((char *)p);
213 }
214 if (term->tl_rows == 0)
215 term->tl_rows = curwin->w_height;
216 else
217 {
218 win_setheight_win(term->tl_rows, curwin);
219 term->tl_rows_fixed = TRUE;
220 }
221 if (term->tl_cols == 0)
222 term->tl_cols = curwin->w_width;
223 else
224 {
225 win_setwidth_win(term->tl_cols, curwin);
226 term->tl_cols_fixed = TRUE;
227 }
228}
229
230/*
231 * Initialize job options for a terminal job.
232 * Caller may overrule some of them.
233 */
234 static void
235init_job_options(jobopt_T *opt)
236{
237 clear_job_options(opt);
238
239 opt->jo_mode = MODE_RAW;
240 opt->jo_out_mode = MODE_RAW;
241 opt->jo_err_mode = MODE_RAW;
242 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
243}
244
245/*
246 * Set job options mandatory for a terminal job.
247 */
248 static void
249setup_job_options(jobopt_T *opt, int rows, int cols)
250{
251 if (!(opt->jo_set & JO_OUT_IO))
252 {
253 /* Connect stdout to the terminal. */
254 opt->jo_io[PART_OUT] = JIO_BUFFER;
255 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
256 opt->jo_modifiable[PART_OUT] = 0;
257 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
258 }
259
260 if (!(opt->jo_set & JO_ERR_IO))
261 {
262 /* Connect stderr to the terminal. */
263 opt->jo_io[PART_ERR] = JIO_BUFFER;
264 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
265 opt->jo_modifiable[PART_ERR] = 0;
266 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
267 }
268
269 opt->jo_pty = TRUE;
270 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
271 opt->jo_term_rows = rows;
272 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
273 opt->jo_term_cols = cols;
274}
275
276/*
277 * Start a terminal window and return its buffer.
278 * Returns NULL when failed.
279 */
280 static buf_T *
281term_start(typval_T *argvar, jobopt_T *opt, int forceit)
282{
283 exarg_T split_ea;
284 win_T *old_curwin = curwin;
285 term_T *term;
286 buf_T *old_curbuf = NULL;
287 int res;
288 buf_T *newbuf;
289
290 if (check_restricted() || check_secure())
291 return NULL;
292
293 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
294 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
295 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
296 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
297 {
298 EMSG(_(e_invarg));
299 return NULL;
300 }
301
302 term = (term_T *)alloc_clear(sizeof(term_T));
303 if (term == NULL)
304 return NULL;
305 term->tl_dirty_row_end = MAX_ROW;
306 term->tl_cursor_visible = TRUE;
307 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
308 term->tl_finish = opt->jo_term_finish;
309 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
310
311 vim_memset(&split_ea, 0, sizeof(split_ea));
312 if (opt->jo_curwin)
313 {
314 /* Create a new buffer in the current window. */
315 if (!can_abandon(curbuf, forceit))
316 {
317 no_write_message();
318 vim_free(term);
319 return NULL;
320 }
321 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
322 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
323 {
324 vim_free(term);
325 return NULL;
326 }
327 }
328 else if (opt->jo_hidden)
329 {
330 buf_T *buf;
331
332 /* Create a new buffer without a window. Make it the current buffer for
333 * a moment to be able to do the initialisations. */
334 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
335 BLN_NEW | BLN_LISTED);
336 if (buf == NULL || ml_open(buf) == FAIL)
337 {
338 vim_free(term);
339 return NULL;
340 }
341 old_curbuf = curbuf;
342 --curbuf->b_nwindows;
343 curbuf = buf;
344 curwin->w_buffer = buf;
345 ++curbuf->b_nwindows;
346 }
347 else
348 {
349 /* Open a new window or tab. */
350 split_ea.cmdidx = CMD_new;
351 split_ea.cmd = (char_u *)"new";
352 split_ea.arg = (char_u *)"";
353 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
354 {
355 split_ea.line2 = opt->jo_term_rows;
356 split_ea.addr_count = 1;
357 }
358 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
359 {
360 split_ea.line2 = opt->jo_term_cols;
361 split_ea.addr_count = 1;
362 }
363
364 ex_splitview(&split_ea);
365 if (curwin == old_curwin)
366 {
367 /* split failed */
368 vim_free(term);
369 return NULL;
370 }
371 }
372 term->tl_buffer = curbuf;
373 curbuf->b_term = term;
374
375 if (!opt->jo_hidden)
376 {
377 /* only one size was taken care of with :new, do the other one */
378 if (opt->jo_term_rows > 0 && (cmdmod.split & WSP_VERT))
379 win_setheight(opt->jo_term_rows);
380 if (opt->jo_term_cols > 0 && !(cmdmod.split & WSP_VERT))
381 win_setwidth(opt->jo_term_cols);
382 }
383
384 /* Link the new terminal in the list of active terminals. */
385 term->tl_next = first_term;
386 first_term = term;
387
388 if (opt->jo_term_name != NULL)
389 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
390 else
391 {
392 int i;
393 size_t len;
394 char_u *cmd, *p;
395
396 if (argvar->v_type == VAR_STRING)
397 {
398 cmd = argvar->vval.v_string;
399 if (cmd == NULL)
400 cmd = (char_u *)"";
401 else if (STRCMP(cmd, "NONE") == 0)
402 cmd = (char_u *)"pty";
403 }
404 else if (argvar->v_type != VAR_LIST
405 || argvar->vval.v_list == NULL
406 || argvar->vval.v_list->lv_len < 1
407 || (cmd = get_tv_string_chk(
408 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
409 cmd = (char_u*)"";
410
411 len = STRLEN(cmd) + 10;
412 p = alloc((int)len);
413
414 for (i = 0; p != NULL; ++i)
415 {
416 /* Prepend a ! to the command name to avoid the buffer name equals
417 * the executable, otherwise ":w!" would overwrite it. */
418 if (i == 0)
419 vim_snprintf((char *)p, len, "!%s", cmd);
420 else
421 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
422 if (buflist_findname(p) == NULL)
423 {
424 vim_free(curbuf->b_ffname);
425 curbuf->b_ffname = p;
426 break;
427 }
428 }
429 }
430 curbuf->b_fname = curbuf->b_ffname;
431
432 if (opt->jo_term_opencmd != NULL)
433 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
434
435 if (opt->jo_eof_chars != NULL)
436 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
437
438 set_string_option_direct((char_u *)"buftype", -1,
439 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
440
441 /* Mark the buffer as not modifiable. It can only be made modifiable after
442 * the job finished. */
443 curbuf->b_p_ma = FALSE;
444
445 set_term_and_win_size(term);
446 setup_job_options(opt, term->tl_rows, term->tl_cols);
447
448 /* System dependent: setup the vterm and maybe start the job in it. */
449 if (argvar->v_type == VAR_STRING
450 && argvar->vval.v_string != NULL
451 && STRCMP(argvar->vval.v_string, "NONE") == 0)
452 res = create_pty_only(term, opt);
453 else
454 res = term_and_job_init(term, argvar, opt);
455
456 newbuf = curbuf;
457 if (res == OK)
458 {
459 /* Get and remember the size we ended up with. Update the pty. */
460 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
461 term_report_winsize(term, term->tl_rows, term->tl_cols);
462
463 /* Make sure we don't get stuck on sending keys to the job, it leads to
464 * a deadlock if the job is waiting for Vim to read. */
465 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
466
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200467#ifdef FEAT_AUTOCMD
468 ++curbuf->b_locked;
469 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
470 --curbuf->b_locked;
471#endif
472
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200473 if (old_curbuf != NULL)
474 {
475 --curbuf->b_nwindows;
476 curbuf = old_curbuf;
477 curwin->w_buffer = curbuf;
478 ++curbuf->b_nwindows;
479 }
480 }
481 else
482 {
483 buf_T *buf = curbuf;
484
485 free_terminal(curbuf);
486 if (old_curbuf != NULL)
487 {
488 --curbuf->b_nwindows;
489 curbuf = old_curbuf;
490 curwin->w_buffer = curbuf;
491 ++curbuf->b_nwindows;
492 }
493
494 /* Wiping out the buffer will also close the window and call
495 * free_terminal(). */
496 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
497 return NULL;
498 }
499 return newbuf;
500}
501
502/*
503 * ":terminal": open a terminal window and execute a job in it.
504 */
505 void
506ex_terminal(exarg_T *eap)
507{
508 typval_T argvar[2];
509 jobopt_T opt;
510 char_u *cmd;
511 char_u *tofree = NULL;
512
513 init_job_options(&opt);
514
515 cmd = eap->arg;
516 while (*cmd && *cmd == '+' && *(cmd + 1) == '+')
517 {
518 char_u *p, *ep;
519
520 cmd += 2;
521 p = skiptowhite(cmd);
522 ep = vim_strchr(cmd, '=');
523 if (ep != NULL && ep < p)
524 p = ep;
525
526 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
527 opt.jo_term_finish = 'c';
528 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
529 opt.jo_term_finish = 'o';
530 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
531 opt.jo_curwin = 1;
532 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
533 opt.jo_hidden = 1;
534 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
535 && ep != NULL && isdigit(ep[1]))
536 {
537 opt.jo_set2 |= JO2_TERM_ROWS;
538 opt.jo_term_rows = atoi((char *)ep + 1);
539 p = skiptowhite(cmd);
540 }
541 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
542 && ep != NULL && isdigit(ep[1]))
543 {
544 opt.jo_set2 |= JO2_TERM_COLS;
545 opt.jo_term_cols = atoi((char *)ep + 1);
546 p = skiptowhite(cmd);
547 }
548 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
549 && ep != NULL)
550 {
551 char_u *buf = NULL;
552 char_u *keys;
553
554 p = skiptowhite(cmd);
555 *p = NUL;
556 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
557 opt.jo_set2 |= JO2_EOF_CHARS;
558 opt.jo_eof_chars = vim_strsave(keys);
559 vim_free(buf);
560 *p = ' ';
561 }
562 else
563 {
564 if (*p)
565 *p = NUL;
566 EMSG2(_("E181: Invalid attribute: %s"), cmd);
567 return;
568 }
569 cmd = skipwhite(p);
570 }
571 if (*cmd == NUL)
572 /* Make a copy of 'shell', an autocommand may change the option. */
573 tofree = cmd = vim_strsave(p_sh);
574
575 if (eap->addr_count > 0)
576 {
577 /* Write lines from current buffer to the job. */
578 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
579 opt.jo_io[PART_IN] = JIO_BUFFER;
580 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
581 opt.jo_in_top = eap->line1;
582 opt.jo_in_bot = eap->line2;
583 }
584
585 argvar[0].v_type = VAR_STRING;
586 argvar[0].vval.v_string = cmd;
587 argvar[1].v_type = VAR_UNKNOWN;
588 term_start(argvar, &opt, eap->forceit);
589 vim_free(tofree);
590 vim_free(opt.jo_eof_chars);
591}
592
593/*
594 * Free the scrollback buffer for "term".
595 */
596 static void
597free_scrollback(term_T *term)
598{
599 int i;
600
601 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
602 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
603 ga_clear(&term->tl_scrollback);
604}
605
606/*
607 * Free a terminal and everything it refers to.
608 * Kills the job if there is one.
609 * Called when wiping out a buffer.
610 */
611 void
612free_terminal(buf_T *buf)
613{
614 term_T *term = buf->b_term;
615 term_T *tp;
616
617 if (term == NULL)
618 return;
619 if (first_term == term)
620 first_term = term->tl_next;
621 else
622 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
623 if (tp->tl_next == term)
624 {
625 tp->tl_next = term->tl_next;
626 break;
627 }
628
629 if (term->tl_job != NULL)
630 {
631 if (term->tl_job->jv_status != JOB_ENDED
632 && term->tl_job->jv_status != JOB_FINISHED
633 && term->tl_job->jv_status != JOB_FAILED)
634 job_stop(term->tl_job, NULL, "kill");
635 job_unref(term->tl_job);
636 }
637
638 free_scrollback(term);
639
640 term_free_vterm(term);
641 vim_free(term->tl_title);
642 vim_free(term->tl_status_text);
643 vim_free(term->tl_opencmd);
644 vim_free(term->tl_eof_chars);
645 vim_free(term->tl_cursor_color);
646 vim_free(term);
647 buf->b_term = NULL;
648 if (in_terminal_loop == term)
649 in_terminal_loop = NULL;
650}
651
652/*
653 * Write job output "msg[len]" to the vterm.
654 */
655 static void
656term_write_job_output(term_T *term, char_u *msg, size_t len)
657{
658 VTerm *vterm = term->tl_vterm;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200659
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100660 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200661
662 /* this invokes the damage callbacks */
663 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
664}
665
666 static void
667update_cursor(term_T *term, int redraw)
668{
669 if (term->tl_normal_mode)
670 return;
671 setcursor();
672 if (redraw)
673 {
674 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
675 cursor_on();
676 out_flush();
677#ifdef FEAT_GUI
678 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100679 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200680 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100681 gui_mch_flush();
682 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200683#endif
684 }
685}
686
687/*
688 * Invoked when "msg" output from a job was received. Write it to the terminal
689 * of "buffer".
690 */
691 void
692write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
693{
694 size_t len = STRLEN(msg);
695 term_T *term = buffer->b_term;
696
697 if (term->tl_vterm == NULL)
698 {
699 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
700 return;
701 }
702 ch_log(channel, "writing %d bytes to terminal", (int)len);
703 term_write_job_output(term, msg, len);
704
705 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
706 * contents, thus no screen update is needed. */
707 if (!term->tl_normal_mode)
708 {
709 /* TODO: only update once in a while. */
710 ch_log(term->tl_job->jv_channel, "updating screen");
711 if (buffer == curbuf)
712 {
713 update_screen(0);
714 update_cursor(term, TRUE);
715 }
716 else
717 redraw_after_callback(TRUE);
718 }
719}
720
721/*
722 * Send a mouse position and click to the vterm
723 */
724 static int
725term_send_mouse(VTerm *vterm, int button, int pressed)
726{
727 VTermModifier mod = VTERM_MOD_NONE;
728
729 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200730 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100731 if (button != 0)
732 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200733 return TRUE;
734}
735
736/*
737 * Convert typed key "c" into bytes to send to the job.
738 * Return the number of bytes in "buf".
739 */
740 static int
741term_convert_key(term_T *term, int c, char *buf)
742{
743 VTerm *vterm = term->tl_vterm;
744 VTermKey key = VTERM_KEY_NONE;
745 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100746 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200747
748 switch (c)
749 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100750 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
751
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200752 /* don't use VTERM_KEY_BACKSPACE, it always
753 * becomes 0x7f DEL */
754 case K_BS: c = term_backspace_char; break;
755
756 case ESC: key = VTERM_KEY_ESCAPE; break;
757 case K_DEL: key = VTERM_KEY_DEL; break;
758 case K_DOWN: key = VTERM_KEY_DOWN; break;
759 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
760 key = VTERM_KEY_DOWN; break;
761 case K_END: key = VTERM_KEY_END; break;
762 case K_S_END: mod = VTERM_MOD_SHIFT;
763 key = VTERM_KEY_END; break;
764 case K_C_END: mod = VTERM_MOD_CTRL;
765 key = VTERM_KEY_END; break;
766 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
767 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
768 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
769 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
770 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
771 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
772 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
773 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
774 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
775 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
776 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
777 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
778 case K_HOME: key = VTERM_KEY_HOME; break;
779 case K_S_HOME: mod = VTERM_MOD_SHIFT;
780 key = VTERM_KEY_HOME; break;
781 case K_C_HOME: mod = VTERM_MOD_CTRL;
782 key = VTERM_KEY_HOME; break;
783 case K_INS: key = VTERM_KEY_INS; break;
784 case K_K0: key = VTERM_KEY_KP_0; break;
785 case K_K1: key = VTERM_KEY_KP_1; break;
786 case K_K2: key = VTERM_KEY_KP_2; break;
787 case K_K3: key = VTERM_KEY_KP_3; break;
788 case K_K4: key = VTERM_KEY_KP_4; break;
789 case K_K5: key = VTERM_KEY_KP_5; break;
790 case K_K6: key = VTERM_KEY_KP_6; break;
791 case K_K7: key = VTERM_KEY_KP_7; break;
792 case K_K8: key = VTERM_KEY_KP_8; break;
793 case K_K9: key = VTERM_KEY_KP_9; break;
794 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
795 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
796 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
797 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
798 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
799 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
800 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
801 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
802 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
803 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
804 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
805 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
806 case K_LEFT: key = VTERM_KEY_LEFT; break;
807 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
808 key = VTERM_KEY_LEFT; break;
809 case K_C_LEFT: mod = VTERM_MOD_CTRL;
810 key = VTERM_KEY_LEFT; break;
811 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
812 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
813 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
814 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
815 key = VTERM_KEY_RIGHT; break;
816 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
817 key = VTERM_KEY_RIGHT; break;
818 case K_UP: key = VTERM_KEY_UP; break;
819 case K_S_UP: mod = VTERM_MOD_SHIFT;
820 key = VTERM_KEY_UP; break;
821 case TAB: key = VTERM_KEY_TAB; break;
822
Bram Moolenaara42ad572017-11-16 13:08:04 +0100823 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
824 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200825 case K_MOUSELEFT: /* TODO */ return 0;
826 case K_MOUSERIGHT: /* TODO */ return 0;
827
828 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100829 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
830 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200831 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100832 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100833 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100834 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
835 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
836 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
837 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
838 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
839 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200840 case K_X1MOUSE: /* TODO */ return 0;
841 case K_X1DRAG: /* TODO */ return 0;
842 case K_X1RELEASE: /* TODO */ return 0;
843 case K_X2MOUSE: /* TODO */ return 0;
844 case K_X2DRAG: /* TODO */ return 0;
845 case K_X2RELEASE: /* TODO */ return 0;
846
847 case K_IGNORE: return 0;
848 case K_NOP: return 0;
849 case K_UNDO: return 0;
850 case K_HELP: return 0;
851 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
852 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
853 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
854 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
855 case K_SELECT: return 0;
856#ifdef FEAT_GUI
857 case K_VER_SCROLLBAR: return 0;
858 case K_HOR_SCROLLBAR: return 0;
859#endif
860#ifdef FEAT_GUI_TABLINE
861 case K_TABLINE: return 0;
862 case K_TABMENU: return 0;
863#endif
864#ifdef FEAT_NETBEANS_INTG
865 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
866#endif
867#ifdef FEAT_DND
868 case K_DROP: return 0;
869#endif
870#ifdef FEAT_AUTOCMD
871 case K_CURSORHOLD: return 0;
872#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100873 case K_PS: vterm_keyboard_start_paste(vterm);
874 other = TRUE;
875 break;
876 case K_PE: vterm_keyboard_end_paste(vterm);
877 other = TRUE;
878 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200879 }
880
881 /*
882 * Convert special keys to vterm keys:
883 * - Write keys to vterm: vterm_keyboard_key()
884 * - Write output to channel.
885 * TODO: use mod_mask
886 */
887 if (key != VTERM_KEY_NONE)
888 /* Special key, let vterm convert it. */
889 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100890 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200891 /* Normal character, let vterm convert it. */
892 vterm_keyboard_unichar(vterm, c, mod);
893
894 /* Read back the converted escape sequence. */
895 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
896}
897
898/*
899 * Return TRUE if the job for "term" is still running.
900 */
901 int
902term_job_running(term_T *term)
903{
904 /* Also consider the job finished when the channel is closed, to avoid a
905 * race condition when updating the title. */
906 return term != NULL
907 && term->tl_job != NULL
908 && channel_is_open(term->tl_job->jv_channel)
909 && (term->tl_job->jv_status == JOB_STARTED
910 || term->tl_job->jv_channel->ch_keep_open);
911}
912
913/*
914 * Return TRUE if "term" has an active channel and used ":term NONE".
915 */
916 int
917term_none_open(term_T *term)
918{
919 /* Also consider the job finished when the channel is closed, to avoid a
920 * race condition when updating the title. */
921 return term != NULL
922 && term->tl_job != NULL
923 && channel_is_open(term->tl_job->jv_channel)
924 && term->tl_job->jv_channel->ch_keep_open;
925}
926
927/*
928 * Add the last line of the scrollback buffer to the buffer in the window.
929 */
930 static void
931add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
932{
933 buf_T *buf = term->tl_buffer;
934 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
935 linenr_T lnum = buf->b_ml.ml_line_count;
936
937#ifdef WIN3264
938 if (!enc_utf8 && enc_codepage > 0)
939 {
940 WCHAR *ret = NULL;
941 int length = 0;
942
943 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
944 &ret, &length);
945 if (ret != NULL)
946 {
947 WideCharToMultiByte_alloc(enc_codepage, 0,
948 ret, length, (char **)&text, &len, 0, 0);
949 vim_free(ret);
950 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
951 vim_free(text);
952 }
953 }
954 else
955#endif
956 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
957 if (empty)
958 {
959 /* Delete the empty line that was in the empty buffer. */
960 curbuf = buf;
961 ml_delete(1, FALSE);
962 curbuf = curwin->w_buffer;
963 }
964}
965
966 static void
967cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
968{
969 attr->width = cell->width;
970 attr->attrs = cell->attrs;
971 attr->fg = cell->fg;
972 attr->bg = cell->bg;
973}
974
975 static int
976equal_celattr(cellattr_T *a, cellattr_T *b)
977{
978 /* Comparing the colors should be sufficient. */
979 return a->fg.red == b->fg.red
980 && a->fg.green == b->fg.green
981 && a->fg.blue == b->fg.blue
982 && a->bg.red == b->bg.red
983 && a->bg.green == b->bg.green
984 && a->bg.blue == b->bg.blue;
985}
986
987
988/*
989 * Add the current lines of the terminal to scrollback and to the buffer.
990 * Called after the job has ended and when switching to Terminal-Normal mode.
991 */
992 static void
993move_terminal_to_buffer(term_T *term)
994{
995 win_T *wp;
996 int len;
997 int lines_skipped = 0;
998 VTermPos pos;
999 VTermScreenCell cell;
1000 cellattr_T fill_attr, new_fill_attr;
1001 cellattr_T *p;
1002 VTermScreen *screen;
1003
1004 if (term->tl_vterm == NULL)
1005 return;
1006 screen = vterm_obtain_screen(term->tl_vterm);
1007 fill_attr = new_fill_attr = term->tl_default_color;
1008
1009 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1010 {
1011 len = 0;
1012 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1013 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1014 && cell.chars[0] != NUL)
1015 {
1016 len = pos.col + 1;
1017 new_fill_attr = term->tl_default_color;
1018 }
1019 else
1020 /* Assume the last attr is the filler attr. */
1021 cell2cellattr(&cell, &new_fill_attr);
1022
1023 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1024 ++lines_skipped;
1025 else
1026 {
1027 while (lines_skipped > 0)
1028 {
1029 /* Line was skipped, add an empty line. */
1030 --lines_skipped;
1031 if (ga_grow(&term->tl_scrollback, 1) == OK)
1032 {
1033 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1034 + term->tl_scrollback.ga_len;
1035
1036 line->sb_cols = 0;
1037 line->sb_cells = NULL;
1038 line->sb_fill_attr = fill_attr;
1039 ++term->tl_scrollback.ga_len;
1040
1041 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1042 }
1043 }
1044
1045 if (len == 0)
1046 p = NULL;
1047 else
1048 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1049 if ((p != NULL || len == 0)
1050 && ga_grow(&term->tl_scrollback, 1) == OK)
1051 {
1052 garray_T ga;
1053 int width;
1054 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1055 + term->tl_scrollback.ga_len;
1056
1057 ga_init2(&ga, 1, 100);
1058 for (pos.col = 0; pos.col < len; pos.col += width)
1059 {
1060 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1061 {
1062 width = 1;
1063 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1064 if (ga_grow(&ga, 1) == OK)
1065 ga.ga_len += utf_char2bytes(' ',
1066 (char_u *)ga.ga_data + ga.ga_len);
1067 }
1068 else
1069 {
1070 width = cell.width;
1071
1072 cell2cellattr(&cell, &p[pos.col]);
1073
1074 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1075 {
1076 int i;
1077 int c;
1078
1079 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1080 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1081 (char_u *)ga.ga_data + ga.ga_len);
1082 }
1083 }
1084 }
1085 line->sb_cols = len;
1086 line->sb_cells = p;
1087 line->sb_fill_attr = new_fill_attr;
1088 fill_attr = new_fill_attr;
1089 ++term->tl_scrollback.ga_len;
1090
1091 if (ga_grow(&ga, 1) == FAIL)
1092 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1093 else
1094 {
1095 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1096 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1097 }
1098 ga_clear(&ga);
1099 }
1100 else
1101 vim_free(p);
1102 }
1103 }
1104
1105 /* Obtain the current background color. */
1106 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1107 &term->tl_default_color.fg, &term->tl_default_color.bg);
1108
1109 FOR_ALL_WINDOWS(wp)
1110 {
1111 if (wp->w_buffer == term->tl_buffer)
1112 {
1113 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1114 wp->w_cursor.col = 0;
1115 wp->w_valid = 0;
1116 if (wp->w_cursor.lnum >= wp->w_height)
1117 {
1118 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1119
1120 if (wp->w_topline < min_topline)
1121 wp->w_topline = min_topline;
1122 }
1123 redraw_win_later(wp, NOT_VALID);
1124 }
1125 }
1126}
1127
1128 static void
1129set_terminal_mode(term_T *term, int normal_mode)
1130{
1131 term->tl_normal_mode = normal_mode;
1132 vim_free(term->tl_status_text);
1133 term->tl_status_text = NULL;
1134 if (term->tl_buffer == curbuf)
1135 maketitle();
1136}
1137
1138/*
1139 * Called after the job if finished and Terminal mode is not active:
1140 * Move the vterm contents into the scrollback buffer and free the vterm.
1141 */
1142 static void
1143cleanup_vterm(term_T *term)
1144{
1145 if (term->tl_finish != 'c')
1146 move_terminal_to_buffer(term);
1147 term_free_vterm(term);
1148 set_terminal_mode(term, FALSE);
1149}
1150
1151/*
1152 * Switch from Terminal-Job mode to Terminal-Normal mode.
1153 * Suspends updating the terminal window.
1154 */
1155 static void
1156term_enter_normal_mode(void)
1157{
1158 term_T *term = curbuf->b_term;
1159
1160 /* Append the current terminal contents to the buffer. */
1161 move_terminal_to_buffer(term);
1162
1163 set_terminal_mode(term, TRUE);
1164
1165 /* Move the window cursor to the position of the cursor in the
1166 * terminal. */
1167 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1168 + term->tl_cursor_pos.row + 1;
1169 check_cursor();
1170 coladvance(term->tl_cursor_pos.col);
1171
1172 /* Display the same lines as in the terminal. */
1173 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1174}
1175
1176/*
1177 * Returns TRUE if the current window contains a terminal and we are in
1178 * Terminal-Normal mode.
1179 */
1180 int
1181term_in_normal_mode(void)
1182{
1183 term_T *term = curbuf->b_term;
1184
1185 return term != NULL && term->tl_normal_mode;
1186}
1187
1188/*
1189 * Switch from Terminal-Normal mode to Terminal-Job mode.
1190 * Restores updating the terminal window.
1191 */
1192 void
1193term_enter_job_mode()
1194{
1195 term_T *term = curbuf->b_term;
1196 sb_line_T *line;
1197 garray_T *gap;
1198
1199 /* Remove the terminal contents from the scrollback and the buffer. */
1200 gap = &term->tl_scrollback;
1201 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1202 && gap->ga_len > 0)
1203 {
1204 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1205 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1206 vim_free(line->sb_cells);
1207 --gap->ga_len;
1208 }
1209 check_cursor();
1210
1211 set_terminal_mode(term, FALSE);
1212
1213 if (term->tl_channel_closed)
1214 cleanup_vterm(term);
1215 redraw_buf_and_status_later(curbuf, NOT_VALID);
1216}
1217
1218/*
1219 * Get a key from the user without mapping.
1220 * Note: while waiting a terminal may be closed and freed if the channel is
1221 * closed and ++close was used.
1222 * Uses terminal mode mappings.
1223 */
1224 static int
1225term_vgetc()
1226{
1227 int c;
1228 int save_State = State;
1229
1230 State = TERMINAL;
1231 got_int = FALSE;
1232#ifdef WIN3264
1233 ctrl_break_was_pressed = FALSE;
1234#endif
1235 c = vgetc();
1236 got_int = FALSE;
1237 State = save_State;
1238 return c;
1239}
1240
1241/*
1242 * Get the part that is connected to the tty. Normally this is PART_IN, but
1243 * when writing buffer lines to the job it can be another. This makes it
1244 * possible to do "1,5term vim -".
1245 */
1246 static ch_part_T
1247get_tty_part(term_T *term)
1248{
1249#ifdef UNIX
1250 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1251 int i;
1252
1253 for (i = 0; i < 3; ++i)
1254 {
1255 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1256
1257 if (isatty(fd))
1258 return parts[i];
1259 }
1260#endif
1261 return PART_IN;
1262}
1263
1264/*
1265 * Send keys to terminal.
1266 * Return FAIL when the key needs to be handled in Normal mode.
1267 * Return OK when the key was dropped or sent to the terminal.
1268 */
1269 int
1270send_keys_to_term(term_T *term, int c, int typed)
1271{
1272 char msg[KEY_BUF_LEN];
1273 size_t len;
1274 static int mouse_was_outside = FALSE;
1275 int dragging_outside = FALSE;
1276
1277 /* Catch keys that need to be handled as in Normal mode. */
1278 switch (c)
1279 {
1280 case NUL:
1281 case K_ZERO:
1282 if (typed)
1283 stuffcharReadbuff(c);
1284 return FAIL;
1285
1286 case K_IGNORE:
1287 return FAIL;
1288
1289 case K_LEFTDRAG:
1290 case K_MIDDLEDRAG:
1291 case K_RIGHTDRAG:
1292 case K_X1DRAG:
1293 case K_X2DRAG:
1294 dragging_outside = mouse_was_outside;
1295 /* FALLTHROUGH */
1296 case K_LEFTMOUSE:
1297 case K_LEFTMOUSE_NM:
1298 case K_LEFTRELEASE:
1299 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001300 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001301 case K_MIDDLEMOUSE:
1302 case K_MIDDLERELEASE:
1303 case K_RIGHTMOUSE:
1304 case K_RIGHTRELEASE:
1305 case K_X1MOUSE:
1306 case K_X1RELEASE:
1307 case K_X2MOUSE:
1308 case K_X2RELEASE:
1309
1310 case K_MOUSEUP:
1311 case K_MOUSEDOWN:
1312 case K_MOUSELEFT:
1313 case K_MOUSERIGHT:
1314 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001315 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001316 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001317 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001318 || dragging_outside)
1319 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001320 /* click or scroll outside the current window or on status line
1321 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001322 if (typed)
1323 {
1324 stuffcharReadbuff(c);
1325 mouse_was_outside = TRUE;
1326 }
1327 return FAIL;
1328 }
1329 }
1330 if (typed)
1331 mouse_was_outside = FALSE;
1332
1333 /* Convert the typed key to a sequence of bytes for the job. */
1334 len = term_convert_key(term, c, msg);
1335 if (len > 0)
1336 /* TODO: if FAIL is returned, stop? */
1337 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1338 (char_u *)msg, (int)len, NULL);
1339
1340 return OK;
1341}
1342
1343 static void
1344position_cursor(win_T *wp, VTermPos *pos)
1345{
1346 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1347 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1348 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1349}
1350
1351/*
1352 * Handle CTRL-W "": send register contents to the job.
1353 */
1354 static void
1355term_paste_register(int prev_c UNUSED)
1356{
1357 int c;
1358 list_T *l;
1359 listitem_T *item;
1360 long reglen = 0;
1361 int type;
1362
1363#ifdef FEAT_CMDL_INFO
1364 if (add_to_showcmd(prev_c))
1365 if (add_to_showcmd('"'))
1366 out_flush();
1367#endif
1368 c = term_vgetc();
1369#ifdef FEAT_CMDL_INFO
1370 clear_showcmd();
1371#endif
1372 if (!term_use_loop())
1373 /* job finished while waiting for a character */
1374 return;
1375
1376 /* CTRL-W "= prompt for expression to evaluate. */
1377 if (c == '=' && get_expr_register() != '=')
1378 return;
1379 if (!term_use_loop())
1380 /* job finished while waiting for a character */
1381 return;
1382
1383 l = (list_T *)get_reg_contents(c, GREG_LIST);
1384 if (l != NULL)
1385 {
1386 type = get_reg_type(c, &reglen);
1387 for (item = l->lv_first; item != NULL; item = item->li_next)
1388 {
1389 char_u *s = get_tv_string(&item->li_tv);
1390#ifdef WIN3264
1391 char_u *tmp = s;
1392
1393 if (!enc_utf8 && enc_codepage > 0)
1394 {
1395 WCHAR *ret = NULL;
1396 int length = 0;
1397
1398 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1399 (int)STRLEN(s), &ret, &length);
1400 if (ret != NULL)
1401 {
1402 WideCharToMultiByte_alloc(CP_UTF8, 0,
1403 ret, length, (char **)&s, &length, 0, 0);
1404 vim_free(ret);
1405 }
1406 }
1407#endif
1408 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1409 s, (int)STRLEN(s), NULL);
1410#ifdef WIN3264
1411 if (tmp != s)
1412 vim_free(s);
1413#endif
1414
1415 if (item->li_next != NULL || type == MLINE)
1416 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1417 (char_u *)"\r", 1, NULL);
1418 }
1419 list_free(l);
1420 }
1421}
1422
1423#if defined(FEAT_GUI) || defined(PROTO)
1424/*
1425 * Return TRUE when the cursor of the terminal should be displayed.
1426 */
1427 int
1428terminal_is_active()
1429{
1430 return in_terminal_loop != NULL;
1431}
1432
1433 cursorentry_T *
1434term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1435{
1436 term_T *term = in_terminal_loop;
1437 static cursorentry_T entry;
1438
1439 vim_memset(&entry, 0, sizeof(entry));
1440 entry.shape = entry.mshape =
1441 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1442 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1443 SHAPE_BLOCK;
1444 entry.percentage = 20;
1445 if (term->tl_cursor_blink)
1446 {
1447 entry.blinkwait = 700;
1448 entry.blinkon = 400;
1449 entry.blinkoff = 250;
1450 }
1451 *fg = gui.back_pixel;
1452 if (term->tl_cursor_color == NULL)
1453 *bg = gui.norm_pixel;
1454 else
1455 *bg = color_name2handle(term->tl_cursor_color);
1456 entry.name = "n";
1457 entry.used_for = SHAPE_CURSOR;
1458
1459 return &entry;
1460}
1461#endif
1462
1463static int did_change_cursor = FALSE;
1464
1465 static void
1466may_set_cursor_props(term_T *term)
1467{
1468#ifdef FEAT_GUI
1469 /* For the GUI the cursor properties are obtained with
1470 * term_get_cursor_shape(). */
1471 if (gui.in_use)
1472 return;
1473#endif
1474 if (in_terminal_loop == term)
1475 {
1476 did_change_cursor = TRUE;
1477 if (term->tl_cursor_color != NULL)
1478 term_cursor_color(term->tl_cursor_color);
1479 else
1480 term_cursor_color((char_u *)"");
1481 term_cursor_shape(term->tl_cursor_shape, term->tl_cursor_blink);
1482 }
1483}
1484
1485 static void
1486may_restore_cursor_props(void)
1487{
1488#ifdef FEAT_GUI
1489 if (gui.in_use)
1490 return;
1491#endif
1492 if (did_change_cursor)
1493 {
1494 did_change_cursor = FALSE;
1495 term_cursor_color((char_u *)"");
1496 /* this will restore the initial cursor style, if possible */
1497 ui_cursor_shape_forced(TRUE);
1498 }
1499}
1500
1501/*
1502 * Returns TRUE if the current window contains a terminal and we are sending
1503 * keys to the job.
1504 */
1505 int
1506term_use_loop(void)
1507{
1508 term_T *term = curbuf->b_term;
1509
1510 return term != NULL
1511 && !term->tl_normal_mode
1512 && term->tl_vterm != NULL
1513 && term_job_running(term);
1514}
1515
1516/*
1517 * Wait for input and send it to the job.
1518 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1519 * when there is no more typahead.
1520 * Return when the start of a CTRL-W command is typed or anything else that
1521 * should be handled as a Normal mode command.
1522 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1523 * the terminal was closed.
1524 */
1525 int
1526terminal_loop(int blocking)
1527{
1528 int c;
1529 int termkey = 0;
1530 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001531#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001532 int tty_fd = curbuf->b_term->tl_job->jv_channel
1533 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001534#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001535
1536 /* Remember the terminal we are sending keys to. However, the terminal
1537 * might be closed while waiting for a character, e.g. typing "exit" in a
1538 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1539 * stored reference. */
1540 in_terminal_loop = curbuf->b_term;
1541
1542 if (*curwin->w_p_tk != NUL)
1543 termkey = string_to_key(curwin->w_p_tk, TRUE);
1544 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1545 may_set_cursor_props(curbuf->b_term);
1546
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001547 while (blocking || vpeekc() != NUL)
1548 {
1549 /* TODO: skip screen update when handling a sequence of keys. */
1550 /* Repeat redrawing in case a message is received while redrawing. */
1551 while (must_redraw != 0)
1552 if (update_screen(0) == FAIL)
1553 break;
1554 update_cursor(curbuf->b_term, FALSE);
1555
1556 c = term_vgetc();
1557 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001558 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001559 /* Job finished while waiting for a character. Push back the
1560 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001561 if (c != K_IGNORE)
1562 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001563 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001564 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001565 if (c == K_IGNORE)
1566 continue;
1567
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001568#ifdef UNIX
1569 /*
1570 * The shell or another program may change the tty settings. Getting
1571 * them for every typed character is a bit of overhead, but it's needed
1572 * for the first character typed, e.g. when Vim starts in a shell.
1573 */
1574 if (isatty(tty_fd))
1575 {
1576 ttyinfo_T info;
1577
1578 /* Get the current backspace character of the pty. */
1579 if (get_tty_info(tty_fd, &info) == OK)
1580 term_backspace_char = info.backspace;
1581 }
1582#endif
1583
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001584#ifdef WIN3264
1585 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1586 * Use CTRL-BREAK to kill the job. */
1587 if (ctrl_break_was_pressed)
1588 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1589#endif
1590 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1591 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1592 {
1593 int prev_c = c;
1594
1595#ifdef FEAT_CMDL_INFO
1596 if (add_to_showcmd(c))
1597 out_flush();
1598#endif
1599 c = term_vgetc();
1600#ifdef FEAT_CMDL_INFO
1601 clear_showcmd();
1602#endif
1603 if (!term_use_loop())
1604 /* job finished while waiting for a character */
1605 break;
1606
1607 if (prev_c == Ctrl_BSL)
1608 {
1609 if (c == Ctrl_N)
1610 {
1611 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1612 term_enter_normal_mode();
1613 ret = FAIL;
1614 goto theend;
1615 }
1616 /* Send both keys to the terminal. */
1617 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1618 }
1619 else if (c == Ctrl_C)
1620 {
1621 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1622 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1623 }
1624 else if (termkey == 0 && c == '.')
1625 {
1626 /* "CTRL-W .": send CTRL-W to the job */
1627 c = Ctrl_W;
1628 }
1629 else if (c == 'N')
1630 {
1631 /* CTRL-W N : go to Terminal-Normal mode. */
1632 term_enter_normal_mode();
1633 ret = FAIL;
1634 goto theend;
1635 }
1636 else if (c == '"')
1637 {
1638 term_paste_register(prev_c);
1639 continue;
1640 }
1641 else if (termkey == 0 || c != termkey)
1642 {
1643 stuffcharReadbuff(Ctrl_W);
1644 stuffcharReadbuff(c);
1645 ret = OK;
1646 goto theend;
1647 }
1648 }
1649# ifdef WIN3264
1650 if (!enc_utf8 && has_mbyte && c >= 0x80)
1651 {
1652 WCHAR wc;
1653 char_u mb[3];
1654
1655 mb[0] = (unsigned)c >> 8;
1656 mb[1] = c;
1657 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1658 c = wc;
1659 }
1660# endif
1661 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1662 {
1663 ret = OK;
1664 goto theend;
1665 }
1666 }
1667 ret = FAIL;
1668
1669theend:
1670 in_terminal_loop = NULL;
1671 may_restore_cursor_props();
1672 return ret;
1673}
1674
1675/*
1676 * Called when a job has finished.
1677 * This updates the title and status, but does not close the vterm, because
1678 * there might still be pending output in the channel.
1679 */
1680 void
1681term_job_ended(job_T *job)
1682{
1683 term_T *term;
1684 int did_one = FALSE;
1685
1686 for (term = first_term; term != NULL; term = term->tl_next)
1687 if (term->tl_job == job)
1688 {
1689 vim_free(term->tl_title);
1690 term->tl_title = NULL;
1691 vim_free(term->tl_status_text);
1692 term->tl_status_text = NULL;
1693 redraw_buf_and_status_later(term->tl_buffer, VALID);
1694 did_one = TRUE;
1695 }
1696 if (did_one)
1697 redraw_statuslines();
1698 if (curbuf->b_term != NULL)
1699 {
1700 if (curbuf->b_term->tl_job == job)
1701 maketitle();
1702 update_cursor(curbuf->b_term, TRUE);
1703 }
1704}
1705
1706 static void
1707may_toggle_cursor(term_T *term)
1708{
1709 if (in_terminal_loop == term)
1710 {
1711 if (term->tl_cursor_visible)
1712 cursor_on();
1713 else
1714 cursor_off();
1715 }
1716}
1717
1718/*
1719 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001720 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001721 */
1722 static int
1723color2index(VTermColor *color, int fg, int *boldp)
1724{
1725 int red = color->red;
1726 int blue = color->blue;
1727 int green = color->green;
1728
Bram Moolenaar46359e12017-11-29 22:33:38 +01001729 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001730 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001731 /* First 16 colors and default: use the ANSI index, because these
1732 * colors can be redefined. */
1733 if (t_colors >= 16)
1734 return color->ansi_index;
1735 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001736 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001737 case 0: return 0;
1738 case 1: return lookup_color( 0, fg, boldp) + 1;
1739 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1740 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1741 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1742 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1743 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1744 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1745 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1746 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1747 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1748 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1749 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1750 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1751 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1752 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1753 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754 }
1755 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001756
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001757 if (t_colors >= 256)
1758 {
1759 if (red == blue && red == green)
1760 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001761 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001762 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001763 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1764 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1765 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001766 int i;
1767
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001768 if (red < 5)
1769 return 17; /* 00/00/00 */
1770 if (red > 245) /* ff/ff/ff */
1771 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772 for (i = 0; i < 23; ++i)
1773 if (red < cutoff[i])
1774 return i + 233;
1775 return 256;
1776 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001777 {
1778 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1779 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001780
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001781 /* 216-color cube */
1782 for (ri = 0; ri < 5; ++ri)
1783 if (red < cutoff[ri])
1784 break;
1785 for (gi = 0; gi < 5; ++gi)
1786 if (green < cutoff[gi])
1787 break;
1788 for (bi = 0; bi < 5; ++bi)
1789 if (blue < cutoff[bi])
1790 break;
1791 return 17 + ri * 36 + gi * 6 + bi;
1792 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001793 }
1794 return 0;
1795}
1796
1797/*
1798 * Convert the attributes of a vterm cell into an attribute index.
1799 */
1800 static int
1801cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1802{
1803 int attr = 0;
1804
1805 if (cellattrs.bold)
1806 attr |= HL_BOLD;
1807 if (cellattrs.underline)
1808 attr |= HL_UNDERLINE;
1809 if (cellattrs.italic)
1810 attr |= HL_ITALIC;
1811 if (cellattrs.strike)
1812 attr |= HL_STRIKETHROUGH;
1813 if (cellattrs.reverse)
1814 attr |= HL_INVERSE;
1815
1816#ifdef FEAT_GUI
1817 if (gui.in_use)
1818 {
1819 guicolor_T fg, bg;
1820
1821 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1822 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1823 return get_gui_attr_idx(attr, fg, bg);
1824 }
1825 else
1826#endif
1827#ifdef FEAT_TERMGUICOLORS
1828 if (p_tgc)
1829 {
1830 guicolor_T fg, bg;
1831
1832 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1833 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1834
1835 return get_tgc_attr_idx(attr, fg, bg);
1836 }
1837 else
1838#endif
1839 {
1840 int bold = MAYBE;
1841 int fg = color2index(&cellfg, TRUE, &bold);
1842 int bg = color2index(&cellbg, FALSE, &bold);
1843
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001844 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001845 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001846 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001847 if (fg == 0 && term_default_cterm_fg >= 0)
1848 fg = term_default_cterm_fg + 1;
1849 if (bg == 0 && term_default_cterm_bg >= 0)
1850 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001851 }
1852
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001853 /* with 8 colors set the bold attribute to get a bright foreground */
1854 if (bold == TRUE)
1855 attr |= HL_BOLD;
1856 return get_cterm_attr_idx(attr, fg, bg);
1857 }
1858 return 0;
1859}
1860
1861 static int
1862handle_damage(VTermRect rect, void *user)
1863{
1864 term_T *term = (term_T *)user;
1865
1866 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1867 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1868 redraw_buf_later(term->tl_buffer, NOT_VALID);
1869 return 1;
1870}
1871
1872 static int
1873handle_moverect(VTermRect dest, VTermRect src, void *user)
1874{
1875 term_T *term = (term_T *)user;
1876
1877 /* Scrolling up is done much more efficiently by deleting lines instead of
1878 * redrawing the text. */
1879 if (dest.start_col == src.start_col
1880 && dest.end_col == src.end_col
1881 && dest.start_row < src.start_row)
1882 {
1883 win_T *wp;
1884 VTermColor fg, bg;
1885 VTermScreenCellAttrs attr;
1886 int clear_attr;
1887
1888 /* Set the color to clear lines with. */
1889 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1890 &fg, &bg);
1891 vim_memset(&attr, 0, sizeof(attr));
1892 clear_attr = cell2attr(attr, fg, bg);
1893
1894 FOR_ALL_WINDOWS(wp)
1895 {
1896 if (wp->w_buffer == term->tl_buffer)
1897 win_del_lines(wp, dest.start_row,
1898 src.start_row - dest.start_row, FALSE, FALSE,
1899 clear_attr);
1900 }
1901 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02001902
1903 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
1904 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
1905
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001906 redraw_buf_later(term->tl_buffer, NOT_VALID);
1907 return 1;
1908}
1909
1910 static int
1911handle_movecursor(
1912 VTermPos pos,
1913 VTermPos oldpos UNUSED,
1914 int visible,
1915 void *user)
1916{
1917 term_T *term = (term_T *)user;
1918 win_T *wp;
1919
1920 term->tl_cursor_pos = pos;
1921 term->tl_cursor_visible = visible;
1922
1923 FOR_ALL_WINDOWS(wp)
1924 {
1925 if (wp->w_buffer == term->tl_buffer)
1926 position_cursor(wp, &pos);
1927 }
1928 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
1929 {
1930 may_toggle_cursor(term);
1931 update_cursor(term, term->tl_cursor_visible);
1932 }
1933
1934 return 1;
1935}
1936
1937 static int
1938handle_settermprop(
1939 VTermProp prop,
1940 VTermValue *value,
1941 void *user)
1942{
1943 term_T *term = (term_T *)user;
1944
1945 switch (prop)
1946 {
1947 case VTERM_PROP_TITLE:
1948 vim_free(term->tl_title);
1949 /* a blank title isn't useful, make it empty, so that "running" is
1950 * displayed */
1951 if (*skipwhite((char_u *)value->string) == NUL)
1952 term->tl_title = NULL;
1953#ifdef WIN3264
1954 else if (!enc_utf8 && enc_codepage > 0)
1955 {
1956 WCHAR *ret = NULL;
1957 int length = 0;
1958
1959 MultiByteToWideChar_alloc(CP_UTF8, 0,
1960 (char*)value->string, (int)STRLEN(value->string),
1961 &ret, &length);
1962 if (ret != NULL)
1963 {
1964 WideCharToMultiByte_alloc(enc_codepage, 0,
1965 ret, length, (char**)&term->tl_title,
1966 &length, 0, 0);
1967 vim_free(ret);
1968 }
1969 }
1970#endif
1971 else
1972 term->tl_title = vim_strsave((char_u *)value->string);
1973 vim_free(term->tl_status_text);
1974 term->tl_status_text = NULL;
1975 if (term == curbuf->b_term)
1976 maketitle();
1977 break;
1978
1979 case VTERM_PROP_CURSORVISIBLE:
1980 term->tl_cursor_visible = value->boolean;
1981 may_toggle_cursor(term);
1982 out_flush();
1983 break;
1984
1985 case VTERM_PROP_CURSORBLINK:
1986 term->tl_cursor_blink = value->boolean;
1987 may_set_cursor_props(term);
1988 break;
1989
1990 case VTERM_PROP_CURSORSHAPE:
1991 term->tl_cursor_shape = value->number;
1992 may_set_cursor_props(term);
1993 break;
1994
1995 case VTERM_PROP_CURSORCOLOR:
1996 vim_free(term->tl_cursor_color);
1997 if (*value->string == NUL)
1998 term->tl_cursor_color = NULL;
1999 else
2000 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2001 may_set_cursor_props(term);
2002 break;
2003
2004 case VTERM_PROP_ALTSCREEN:
2005 /* TODO: do anything else? */
2006 term->tl_using_altscreen = value->boolean;
2007 break;
2008
2009 default:
2010 break;
2011 }
2012 /* Always return 1, otherwise vterm doesn't store the value internally. */
2013 return 1;
2014}
2015
2016/*
2017 * The job running in the terminal resized the terminal.
2018 */
2019 static int
2020handle_resize(int rows, int cols, void *user)
2021{
2022 term_T *term = (term_T *)user;
2023 win_T *wp;
2024
2025 term->tl_rows = rows;
2026 term->tl_cols = cols;
2027 if (term->tl_vterm_size_changed)
2028 /* Size was set by vterm_set_size(), don't set the window size. */
2029 term->tl_vterm_size_changed = FALSE;
2030 else
2031 {
2032 FOR_ALL_WINDOWS(wp)
2033 {
2034 if (wp->w_buffer == term->tl_buffer)
2035 {
2036 win_setheight_win(rows, wp);
2037 win_setwidth_win(cols, wp);
2038 }
2039 }
2040 redraw_buf_later(term->tl_buffer, NOT_VALID);
2041 }
2042 return 1;
2043}
2044
2045/*
2046 * Handle a line that is pushed off the top of the screen.
2047 */
2048 static int
2049handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2050{
2051 term_T *term = (term_T *)user;
2052
2053 /* TODO: Limit the number of lines that are stored. */
2054 if (ga_grow(&term->tl_scrollback, 1) == OK)
2055 {
2056 cellattr_T *p = NULL;
2057 int len = 0;
2058 int i;
2059 int c;
2060 int col;
2061 sb_line_T *line;
2062 garray_T ga;
2063 cellattr_T fill_attr = term->tl_default_color;
2064
2065 /* do not store empty cells at the end */
2066 for (i = 0; i < cols; ++i)
2067 if (cells[i].chars[0] != 0)
2068 len = i + 1;
2069 else
2070 cell2cellattr(&cells[i], &fill_attr);
2071
2072 ga_init2(&ga, 1, 100);
2073 if (len > 0)
2074 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2075 if (p != NULL)
2076 {
2077 for (col = 0; col < len; col += cells[col].width)
2078 {
2079 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2080 {
2081 ga.ga_len = 0;
2082 break;
2083 }
2084 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2085 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2086 (char_u *)ga.ga_data + ga.ga_len);
2087 cell2cellattr(&cells[col], &p[col]);
2088 }
2089 }
2090 if (ga_grow(&ga, 1) == FAIL)
2091 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2092 else
2093 {
2094 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2095 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2096 }
2097 ga_clear(&ga);
2098
2099 line = (sb_line_T *)term->tl_scrollback.ga_data
2100 + term->tl_scrollback.ga_len;
2101 line->sb_cols = len;
2102 line->sb_cells = p;
2103 line->sb_fill_attr = fill_attr;
2104 ++term->tl_scrollback.ga_len;
2105 ++term->tl_scrollback_scrolled;
2106 }
2107 return 0; /* ignored */
2108}
2109
2110static VTermScreenCallbacks screen_callbacks = {
2111 handle_damage, /* damage */
2112 handle_moverect, /* moverect */
2113 handle_movecursor, /* movecursor */
2114 handle_settermprop, /* settermprop */
2115 NULL, /* bell */
2116 handle_resize, /* resize */
2117 handle_pushline, /* sb_pushline */
2118 NULL /* sb_popline */
2119};
2120
2121/*
2122 * Called when a channel has been closed.
2123 * If this was a channel for a terminal window then finish it up.
2124 */
2125 void
2126term_channel_closed(channel_T *ch)
2127{
2128 term_T *term;
2129 int did_one = FALSE;
2130
2131 for (term = first_term; term != NULL; term = term->tl_next)
2132 if (term->tl_job == ch->ch_job)
2133 {
2134 term->tl_channel_closed = TRUE;
2135 did_one = TRUE;
2136
2137 vim_free(term->tl_title);
2138 term->tl_title = NULL;
2139 vim_free(term->tl_status_text);
2140 term->tl_status_text = NULL;
2141
2142 /* Unless in Terminal-Normal mode: clear the vterm. */
2143 if (!term->tl_normal_mode)
2144 {
2145 int fnum = term->tl_buffer->b_fnum;
2146
2147 cleanup_vterm(term);
2148
2149 if (term->tl_finish == 'c')
2150 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002151 aco_save_T aco;
2152
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002153 /* ++close or term_finish == "close" */
2154 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002155 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002156 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002157 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002158 break;
2159 }
2160 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2161 {
2162 char buf[50];
2163
2164 /* TODO: use term_opencmd */
2165 ch_log(NULL, "terminal job finished, opening window");
2166 vim_snprintf(buf, sizeof(buf),
2167 term->tl_opencmd == NULL
2168 ? "botright sbuf %d"
2169 : (char *)term->tl_opencmd, fnum);
2170 do_cmdline_cmd((char_u *)buf);
2171 }
2172 else
2173 ch_log(NULL, "terminal job finished");
2174 }
2175
2176 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2177 }
2178 if (did_one)
2179 {
2180 redraw_statuslines();
2181
2182 /* Need to break out of vgetc(). */
2183 ins_char_typebuf(K_IGNORE);
2184 typebuf_was_filled = TRUE;
2185
2186 term = curbuf->b_term;
2187 if (term != NULL)
2188 {
2189 if (term->tl_job == ch->ch_job)
2190 maketitle();
2191 update_cursor(term, term->tl_cursor_visible);
2192 }
2193 }
2194}
2195
2196/*
2197 * Called to update a window that contains an active terminal.
2198 * Returns FAIL when there is no terminal running in this window or in
2199 * Terminal-Normal mode.
2200 */
2201 int
2202term_update_window(win_T *wp)
2203{
2204 term_T *term = wp->w_buffer->b_term;
2205 VTerm *vterm;
2206 VTermScreen *screen;
2207 VTermState *state;
2208 VTermPos pos;
2209
2210 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2211 return FAIL;
2212
2213 vterm = term->tl_vterm;
2214 screen = vterm_obtain_screen(vterm);
2215 state = vterm_obtain_state(vterm);
2216
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002217 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002218 {
2219 term->tl_dirty_row_start = 0;
2220 term->tl_dirty_row_end = MAX_ROW;
2221 }
2222
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002223 /*
2224 * If the window was resized a redraw will be triggered and we get here.
2225 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2226 */
2227 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2228 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2229 {
2230 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2231 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2232 win_T *twp;
2233
2234 FOR_ALL_WINDOWS(twp)
2235 {
2236 /* When more than one window shows the same terminal, use the
2237 * smallest size. */
2238 if (twp->w_buffer == term->tl_buffer)
2239 {
2240 if (!term->tl_rows_fixed && rows > twp->w_height)
2241 rows = twp->w_height;
2242 if (!term->tl_cols_fixed && cols > twp->w_width)
2243 cols = twp->w_width;
2244 }
2245 }
2246
2247 term->tl_vterm_size_changed = TRUE;
2248 vterm_set_size(vterm, rows, cols);
2249 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2250 rows);
2251 term_report_winsize(term, rows, cols);
2252 }
2253
2254 /* The cursor may have been moved when resizing. */
2255 vterm_state_get_cursorpos(state, &pos);
2256 position_cursor(wp, &pos);
2257
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002258 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2259 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002260 {
2261 int off = screen_get_current_line_off();
2262 int max_col = MIN(wp->w_width, term->tl_cols);
2263
2264 if (pos.row < term->tl_rows)
2265 {
2266 for (pos.col = 0; pos.col < max_col; )
2267 {
2268 VTermScreenCell cell;
2269 int c;
2270
2271 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2272 vim_memset(&cell, 0, sizeof(cell));
2273
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002274 c = cell.chars[0];
2275 if (c == NUL)
2276 {
2277 ScreenLines[off] = ' ';
2278 if (enc_utf8)
2279 ScreenLinesUC[off] = NUL;
2280 }
2281 else
2282 {
2283 if (enc_utf8)
2284 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002285 int i;
2286
2287 /* composing chars */
2288 for (i = 0; i < Screen_mco
2289 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2290 {
2291 ScreenLinesC[i][off] = cell.chars[i + 1];
2292 if (cell.chars[i + 1] == 0)
2293 break;
2294 }
2295 if (c >= 0x80 || (Screen_mco > 0
2296 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002297 {
2298 ScreenLines[off] = ' ';
2299 ScreenLinesUC[off] = c;
2300 }
2301 else
2302 {
2303 ScreenLines[off] = c;
2304 ScreenLinesUC[off] = NUL;
2305 }
2306 }
2307#ifdef WIN3264
2308 else if (has_mbyte && c >= 0x80)
2309 {
2310 char_u mb[MB_MAXBYTES+1];
2311 WCHAR wc = c;
2312
2313 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2314 (char*)mb, 2, 0, 0) > 1)
2315 {
2316 ScreenLines[off] = mb[0];
2317 ScreenLines[off + 1] = mb[1];
2318 cell.width = mb_ptr2cells(mb);
2319 }
2320 else
2321 ScreenLines[off] = c;
2322 }
2323#endif
2324 else
2325 ScreenLines[off] = c;
2326 }
2327 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2328
2329 ++pos.col;
2330 ++off;
2331 if (cell.width == 2)
2332 {
2333 if (enc_utf8)
2334 ScreenLinesUC[off] = NUL;
2335
2336 /* don't set the second byte to NUL for a DBCS encoding, it
2337 * has been set above */
2338 if (enc_utf8 || !has_mbyte)
2339 ScreenLines[off] = NUL;
2340
2341 ++pos.col;
2342 ++off;
2343 }
2344 }
2345 }
2346 else
2347 pos.col = 0;
2348
2349 screen_line(wp->w_winrow + pos.row, wp->w_wincol,
2350 pos.col, wp->w_width, FALSE);
2351 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002352 term->tl_dirty_row_start = MAX_ROW;
2353 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002354
2355 return OK;
2356}
2357
2358/*
2359 * Return TRUE if "wp" is a terminal window where the job has finished.
2360 */
2361 int
2362term_is_finished(buf_T *buf)
2363{
2364 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2365}
2366
2367/*
2368 * Return TRUE if "wp" is a terminal window where the job has finished or we
2369 * are in Terminal-Normal mode, thus we show the buffer contents.
2370 */
2371 int
2372term_show_buffer(buf_T *buf)
2373{
2374 term_T *term = buf->b_term;
2375
2376 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2377}
2378
2379/*
2380 * The current buffer is going to be changed. If there is terminal
2381 * highlighting remove it now.
2382 */
2383 void
2384term_change_in_curbuf(void)
2385{
2386 term_T *term = curbuf->b_term;
2387
2388 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2389 {
2390 free_scrollback(term);
2391 redraw_buf_later(term->tl_buffer, NOT_VALID);
2392
2393 /* The buffer is now like a normal buffer, it cannot be easily
2394 * abandoned when changed. */
2395 set_string_option_direct((char_u *)"buftype", -1,
2396 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2397 }
2398}
2399
2400/*
2401 * Get the screen attribute for a position in the buffer.
2402 * Use a negative "col" to get the filler background color.
2403 */
2404 int
2405term_get_attr(buf_T *buf, linenr_T lnum, int col)
2406{
2407 term_T *term = buf->b_term;
2408 sb_line_T *line;
2409 cellattr_T *cellattr;
2410
2411 if (lnum > term->tl_scrollback.ga_len)
2412 cellattr = &term->tl_default_color;
2413 else
2414 {
2415 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2416 if (col < 0 || col >= line->sb_cols)
2417 cellattr = &line->sb_fill_attr;
2418 else
2419 cellattr = line->sb_cells + col;
2420 }
2421 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2422}
2423
2424static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002425 { 0, 0, 0, 1}, /* black */
2426 {224, 0, 0, 2}, /* dark red */
2427 { 0, 224, 0, 3}, /* dark green */
2428 {224, 224, 0, 4}, /* dark yellow / brown */
2429 { 0, 0, 224, 5}, /* dark blue */
2430 {224, 0, 224, 6}, /* dark magenta */
2431 { 0, 224, 224, 7}, /* dark cyan */
2432 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002433
Bram Moolenaar46359e12017-11-29 22:33:38 +01002434 {128, 128, 128, 9}, /* dark grey */
2435 {255, 64, 64, 10}, /* light red */
2436 { 64, 255, 64, 11}, /* light green */
2437 {255, 255, 64, 12}, /* yellow */
2438 { 64, 64, 255, 13}, /* light blue */
2439 {255, 64, 255, 14}, /* light magenta */
2440 { 64, 255, 255, 15}, /* light cyan */
2441 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442};
2443
2444static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002445 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002446};
2447
2448static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002449 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2450 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002451};
2452
2453/*
2454 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002455 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002456 */
2457 static void
2458cterm_color2rgb(int nr, VTermColor *rgb)
2459{
2460 int idx;
2461
2462 if (nr < 16)
2463 {
2464 *rgb = ansi_table[nr];
2465 }
2466 else if (nr < 232)
2467 {
2468 /* 216 color cube */
2469 idx = nr - 16;
2470 rgb->blue = cube_value[idx % 6];
2471 rgb->green = cube_value[idx / 6 % 6];
2472 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002473 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002474 }
2475 else if (nr < 256)
2476 {
2477 /* 24 grey scale ramp */
2478 idx = nr - 232;
2479 rgb->blue = grey_ramp[idx];
2480 rgb->green = grey_ramp[idx];
2481 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002482 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002483 }
2484}
2485
2486/*
2487 * Create a new vterm and initialize it.
2488 */
2489 static void
2490create_vterm(term_T *term, int rows, int cols)
2491{
2492 VTerm *vterm;
2493 VTermScreen *screen;
2494 VTermValue value;
2495 VTermColor *fg, *bg;
2496 int fgval, bgval;
2497 int id;
2498
2499 vterm = vterm_new(rows, cols);
2500 term->tl_vterm = vterm;
2501 screen = vterm_obtain_screen(vterm);
2502 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2503 /* TODO: depends on 'encoding'. */
2504 vterm_set_utf8(vterm, 1);
2505
2506 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2507 term->tl_default_color.width = 1;
2508 fg = &term->tl_default_color.fg;
2509 bg = &term->tl_default_color.bg;
2510
2511 /* Vterm uses a default black background. Set it to white when
2512 * 'background' is "light". */
2513 if (*p_bg == 'l')
2514 {
2515 fgval = 0;
2516 bgval = 255;
2517 }
2518 else
2519 {
2520 fgval = 255;
2521 bgval = 0;
2522 }
2523 fg->red = fg->green = fg->blue = fgval;
2524 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002525 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002526
2527 /* The "Terminal" highlight group overrules the defaults. */
2528 id = syn_name2id((char_u *)"Terminal");
2529
Bram Moolenaar46359e12017-11-29 22:33:38 +01002530 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002531#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2532 if (0
2533# ifdef FEAT_GUI
2534 || gui.in_use
2535# endif
2536# ifdef FEAT_TERMGUICOLORS
2537 || p_tgc
2538# endif
2539 )
2540 {
2541 guicolor_T fg_rgb = INVALCOLOR;
2542 guicolor_T bg_rgb = INVALCOLOR;
2543
2544 if (id != 0)
2545 syn_id2colors(id, &fg_rgb, &bg_rgb);
2546
2547# ifdef FEAT_GUI
2548 if (gui.in_use)
2549 {
2550 if (fg_rgb == INVALCOLOR)
2551 fg_rgb = gui.norm_pixel;
2552 if (bg_rgb == INVALCOLOR)
2553 bg_rgb = gui.back_pixel;
2554 }
2555# ifdef FEAT_TERMGUICOLORS
2556 else
2557# endif
2558# endif
2559# ifdef FEAT_TERMGUICOLORS
2560 {
2561 if (fg_rgb == INVALCOLOR)
2562 fg_rgb = cterm_normal_fg_gui_color;
2563 if (bg_rgb == INVALCOLOR)
2564 bg_rgb = cterm_normal_bg_gui_color;
2565 }
2566# endif
2567 if (fg_rgb != INVALCOLOR)
2568 {
2569 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2570
2571 fg->red = (unsigned)(rgb >> 16);
2572 fg->green = (unsigned)(rgb >> 8) & 255;
2573 fg->blue = (unsigned)rgb & 255;
2574 }
2575 if (bg_rgb != INVALCOLOR)
2576 {
2577 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2578
2579 bg->red = (unsigned)(rgb >> 16);
2580 bg->green = (unsigned)(rgb >> 8) & 255;
2581 bg->blue = (unsigned)rgb & 255;
2582 }
2583 }
2584 else
2585#endif
2586 if (id != 0 && t_colors >= 16)
2587 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002588 if (term_default_cterm_fg >= 0)
2589 cterm_color2rgb(term_default_cterm_fg, fg);
2590 if (term_default_cterm_bg >= 0)
2591 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002592 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002593 else
2594 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002595#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002596 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002597#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002598
2599 /* In an MS-Windows console we know the normal colors. */
2600 if (cterm_normal_fg_color > 0)
2601 {
2602 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002603# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002604 tmp = fg->red;
2605 fg->red = fg->blue;
2606 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002607# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002608 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002609# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002610 else
2611 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002612# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002613
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 if (cterm_normal_bg_color > 0)
2615 {
2616 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002617# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 tmp = bg->red;
2619 bg->red = bg->blue;
2620 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002621# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002622 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002623# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002624 else
2625 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002626# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002627 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002628
2629 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2630
2631 /* Required to initialize most things. */
2632 vterm_screen_reset(screen, 1 /* hard */);
2633
2634 /* Allow using alternate screen. */
2635 vterm_screen_enable_altscreen(screen, 1);
2636
2637 /* For unix do not use a blinking cursor. In an xterm this causes the
2638 * cursor to blink if it's blinking in the xterm.
2639 * For Windows we respect the system wide setting. */
2640#ifdef WIN3264
2641 if (GetCaretBlinkTime() == INFINITE)
2642 value.boolean = 0;
2643 else
2644 value.boolean = 1;
2645#else
2646 value.boolean = 0;
2647#endif
2648 vterm_state_set_termprop(vterm_obtain_state(vterm),
2649 VTERM_PROP_CURSORBLINK, &value);
2650}
2651
2652/*
2653 * Return the text to show for the buffer name and status.
2654 */
2655 char_u *
2656term_get_status_text(term_T *term)
2657{
2658 if (term->tl_status_text == NULL)
2659 {
2660 char_u *txt;
2661 size_t len;
2662
2663 if (term->tl_normal_mode)
2664 {
2665 if (term_job_running(term))
2666 txt = (char_u *)_("Terminal");
2667 else
2668 txt = (char_u *)_("Terminal-finished");
2669 }
2670 else if (term->tl_title != NULL)
2671 txt = term->tl_title;
2672 else if (term_none_open(term))
2673 txt = (char_u *)_("active");
2674 else if (term_job_running(term))
2675 txt = (char_u *)_("running");
2676 else
2677 txt = (char_u *)_("finished");
2678 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2679 term->tl_status_text = alloc((int)len);
2680 if (term->tl_status_text != NULL)
2681 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2682 term->tl_buffer->b_fname, txt);
2683 }
2684 return term->tl_status_text;
2685}
2686
2687/*
2688 * Mark references in jobs of terminals.
2689 */
2690 int
2691set_ref_in_term(int copyID)
2692{
2693 int abort = FALSE;
2694 term_T *term;
2695 typval_T tv;
2696
2697 for (term = first_term; term != NULL; term = term->tl_next)
2698 if (term->tl_job != NULL)
2699 {
2700 tv.v_type = VAR_JOB;
2701 tv.vval.v_job = term->tl_job;
2702 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2703 }
2704 return abort;
2705}
2706
2707/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002708 * Cache "Terminal" highlight group colors.
2709 */
2710 void
2711set_terminal_default_colors(int cterm_fg, int cterm_bg)
2712{
2713 term_default_cterm_fg = cterm_fg - 1;
2714 term_default_cterm_bg = cterm_bg - 1;
2715}
2716
2717/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002718 * Get the buffer from the first argument in "argvars".
2719 * Returns NULL when the buffer is not for a terminal window.
2720 */
2721 static buf_T *
2722term_get_buf(typval_T *argvars)
2723{
2724 buf_T *buf;
2725
2726 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2727 ++emsg_off;
2728 buf = get_buf_tv(&argvars[0], FALSE);
2729 --emsg_off;
2730 if (buf == NULL || buf->b_term == NULL)
2731 return NULL;
2732 return buf;
2733}
2734
2735/*
2736 * "term_getaltscreen(buf)" function
2737 */
2738 void
2739f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2740{
2741 buf_T *buf = term_get_buf(argvars);
2742
2743 if (buf == NULL)
2744 return;
2745 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2746}
2747
2748/*
2749 * "term_getattr(attr, name)" function
2750 */
2751 void
2752f_term_getattr(typval_T *argvars, typval_T *rettv)
2753{
2754 int attr;
2755 size_t i;
2756 char_u *name;
2757
2758 static struct {
2759 char *name;
2760 int attr;
2761 } attrs[] = {
2762 {"bold", HL_BOLD},
2763 {"italic", HL_ITALIC},
2764 {"underline", HL_UNDERLINE},
2765 {"strike", HL_STRIKETHROUGH},
2766 {"reverse", HL_INVERSE},
2767 };
2768
2769 attr = get_tv_number(&argvars[0]);
2770 name = get_tv_string_chk(&argvars[1]);
2771 if (name == NULL)
2772 return;
2773
2774 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2775 if (STRCMP(name, attrs[i].name) == 0)
2776 {
2777 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2778 break;
2779 }
2780}
2781
2782/*
2783 * "term_getcursor(buf)" function
2784 */
2785 void
2786f_term_getcursor(typval_T *argvars, typval_T *rettv)
2787{
2788 buf_T *buf = term_get_buf(argvars);
2789 term_T *term;
2790 list_T *l;
2791 dict_T *d;
2792
2793 if (rettv_list_alloc(rettv) == FAIL)
2794 return;
2795 if (buf == NULL)
2796 return;
2797 term = buf->b_term;
2798
2799 l = rettv->vval.v_list;
2800 list_append_number(l, term->tl_cursor_pos.row + 1);
2801 list_append_number(l, term->tl_cursor_pos.col + 1);
2802
2803 d = dict_alloc();
2804 if (d != NULL)
2805 {
2806 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2807 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2808 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2809 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2810 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2811 ? (char_u *)"" : term->tl_cursor_color);
2812 list_append_dict(l, d);
2813 }
2814}
2815
2816/*
2817 * "term_getjob(buf)" function
2818 */
2819 void
2820f_term_getjob(typval_T *argvars, typval_T *rettv)
2821{
2822 buf_T *buf = term_get_buf(argvars);
2823
2824 rettv->v_type = VAR_JOB;
2825 rettv->vval.v_job = NULL;
2826 if (buf == NULL)
2827 return;
2828
2829 rettv->vval.v_job = buf->b_term->tl_job;
2830 if (rettv->vval.v_job != NULL)
2831 ++rettv->vval.v_job->jv_refcount;
2832}
2833
2834 static int
2835get_row_number(typval_T *tv, term_T *term)
2836{
2837 if (tv->v_type == VAR_STRING
2838 && tv->vval.v_string != NULL
2839 && STRCMP(tv->vval.v_string, ".") == 0)
2840 return term->tl_cursor_pos.row;
2841 return (int)get_tv_number(tv) - 1;
2842}
2843
2844/*
2845 * "term_getline(buf, row)" function
2846 */
2847 void
2848f_term_getline(typval_T *argvars, typval_T *rettv)
2849{
2850 buf_T *buf = term_get_buf(argvars);
2851 term_T *term;
2852 int row;
2853
2854 rettv->v_type = VAR_STRING;
2855 if (buf == NULL)
2856 return;
2857 term = buf->b_term;
2858 row = get_row_number(&argvars[1], term);
2859
2860 if (term->tl_vterm == NULL)
2861 {
2862 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2863
2864 /* vterm is finished, get the text from the buffer */
2865 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2866 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2867 }
2868 else
2869 {
2870 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2871 VTermRect rect;
2872 int len;
2873 char_u *p;
2874
2875 if (row < 0 || row >= term->tl_rows)
2876 return;
2877 len = term->tl_cols * MB_MAXBYTES + 1;
2878 p = alloc(len);
2879 if (p == NULL)
2880 return;
2881 rettv->vval.v_string = p;
2882
2883 rect.start_col = 0;
2884 rect.end_col = term->tl_cols;
2885 rect.start_row = row;
2886 rect.end_row = row + 1;
2887 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2888 }
2889}
2890
2891/*
2892 * "term_getscrolled(buf)" function
2893 */
2894 void
2895f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2896{
2897 buf_T *buf = term_get_buf(argvars);
2898
2899 if (buf == NULL)
2900 return;
2901 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2902}
2903
2904/*
2905 * "term_getsize(buf)" function
2906 */
2907 void
2908f_term_getsize(typval_T *argvars, typval_T *rettv)
2909{
2910 buf_T *buf = term_get_buf(argvars);
2911 list_T *l;
2912
2913 if (rettv_list_alloc(rettv) == FAIL)
2914 return;
2915 if (buf == NULL)
2916 return;
2917
2918 l = rettv->vval.v_list;
2919 list_append_number(l, buf->b_term->tl_rows);
2920 list_append_number(l, buf->b_term->tl_cols);
2921}
2922
2923/*
2924 * "term_getstatus(buf)" function
2925 */
2926 void
2927f_term_getstatus(typval_T *argvars, typval_T *rettv)
2928{
2929 buf_T *buf = term_get_buf(argvars);
2930 term_T *term;
2931 char_u val[100];
2932
2933 rettv->v_type = VAR_STRING;
2934 if (buf == NULL)
2935 return;
2936 term = buf->b_term;
2937
2938 if (term_job_running(term))
2939 STRCPY(val, "running");
2940 else
2941 STRCPY(val, "finished");
2942 if (term->tl_normal_mode)
2943 STRCAT(val, ",normal");
2944 rettv->vval.v_string = vim_strsave(val);
2945}
2946
2947/*
2948 * "term_gettitle(buf)" function
2949 */
2950 void
2951f_term_gettitle(typval_T *argvars, typval_T *rettv)
2952{
2953 buf_T *buf = term_get_buf(argvars);
2954
2955 rettv->v_type = VAR_STRING;
2956 if (buf == NULL)
2957 return;
2958
2959 if (buf->b_term->tl_title != NULL)
2960 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
2961}
2962
2963/*
2964 * "term_gettty(buf)" function
2965 */
2966 void
2967f_term_gettty(typval_T *argvars, typval_T *rettv)
2968{
2969 buf_T *buf = term_get_buf(argvars);
2970 char_u *p;
2971 int num = 0;
2972
2973 rettv->v_type = VAR_STRING;
2974 if (buf == NULL)
2975 return;
2976 if (argvars[1].v_type != VAR_UNKNOWN)
2977 num = get_tv_number(&argvars[1]);
2978
2979 switch (num)
2980 {
2981 case 0:
2982 if (buf->b_term->tl_job != NULL)
2983 p = buf->b_term->tl_job->jv_tty_out;
2984 else
2985 p = buf->b_term->tl_tty_out;
2986 break;
2987 case 1:
2988 if (buf->b_term->tl_job != NULL)
2989 p = buf->b_term->tl_job->jv_tty_in;
2990 else
2991 p = buf->b_term->tl_tty_in;
2992 break;
2993 default:
2994 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
2995 return;
2996 }
2997 if (p != NULL)
2998 rettv->vval.v_string = vim_strsave(p);
2999}
3000
3001/*
3002 * "term_list()" function
3003 */
3004 void
3005f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3006{
3007 term_T *tp;
3008 list_T *l;
3009
3010 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3011 return;
3012
3013 l = rettv->vval.v_list;
3014 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3015 if (tp != NULL && tp->tl_buffer != NULL)
3016 if (list_append_number(l,
3017 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3018 return;
3019}
3020
3021/*
3022 * "term_scrape(buf, row)" function
3023 */
3024 void
3025f_term_scrape(typval_T *argvars, typval_T *rettv)
3026{
3027 buf_T *buf = term_get_buf(argvars);
3028 VTermScreen *screen = NULL;
3029 VTermPos pos;
3030 list_T *l;
3031 term_T *term;
3032 char_u *p;
3033 sb_line_T *line;
3034
3035 if (rettv_list_alloc(rettv) == FAIL)
3036 return;
3037 if (buf == NULL)
3038 return;
3039 term = buf->b_term;
3040
3041 l = rettv->vval.v_list;
3042 pos.row = get_row_number(&argvars[1], term);
3043
3044 if (term->tl_vterm != NULL)
3045 {
3046 screen = vterm_obtain_screen(term->tl_vterm);
3047 p = NULL;
3048 line = NULL;
3049 }
3050 else
3051 {
3052 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3053
3054 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3055 return;
3056 p = ml_get_buf(buf, lnum + 1, FALSE);
3057 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3058 }
3059
3060 for (pos.col = 0; pos.col < term->tl_cols; )
3061 {
3062 dict_T *dcell;
3063 int width;
3064 VTermScreenCellAttrs attrs;
3065 VTermColor fg, bg;
3066 char_u rgb[8];
3067 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3068 int off = 0;
3069 int i;
3070
3071 if (screen == NULL)
3072 {
3073 cellattr_T *cellattr;
3074 int len;
3075
3076 /* vterm has finished, get the cell from scrollback */
3077 if (pos.col >= line->sb_cols)
3078 break;
3079 cellattr = line->sb_cells + pos.col;
3080 width = cellattr->width;
3081 attrs = cellattr->attrs;
3082 fg = cellattr->fg;
3083 bg = cellattr->bg;
3084 len = MB_PTR2LEN(p);
3085 mch_memmove(mbs, p, len);
3086 mbs[len] = NUL;
3087 p += len;
3088 }
3089 else
3090 {
3091 VTermScreenCell cell;
3092 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3093 break;
3094 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3095 {
3096 if (cell.chars[i] == 0)
3097 break;
3098 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3099 }
3100 mbs[off] = NUL;
3101 width = cell.width;
3102 attrs = cell.attrs;
3103 fg = cell.fg;
3104 bg = cell.bg;
3105 }
3106 dcell = dict_alloc();
3107 list_append_dict(l, dcell);
3108
3109 dict_add_nr_str(dcell, "chars", 0, mbs);
3110
3111 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3112 fg.red, fg.green, fg.blue);
3113 dict_add_nr_str(dcell, "fg", 0, rgb);
3114 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3115 bg.red, bg.green, bg.blue);
3116 dict_add_nr_str(dcell, "bg", 0, rgb);
3117
3118 dict_add_nr_str(dcell, "attr",
3119 cell2attr(attrs, fg, bg), NULL);
3120 dict_add_nr_str(dcell, "width", width, NULL);
3121
3122 ++pos.col;
3123 if (width == 2)
3124 ++pos.col;
3125 }
3126}
3127
3128/*
3129 * "term_sendkeys(buf, keys)" function
3130 */
3131 void
3132f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3133{
3134 buf_T *buf = term_get_buf(argvars);
3135 char_u *msg;
3136 term_T *term;
3137
3138 rettv->v_type = VAR_UNKNOWN;
3139 if (buf == NULL)
3140 return;
3141
3142 msg = get_tv_string_chk(&argvars[1]);
3143 if (msg == NULL)
3144 return;
3145 term = buf->b_term;
3146 if (term->tl_vterm == NULL)
3147 return;
3148
3149 while (*msg != NUL)
3150 {
3151 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003152 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003153 }
3154}
3155
3156/*
3157 * "term_start(command, options)" function
3158 */
3159 void
3160f_term_start(typval_T *argvars, typval_T *rettv)
3161{
3162 jobopt_T opt;
3163 buf_T *buf;
3164
3165 init_job_options(&opt);
3166 if (argvars[1].v_type != VAR_UNKNOWN
3167 && get_job_options(&argvars[1], &opt,
3168 JO_TIMEOUT_ALL + JO_STOPONEXIT
3169 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3170 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3171 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3172 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3173 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3174 return;
3175
3176 if (opt.jo_vertical)
3177 cmdmod.split = WSP_VERT;
3178 buf = term_start(&argvars[0], &opt, FALSE);
3179
3180 if (buf != NULL && buf->b_term != NULL)
3181 rettv->vval.v_number = buf->b_fnum;
3182}
3183
3184/*
3185 * "term_wait" function
3186 */
3187 void
3188f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3189{
3190 buf_T *buf = term_get_buf(argvars);
3191
3192 if (buf == NULL)
3193 {
3194 ch_log(NULL, "term_wait(): invalid argument");
3195 return;
3196 }
3197 if (buf->b_term->tl_job == NULL)
3198 {
3199 ch_log(NULL, "term_wait(): no job to wait for");
3200 return;
3201 }
3202 if (buf->b_term->tl_job->jv_channel == NULL)
3203 /* channel is closed, nothing to do */
3204 return;
3205
3206 /* Get the job status, this will detect a job that finished. */
3207 if ((buf->b_term->tl_job->jv_channel == NULL
3208 || !buf->b_term->tl_job->jv_channel->ch_keep_open)
3209 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3210 {
3211 /* The job is dead, keep reading channel I/O until the channel is
3212 * closed. buf->b_term may become NULL if the terminal was closed while
3213 * waiting. */
3214 ch_log(NULL, "term_wait(): waiting for channel to close");
3215 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3216 {
3217 mch_check_messages();
3218 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01003219 if (!buf_valid(buf))
3220 /* If the terminal is closed when the channel is closed the
3221 * buffer disappears. */
3222 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003223 ui_delay(10L, FALSE);
3224 }
3225 mch_check_messages();
3226 parse_queued_messages();
3227 }
3228 else
3229 {
3230 long wait = 10L;
3231
3232 mch_check_messages();
3233 parse_queued_messages();
3234
3235 /* Wait for some time for any channel I/O. */
3236 if (argvars[1].v_type != VAR_UNKNOWN)
3237 wait = get_tv_number(&argvars[1]);
3238 ui_delay(wait, TRUE);
3239 mch_check_messages();
3240
3241 /* Flushing messages on channels is hopefully sufficient.
3242 * TODO: is there a better way? */
3243 parse_queued_messages();
3244 }
3245}
3246
3247/*
3248 * Called when a channel has sent all the lines to a terminal.
3249 * Send a CTRL-D to mark the end of the text.
3250 */
3251 void
3252term_send_eof(channel_T *ch)
3253{
3254 term_T *term;
3255
3256 for (term = first_term; term != NULL; term = term->tl_next)
3257 if (term->tl_job == ch->ch_job)
3258 {
3259 if (term->tl_eof_chars != NULL)
3260 {
3261 channel_send(ch, PART_IN, term->tl_eof_chars,
3262 (int)STRLEN(term->tl_eof_chars), NULL);
3263 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3264 }
3265# ifdef WIN3264
3266 else
3267 /* Default: CTRL-D */
3268 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3269# endif
3270 }
3271}
3272
3273# if defined(WIN3264) || defined(PROTO)
3274
3275/**************************************
3276 * 2. MS-Windows implementation.
3277 */
3278
3279# ifndef PROTO
3280
3281#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3282#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
3283#define WINPTY_MOUSE_MODE_FORCE 2
3284
3285void* (*winpty_config_new)(UINT64, void*);
3286void* (*winpty_open)(void*, void*);
3287void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3288BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3289void (*winpty_config_set_mouse_mode)(void*, int);
3290void (*winpty_config_set_initial_size)(void*, int, int);
3291LPCWSTR (*winpty_conin_name)(void*);
3292LPCWSTR (*winpty_conout_name)(void*);
3293LPCWSTR (*winpty_conerr_name)(void*);
3294void (*winpty_free)(void*);
3295void (*winpty_config_free)(void*);
3296void (*winpty_spawn_config_free)(void*);
3297void (*winpty_error_free)(void*);
3298LPCWSTR (*winpty_error_msg)(void*);
3299BOOL (*winpty_set_size)(void*, int, int, void*);
3300HANDLE (*winpty_agent_process)(void*);
3301
3302#define WINPTY_DLL "winpty.dll"
3303
3304static HINSTANCE hWinPtyDLL = NULL;
3305# endif
3306
3307 static int
3308dyn_winpty_init(int verbose)
3309{
3310 int i;
3311 static struct
3312 {
3313 char *name;
3314 FARPROC *ptr;
3315 } winpty_entry[] =
3316 {
3317 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3318 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3319 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3320 {"winpty_config_set_mouse_mode",
3321 (FARPROC*)&winpty_config_set_mouse_mode},
3322 {"winpty_config_set_initial_size",
3323 (FARPROC*)&winpty_config_set_initial_size},
3324 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3325 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3326 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3327 {"winpty_free", (FARPROC*)&winpty_free},
3328 {"winpty_open", (FARPROC*)&winpty_open},
3329 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3330 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3331 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3332 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3333 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3334 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3335 {NULL, NULL}
3336 };
3337
3338 /* No need to initialize twice. */
3339 if (hWinPtyDLL)
3340 return OK;
3341 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3342 * winpty.dll. */
3343 if (*p_winptydll != NUL)
3344 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3345 if (!hWinPtyDLL)
3346 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3347 if (!hWinPtyDLL)
3348 {
3349 if (verbose)
3350 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3351 : (char_u *)WINPTY_DLL);
3352 return FAIL;
3353 }
3354 for (i = 0; winpty_entry[i].name != NULL
3355 && winpty_entry[i].ptr != NULL; ++i)
3356 {
3357 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3358 winpty_entry[i].name)) == NULL)
3359 {
3360 if (verbose)
3361 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3362 return FAIL;
3363 }
3364 }
3365
3366 return OK;
3367}
3368
3369/*
3370 * Create a new terminal of "rows" by "cols" cells.
3371 * Store a reference in "term".
3372 * Return OK or FAIL.
3373 */
3374 static int
3375term_and_job_init(
3376 term_T *term,
3377 typval_T *argvar,
3378 jobopt_T *opt)
3379{
3380 WCHAR *cmd_wchar = NULL;
3381 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003382 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003383 channel_T *channel = NULL;
3384 job_T *job = NULL;
3385 DWORD error;
3386 HANDLE jo = NULL;
3387 HANDLE child_process_handle;
3388 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01003389 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003390 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003391 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003392 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003393
3394 if (dyn_winpty_init(TRUE) == FAIL)
3395 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003396 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
3397 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003398
3399 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003400 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003401 cmd = argvar->vval.v_string;
3402 }
3403 else if (argvar->v_type == VAR_LIST)
3404 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003405 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003406 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003407 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003408 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003409 if (cmd == NULL || *cmd == NUL)
3410 {
3411 EMSG(_(e_invarg));
3412 goto failed;
3413 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003414
3415 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003416 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003417 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003418 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003419 if (opt->jo_cwd != NULL)
3420 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003421
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003422 win32_build_env(opt->jo_env, &ga_env, TRUE);
3423 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003424
3425 job = job_alloc();
3426 if (job == NULL)
3427 goto failed;
3428
3429 channel = add_channel();
3430 if (channel == NULL)
3431 goto failed;
3432
3433 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3434 if (term->tl_winpty_config == NULL)
3435 goto failed;
3436
3437 winpty_config_set_mouse_mode(term->tl_winpty_config,
3438 WINPTY_MOUSE_MODE_FORCE);
3439 winpty_config_set_initial_size(term->tl_winpty_config,
3440 term->tl_cols, term->tl_rows);
3441 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3442 if (term->tl_winpty == NULL)
3443 goto failed;
3444
3445 spawn_config = winpty_spawn_config_new(
3446 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3447 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3448 NULL,
3449 cmd_wchar,
3450 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003451 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003452 &winpty_err);
3453 if (spawn_config == NULL)
3454 goto failed;
3455
3456 channel = add_channel();
3457 if (channel == NULL)
3458 goto failed;
3459
3460 job = job_alloc();
3461 if (job == NULL)
3462 goto failed;
3463
3464 if (opt->jo_set & JO_IN_BUF)
3465 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3466
3467 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3468 &child_thread_handle, &error, &winpty_err))
3469 goto failed;
3470
3471 channel_set_pipes(channel,
3472 (sock_T)CreateFileW(
3473 winpty_conin_name(term->tl_winpty),
3474 GENERIC_WRITE, 0, NULL,
3475 OPEN_EXISTING, 0, NULL),
3476 (sock_T)CreateFileW(
3477 winpty_conout_name(term->tl_winpty),
3478 GENERIC_READ, 0, NULL,
3479 OPEN_EXISTING, 0, NULL),
3480 (sock_T)CreateFileW(
3481 winpty_conerr_name(term->tl_winpty),
3482 GENERIC_READ, 0, NULL,
3483 OPEN_EXISTING, 0, NULL));
3484
3485 /* Write lines with CR instead of NL. */
3486 channel->ch_write_text_mode = TRUE;
3487
3488 jo = CreateJobObject(NULL, NULL);
3489 if (jo == NULL)
3490 goto failed;
3491
3492 if (!AssignProcessToJobObject(jo, child_process_handle))
3493 {
3494 /* Failed, switch the way to terminate process with TerminateProcess. */
3495 CloseHandle(jo);
3496 jo = NULL;
3497 }
3498
3499 winpty_spawn_config_free(spawn_config);
3500 vim_free(cmd_wchar);
3501 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003502 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003503
3504 create_vterm(term, term->tl_rows, term->tl_cols);
3505
3506 channel_set_job(channel, job, opt);
3507 job_set_options(job, opt);
3508
3509 job->jv_channel = channel;
3510 job->jv_proc_info.hProcess = child_process_handle;
3511 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3512 job->jv_job_object = jo;
3513 job->jv_status = JOB_STARTED;
3514 job->jv_tty_in = utf16_to_enc(
3515 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3516 job->jv_tty_out = utf16_to_enc(
3517 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3518 ++job->jv_refcount;
3519 term->tl_job = job;
3520
3521 return OK;
3522
3523failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01003524 ga_clear(&ga_cmd);
3525 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003526 vim_free(cmd_wchar);
3527 vim_free(cwd_wchar);
3528 if (spawn_config != NULL)
3529 winpty_spawn_config_free(spawn_config);
3530 if (channel != NULL)
3531 channel_clear(channel);
3532 if (job != NULL)
3533 {
3534 job->jv_channel = NULL;
3535 job_cleanup(job);
3536 }
3537 term->tl_job = NULL;
3538 if (jo != NULL)
3539 CloseHandle(jo);
3540 if (term->tl_winpty != NULL)
3541 winpty_free(term->tl_winpty);
3542 term->tl_winpty = NULL;
3543 if (term->tl_winpty_config != NULL)
3544 winpty_config_free(term->tl_winpty_config);
3545 term->tl_winpty_config = NULL;
3546 if (winpty_err != NULL)
3547 {
3548 char_u *msg = utf16_to_enc(
3549 (short_u *)winpty_error_msg(winpty_err), NULL);
3550
3551 EMSG(msg);
3552 winpty_error_free(winpty_err);
3553 }
3554 return FAIL;
3555}
3556
3557 static int
3558create_pty_only(term_T *term, jobopt_T *options)
3559{
3560 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3561 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3562 char in_name[80], out_name[80];
3563 channel_T *channel = NULL;
3564
3565 create_vterm(term, term->tl_rows, term->tl_cols);
3566
3567 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3568 GetCurrentProcessId(),
3569 curbuf->b_fnum);
3570 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3571 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3572 PIPE_UNLIMITED_INSTANCES,
3573 0, 0, NMPWAIT_NOWAIT, NULL);
3574 if (hPipeIn == INVALID_HANDLE_VALUE)
3575 goto failed;
3576
3577 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3578 GetCurrentProcessId(),
3579 curbuf->b_fnum);
3580 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3581 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3582 PIPE_UNLIMITED_INSTANCES,
3583 0, 0, 0, NULL);
3584 if (hPipeOut == INVALID_HANDLE_VALUE)
3585 goto failed;
3586
3587 ConnectNamedPipe(hPipeIn, NULL);
3588 ConnectNamedPipe(hPipeOut, NULL);
3589
3590 term->tl_job = job_alloc();
3591 if (term->tl_job == NULL)
3592 goto failed;
3593 ++term->tl_job->jv_refcount;
3594
3595 /* behave like the job is already finished */
3596 term->tl_job->jv_status = JOB_FINISHED;
3597
3598 channel = add_channel();
3599 if (channel == NULL)
3600 goto failed;
3601 term->tl_job->jv_channel = channel;
3602 channel->ch_keep_open = TRUE;
3603 channel->ch_named_pipe = TRUE;
3604
3605 channel_set_pipes(channel,
3606 (sock_T)hPipeIn,
3607 (sock_T)hPipeOut,
3608 (sock_T)hPipeOut);
3609 channel_set_job(channel, term->tl_job, options);
3610 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3611 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3612
3613 return OK;
3614
3615failed:
3616 if (hPipeIn != NULL)
3617 CloseHandle(hPipeIn);
3618 if (hPipeOut != NULL)
3619 CloseHandle(hPipeOut);
3620 return FAIL;
3621}
3622
3623/*
3624 * Free the terminal emulator part of "term".
3625 */
3626 static void
3627term_free_vterm(term_T *term)
3628{
3629 if (term->tl_winpty != NULL)
3630 winpty_free(term->tl_winpty);
3631 term->tl_winpty = NULL;
3632 if (term->tl_winpty_config != NULL)
3633 winpty_config_free(term->tl_winpty_config);
3634 term->tl_winpty_config = NULL;
3635 if (term->tl_vterm != NULL)
3636 vterm_free(term->tl_vterm);
3637 term->tl_vterm = NULL;
3638}
3639
3640/*
3641 * Request size to terminal.
3642 */
3643 static void
3644term_report_winsize(term_T *term, int rows, int cols)
3645{
3646 if (term->tl_winpty)
3647 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3648}
3649
3650 int
3651terminal_enabled(void)
3652{
3653 return dyn_winpty_init(FALSE) == OK;
3654}
3655
3656# else
3657
3658/**************************************
3659 * 3. Unix-like implementation.
3660 */
3661
3662/*
3663 * Create a new terminal of "rows" by "cols" cells.
3664 * Start job for "cmd".
3665 * Store the pointers in "term".
3666 * Return OK or FAIL.
3667 */
3668 static int
3669term_and_job_init(
3670 term_T *term,
3671 typval_T *argvar,
3672 jobopt_T *opt)
3673{
3674 create_vterm(term, term->tl_rows, term->tl_cols);
3675
3676 term->tl_job = job_start(argvar, opt);
3677 if (term->tl_job != NULL)
3678 ++term->tl_job->jv_refcount;
3679
3680 return term->tl_job != NULL
3681 && term->tl_job->jv_channel != NULL
3682 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3683}
3684
3685 static int
3686create_pty_only(term_T *term, jobopt_T *opt)
3687{
3688 create_vterm(term, term->tl_rows, term->tl_cols);
3689
3690 term->tl_job = job_alloc();
3691 if (term->tl_job == NULL)
3692 return FAIL;
3693 ++term->tl_job->jv_refcount;
3694
3695 /* behave like the job is already finished */
3696 term->tl_job->jv_status = JOB_FINISHED;
3697
3698 return mch_create_pty_channel(term->tl_job, opt);
3699}
3700
3701/*
3702 * Free the terminal emulator part of "term".
3703 */
3704 static void
3705term_free_vterm(term_T *term)
3706{
3707 if (term->tl_vterm != NULL)
3708 vterm_free(term->tl_vterm);
3709 term->tl_vterm = NULL;
3710}
3711
3712/*
3713 * Request size to terminal.
3714 */
3715 static void
3716term_report_winsize(term_T *term, int rows, int cols)
3717{
3718 /* Use an ioctl() to report the new window size to the job. */
3719 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3720 {
3721 int fd = -1;
3722 int part;
3723
3724 for (part = PART_OUT; part < PART_COUNT; ++part)
3725 {
3726 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3727 if (isatty(fd))
3728 break;
3729 }
3730 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3731 mch_signal_job(term->tl_job, (char_u *)"winch");
3732 }
3733}
3734
3735# endif
3736
3737#endif /* FEAT_TERMINAL */