blob: a2858a2b0024f07b73a42bb31d52ca1681959836 [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)
45 * - Shift-Tab does not work.
Bram Moolenaar3a497e12017-09-30 20:40:27 +020046 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020047 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
48 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020049 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010050 * - When closing gvim with an active terminal buffer, the dialog suggests
51 * saving the buffer. Should say something else. (Manas Thakur, #2215)
52 * Also: #2223
Bram Moolenaarba6febd2017-10-30 21:56:23 +010053 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020054 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaarff546792017-11-21 14:47:57 +010055 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020056 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010057 * - After executing a shell command the status line isn't redraw.
Bram Moolenaarba6febd2017-10-30 21:56:23 +010058 * - What to store in a session file? Shell at the prompt would be OK to
59 * restore, but others may not. Open the window and let the user start the
60 * command?
Bram Moolenaar46359e12017-11-29 22:33:38 +010061 * - implement term_setsize()
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020062 * - add test for giving error for invalid 'termsize' value.
63 * - support minimal size when 'termsize' is "rows*cols".
64 * - support minimal size when 'termsize' is empty?
65 * - GUI: when using tabs, focus in terminal, click on tab does not work.
66 * - GUI: when 'confirm' is set and trying to exit Vim, dialog offers to save
67 * changes to "!shell".
68 * (justrajdeep, 2017 Aug 22)
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020069 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020070 * - For the GUI fill termios with default values, perhaps like pangoterm:
71 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
72 * - if the job in the terminal does not support the mouse, we can use the
73 * mouse in the Terminal window for copy/paste.
74 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
75 * conversions.
76 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
77 * the window and position it higher up when it gets filled, so it looks like
78 * the text scrolls up.
79 * - Copy text in the vterm to the Vim buffer once in a while, so that
80 * completion works.
81 * - add an optional limit for the scrollback size. When reaching it remove
82 * 10% at the start.
83 */
84
85#include "vim.h"
86
87#if defined(FEAT_TERMINAL) || defined(PROTO)
88
89#ifndef MIN
90# define MIN(x,y) ((x) < (y) ? (x) : (y))
91#endif
92#ifndef MAX
93# define MAX(x,y) ((x) > (y) ? (x) : (y))
94#endif
95
96#include "libvterm/include/vterm.h"
97
98/* This is VTermScreenCell without the characters, thus much smaller. */
99typedef struct {
100 VTermScreenCellAttrs attrs;
101 char width;
102 VTermColor fg, bg;
103} cellattr_T;
104
105typedef struct sb_line_S {
106 int sb_cols; /* can differ per line */
107 cellattr_T *sb_cells; /* allocated */
108 cellattr_T sb_fill_attr; /* for short line */
109} sb_line_T;
110
111/* typedef term_T in structs.h */
112struct terminal_S {
113 term_T *tl_next;
114
115 VTerm *tl_vterm;
116 job_T *tl_job;
117 buf_T *tl_buffer;
118
119 /* Set when setting the size of a vterm, reset after redrawing. */
120 int tl_vterm_size_changed;
121
122 /* used when tl_job is NULL and only a pty was created */
123 int tl_tty_fd;
124 char_u *tl_tty_in;
125 char_u *tl_tty_out;
126
127 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
128 int tl_channel_closed;
129 int tl_finish; /* 'c' for ++close, 'o' for ++open */
130 char_u *tl_opencmd;
131 char_u *tl_eof_chars;
132
133#ifdef WIN3264
134 void *tl_winpty_config;
135 void *tl_winpty;
136#endif
137
138 /* last known vterm size */
139 int tl_rows;
140 int tl_cols;
141 /* vterm size does not follow window size */
142 int tl_rows_fixed;
143 int tl_cols_fixed;
144
145 char_u *tl_title; /* NULL or allocated */
146 char_u *tl_status_text; /* NULL or allocated */
147
148 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200149 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200150 int tl_dirty_row_end; /* row below last one to update */
151
152 garray_T tl_scrollback;
153 int tl_scrollback_scrolled;
154 cellattr_T tl_default_color;
155
156 VTermPos tl_cursor_pos;
157 int tl_cursor_visible;
158 int tl_cursor_blink;
159 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
160 char_u *tl_cursor_color; /* NULL or allocated */
161
162 int tl_using_altscreen;
163};
164
165#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
166#define TMODE_LOOP 2 /* CTRL-W N used */
167
168/*
169 * List of all active terminals.
170 */
171static term_T *first_term = NULL;
172
173/* Terminal active in terminal_loop(). */
174static term_T *in_terminal_loop = NULL;
175
176#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
177#define KEY_BUF_LEN 200
178
179/*
180 * Functions with separate implementation for MS-Windows and Unix-like systems.
181 */
182static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
183static int create_pty_only(term_T *term, jobopt_T *opt);
184static void term_report_winsize(term_T *term, int rows, int cols);
185static void term_free_vterm(term_T *term);
186
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100187/* The character that we know (or assume) that the terminal expects for the
188 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200189static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
191
192/**************************************
193 * 1. Generic code for all systems.
194 */
195
196/*
197 * Determine the terminal size from 'termsize' and the current window.
198 * Assumes term->tl_rows and term->tl_cols are zero.
199 */
200 static void
201set_term_and_win_size(term_T *term)
202{
203 if (*curwin->w_p_tms != NUL)
204 {
205 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
206
207 term->tl_rows = atoi((char *)curwin->w_p_tms);
208 term->tl_cols = atoi((char *)p);
209 }
210 if (term->tl_rows == 0)
211 term->tl_rows = curwin->w_height;
212 else
213 {
214 win_setheight_win(term->tl_rows, curwin);
215 term->tl_rows_fixed = TRUE;
216 }
217 if (term->tl_cols == 0)
218 term->tl_cols = curwin->w_width;
219 else
220 {
221 win_setwidth_win(term->tl_cols, curwin);
222 term->tl_cols_fixed = TRUE;
223 }
224}
225
226/*
227 * Initialize job options for a terminal job.
228 * Caller may overrule some of them.
229 */
230 static void
231init_job_options(jobopt_T *opt)
232{
233 clear_job_options(opt);
234
235 opt->jo_mode = MODE_RAW;
236 opt->jo_out_mode = MODE_RAW;
237 opt->jo_err_mode = MODE_RAW;
238 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
239}
240
241/*
242 * Set job options mandatory for a terminal job.
243 */
244 static void
245setup_job_options(jobopt_T *opt, int rows, int cols)
246{
247 if (!(opt->jo_set & JO_OUT_IO))
248 {
249 /* Connect stdout to the terminal. */
250 opt->jo_io[PART_OUT] = JIO_BUFFER;
251 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
252 opt->jo_modifiable[PART_OUT] = 0;
253 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
254 }
255
256 if (!(opt->jo_set & JO_ERR_IO))
257 {
258 /* Connect stderr to the terminal. */
259 opt->jo_io[PART_ERR] = JIO_BUFFER;
260 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
261 opt->jo_modifiable[PART_ERR] = 0;
262 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
263 }
264
265 opt->jo_pty = TRUE;
266 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
267 opt->jo_term_rows = rows;
268 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
269 opt->jo_term_cols = cols;
270}
271
272/*
273 * Start a terminal window and return its buffer.
274 * Returns NULL when failed.
275 */
276 static buf_T *
277term_start(typval_T *argvar, jobopt_T *opt, int forceit)
278{
279 exarg_T split_ea;
280 win_T *old_curwin = curwin;
281 term_T *term;
282 buf_T *old_curbuf = NULL;
283 int res;
284 buf_T *newbuf;
285
286 if (check_restricted() || check_secure())
287 return NULL;
288
289 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
290 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
291 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
292 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
293 {
294 EMSG(_(e_invarg));
295 return NULL;
296 }
297
298 term = (term_T *)alloc_clear(sizeof(term_T));
299 if (term == NULL)
300 return NULL;
301 term->tl_dirty_row_end = MAX_ROW;
302 term->tl_cursor_visible = TRUE;
303 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
304 term->tl_finish = opt->jo_term_finish;
305 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
306
307 vim_memset(&split_ea, 0, sizeof(split_ea));
308 if (opt->jo_curwin)
309 {
310 /* Create a new buffer in the current window. */
311 if (!can_abandon(curbuf, forceit))
312 {
313 no_write_message();
314 vim_free(term);
315 return NULL;
316 }
317 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
318 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
319 {
320 vim_free(term);
321 return NULL;
322 }
323 }
324 else if (opt->jo_hidden)
325 {
326 buf_T *buf;
327
328 /* Create a new buffer without a window. Make it the current buffer for
329 * a moment to be able to do the initialisations. */
330 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
331 BLN_NEW | BLN_LISTED);
332 if (buf == NULL || ml_open(buf) == FAIL)
333 {
334 vim_free(term);
335 return NULL;
336 }
337 old_curbuf = curbuf;
338 --curbuf->b_nwindows;
339 curbuf = buf;
340 curwin->w_buffer = buf;
341 ++curbuf->b_nwindows;
342 }
343 else
344 {
345 /* Open a new window or tab. */
346 split_ea.cmdidx = CMD_new;
347 split_ea.cmd = (char_u *)"new";
348 split_ea.arg = (char_u *)"";
349 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
350 {
351 split_ea.line2 = opt->jo_term_rows;
352 split_ea.addr_count = 1;
353 }
354 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
355 {
356 split_ea.line2 = opt->jo_term_cols;
357 split_ea.addr_count = 1;
358 }
359
360 ex_splitview(&split_ea);
361 if (curwin == old_curwin)
362 {
363 /* split failed */
364 vim_free(term);
365 return NULL;
366 }
367 }
368 term->tl_buffer = curbuf;
369 curbuf->b_term = term;
370
371 if (!opt->jo_hidden)
372 {
373 /* only one size was taken care of with :new, do the other one */
374 if (opt->jo_term_rows > 0 && (cmdmod.split & WSP_VERT))
375 win_setheight(opt->jo_term_rows);
376 if (opt->jo_term_cols > 0 && !(cmdmod.split & WSP_VERT))
377 win_setwidth(opt->jo_term_cols);
378 }
379
380 /* Link the new terminal in the list of active terminals. */
381 term->tl_next = first_term;
382 first_term = term;
383
384 if (opt->jo_term_name != NULL)
385 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
386 else
387 {
388 int i;
389 size_t len;
390 char_u *cmd, *p;
391
392 if (argvar->v_type == VAR_STRING)
393 {
394 cmd = argvar->vval.v_string;
395 if (cmd == NULL)
396 cmd = (char_u *)"";
397 else if (STRCMP(cmd, "NONE") == 0)
398 cmd = (char_u *)"pty";
399 }
400 else if (argvar->v_type != VAR_LIST
401 || argvar->vval.v_list == NULL
402 || argvar->vval.v_list->lv_len < 1
403 || (cmd = get_tv_string_chk(
404 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
405 cmd = (char_u*)"";
406
407 len = STRLEN(cmd) + 10;
408 p = alloc((int)len);
409
410 for (i = 0; p != NULL; ++i)
411 {
412 /* Prepend a ! to the command name to avoid the buffer name equals
413 * the executable, otherwise ":w!" would overwrite it. */
414 if (i == 0)
415 vim_snprintf((char *)p, len, "!%s", cmd);
416 else
417 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
418 if (buflist_findname(p) == NULL)
419 {
420 vim_free(curbuf->b_ffname);
421 curbuf->b_ffname = p;
422 break;
423 }
424 }
425 }
426 curbuf->b_fname = curbuf->b_ffname;
427
428 if (opt->jo_term_opencmd != NULL)
429 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
430
431 if (opt->jo_eof_chars != NULL)
432 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
433
434 set_string_option_direct((char_u *)"buftype", -1,
435 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
436
437 /* Mark the buffer as not modifiable. It can only be made modifiable after
438 * the job finished. */
439 curbuf->b_p_ma = FALSE;
440
441 set_term_and_win_size(term);
442 setup_job_options(opt, term->tl_rows, term->tl_cols);
443
444 /* System dependent: setup the vterm and maybe start the job in it. */
445 if (argvar->v_type == VAR_STRING
446 && argvar->vval.v_string != NULL
447 && STRCMP(argvar->vval.v_string, "NONE") == 0)
448 res = create_pty_only(term, opt);
449 else
450 res = term_and_job_init(term, argvar, opt);
451
452 newbuf = curbuf;
453 if (res == OK)
454 {
455 /* Get and remember the size we ended up with. Update the pty. */
456 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
457 term_report_winsize(term, term->tl_rows, term->tl_cols);
458
459 /* Make sure we don't get stuck on sending keys to the job, it leads to
460 * a deadlock if the job is waiting for Vim to read. */
461 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
462
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200463#ifdef FEAT_AUTOCMD
464 ++curbuf->b_locked;
465 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
466 --curbuf->b_locked;
467#endif
468
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200469 if (old_curbuf != NULL)
470 {
471 --curbuf->b_nwindows;
472 curbuf = old_curbuf;
473 curwin->w_buffer = curbuf;
474 ++curbuf->b_nwindows;
475 }
476 }
477 else
478 {
479 buf_T *buf = curbuf;
480
481 free_terminal(curbuf);
482 if (old_curbuf != NULL)
483 {
484 --curbuf->b_nwindows;
485 curbuf = old_curbuf;
486 curwin->w_buffer = curbuf;
487 ++curbuf->b_nwindows;
488 }
489
490 /* Wiping out the buffer will also close the window and call
491 * free_terminal(). */
492 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
493 return NULL;
494 }
495 return newbuf;
496}
497
498/*
499 * ":terminal": open a terminal window and execute a job in it.
500 */
501 void
502ex_terminal(exarg_T *eap)
503{
504 typval_T argvar[2];
505 jobopt_T opt;
506 char_u *cmd;
507 char_u *tofree = NULL;
508
509 init_job_options(&opt);
510
511 cmd = eap->arg;
512 while (*cmd && *cmd == '+' && *(cmd + 1) == '+')
513 {
514 char_u *p, *ep;
515
516 cmd += 2;
517 p = skiptowhite(cmd);
518 ep = vim_strchr(cmd, '=');
519 if (ep != NULL && ep < p)
520 p = ep;
521
522 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
523 opt.jo_term_finish = 'c';
524 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
525 opt.jo_term_finish = 'o';
526 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
527 opt.jo_curwin = 1;
528 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
529 opt.jo_hidden = 1;
530 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
531 && ep != NULL && isdigit(ep[1]))
532 {
533 opt.jo_set2 |= JO2_TERM_ROWS;
534 opt.jo_term_rows = atoi((char *)ep + 1);
535 p = skiptowhite(cmd);
536 }
537 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
538 && ep != NULL && isdigit(ep[1]))
539 {
540 opt.jo_set2 |= JO2_TERM_COLS;
541 opt.jo_term_cols = atoi((char *)ep + 1);
542 p = skiptowhite(cmd);
543 }
544 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
545 && ep != NULL)
546 {
547 char_u *buf = NULL;
548 char_u *keys;
549
550 p = skiptowhite(cmd);
551 *p = NUL;
552 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
553 opt.jo_set2 |= JO2_EOF_CHARS;
554 opt.jo_eof_chars = vim_strsave(keys);
555 vim_free(buf);
556 *p = ' ';
557 }
558 else
559 {
560 if (*p)
561 *p = NUL;
562 EMSG2(_("E181: Invalid attribute: %s"), cmd);
563 return;
564 }
565 cmd = skipwhite(p);
566 }
567 if (*cmd == NUL)
568 /* Make a copy of 'shell', an autocommand may change the option. */
569 tofree = cmd = vim_strsave(p_sh);
570
571 if (eap->addr_count > 0)
572 {
573 /* Write lines from current buffer to the job. */
574 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
575 opt.jo_io[PART_IN] = JIO_BUFFER;
576 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
577 opt.jo_in_top = eap->line1;
578 opt.jo_in_bot = eap->line2;
579 }
580
581 argvar[0].v_type = VAR_STRING;
582 argvar[0].vval.v_string = cmd;
583 argvar[1].v_type = VAR_UNKNOWN;
584 term_start(argvar, &opt, eap->forceit);
585 vim_free(tofree);
586 vim_free(opt.jo_eof_chars);
587}
588
589/*
590 * Free the scrollback buffer for "term".
591 */
592 static void
593free_scrollback(term_T *term)
594{
595 int i;
596
597 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
598 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
599 ga_clear(&term->tl_scrollback);
600}
601
602/*
603 * Free a terminal and everything it refers to.
604 * Kills the job if there is one.
605 * Called when wiping out a buffer.
606 */
607 void
608free_terminal(buf_T *buf)
609{
610 term_T *term = buf->b_term;
611 term_T *tp;
612
613 if (term == NULL)
614 return;
615 if (first_term == term)
616 first_term = term->tl_next;
617 else
618 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
619 if (tp->tl_next == term)
620 {
621 tp->tl_next = term->tl_next;
622 break;
623 }
624
625 if (term->tl_job != NULL)
626 {
627 if (term->tl_job->jv_status != JOB_ENDED
628 && term->tl_job->jv_status != JOB_FINISHED
629 && term->tl_job->jv_status != JOB_FAILED)
630 job_stop(term->tl_job, NULL, "kill");
631 job_unref(term->tl_job);
632 }
633
634 free_scrollback(term);
635
636 term_free_vterm(term);
637 vim_free(term->tl_title);
638 vim_free(term->tl_status_text);
639 vim_free(term->tl_opencmd);
640 vim_free(term->tl_eof_chars);
641 vim_free(term->tl_cursor_color);
642 vim_free(term);
643 buf->b_term = NULL;
644 if (in_terminal_loop == term)
645 in_terminal_loop = NULL;
646}
647
648/*
649 * Write job output "msg[len]" to the vterm.
650 */
651 static void
652term_write_job_output(term_T *term, char_u *msg, size_t len)
653{
654 VTerm *vterm = term->tl_vterm;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200655
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100656 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200657
658 /* this invokes the damage callbacks */
659 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
660}
661
662 static void
663update_cursor(term_T *term, int redraw)
664{
665 if (term->tl_normal_mode)
666 return;
667 setcursor();
668 if (redraw)
669 {
670 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
671 cursor_on();
672 out_flush();
673#ifdef FEAT_GUI
674 if (gui.in_use)
675 gui_update_cursor(FALSE, FALSE);
676#endif
677 }
678}
679
680/*
681 * Invoked when "msg" output from a job was received. Write it to the terminal
682 * of "buffer".
683 */
684 void
685write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
686{
687 size_t len = STRLEN(msg);
688 term_T *term = buffer->b_term;
689
690 if (term->tl_vterm == NULL)
691 {
692 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
693 return;
694 }
695 ch_log(channel, "writing %d bytes to terminal", (int)len);
696 term_write_job_output(term, msg, len);
697
698 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
699 * contents, thus no screen update is needed. */
700 if (!term->tl_normal_mode)
701 {
702 /* TODO: only update once in a while. */
703 ch_log(term->tl_job->jv_channel, "updating screen");
704 if (buffer == curbuf)
705 {
706 update_screen(0);
707 update_cursor(term, TRUE);
708 }
709 else
710 redraw_after_callback(TRUE);
711 }
712}
713
714/*
715 * Send a mouse position and click to the vterm
716 */
717 static int
718term_send_mouse(VTerm *vterm, int button, int pressed)
719{
720 VTermModifier mod = VTERM_MOD_NONE;
721
722 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200723 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100724 if (button != 0)
725 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200726 return TRUE;
727}
728
729/*
730 * Convert typed key "c" into bytes to send to the job.
731 * Return the number of bytes in "buf".
732 */
733 static int
734term_convert_key(term_T *term, int c, char *buf)
735{
736 VTerm *vterm = term->tl_vterm;
737 VTermKey key = VTERM_KEY_NONE;
738 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100739 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200740
741 switch (c)
742 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100743 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
744
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200745 /* don't use VTERM_KEY_BACKSPACE, it always
746 * becomes 0x7f DEL */
747 case K_BS: c = term_backspace_char; break;
748
749 case ESC: key = VTERM_KEY_ESCAPE; break;
750 case K_DEL: key = VTERM_KEY_DEL; break;
751 case K_DOWN: key = VTERM_KEY_DOWN; break;
752 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
753 key = VTERM_KEY_DOWN; break;
754 case K_END: key = VTERM_KEY_END; break;
755 case K_S_END: mod = VTERM_MOD_SHIFT;
756 key = VTERM_KEY_END; break;
757 case K_C_END: mod = VTERM_MOD_CTRL;
758 key = VTERM_KEY_END; break;
759 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
760 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
761 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
762 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
763 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
764 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
765 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
766 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
767 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
768 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
769 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
770 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
771 case K_HOME: key = VTERM_KEY_HOME; break;
772 case K_S_HOME: mod = VTERM_MOD_SHIFT;
773 key = VTERM_KEY_HOME; break;
774 case K_C_HOME: mod = VTERM_MOD_CTRL;
775 key = VTERM_KEY_HOME; break;
776 case K_INS: key = VTERM_KEY_INS; break;
777 case K_K0: key = VTERM_KEY_KP_0; break;
778 case K_K1: key = VTERM_KEY_KP_1; break;
779 case K_K2: key = VTERM_KEY_KP_2; break;
780 case K_K3: key = VTERM_KEY_KP_3; break;
781 case K_K4: key = VTERM_KEY_KP_4; break;
782 case K_K5: key = VTERM_KEY_KP_5; break;
783 case K_K6: key = VTERM_KEY_KP_6; break;
784 case K_K7: key = VTERM_KEY_KP_7; break;
785 case K_K8: key = VTERM_KEY_KP_8; break;
786 case K_K9: key = VTERM_KEY_KP_9; break;
787 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
788 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
789 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
790 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
791 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
792 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
793 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
794 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
795 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
796 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
797 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
798 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
799 case K_LEFT: key = VTERM_KEY_LEFT; break;
800 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
801 key = VTERM_KEY_LEFT; break;
802 case K_C_LEFT: mod = VTERM_MOD_CTRL;
803 key = VTERM_KEY_LEFT; break;
804 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
805 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
806 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
807 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
808 key = VTERM_KEY_RIGHT; break;
809 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
810 key = VTERM_KEY_RIGHT; break;
811 case K_UP: key = VTERM_KEY_UP; break;
812 case K_S_UP: mod = VTERM_MOD_SHIFT;
813 key = VTERM_KEY_UP; break;
814 case TAB: key = VTERM_KEY_TAB; break;
815
Bram Moolenaara42ad572017-11-16 13:08:04 +0100816 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
817 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200818 case K_MOUSELEFT: /* TODO */ return 0;
819 case K_MOUSERIGHT: /* TODO */ return 0;
820
821 case K_LEFTMOUSE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100822 case K_LEFTMOUSE_NM: other = term_send_mouse(vterm, 1, 1); break;
823 case K_LEFTDRAG: other = term_send_mouse(vterm, 1, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200824 case K_LEFTRELEASE:
Bram Moolenaara42ad572017-11-16 13:08:04 +0100825 case K_LEFTRELEASE_NM: other = term_send_mouse(vterm, 1, 0); break;
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100826 case K_MOUSEMOVE: other = term_send_mouse(vterm, 0, 0); break;
Bram Moolenaara42ad572017-11-16 13:08:04 +0100827 case K_MIDDLEMOUSE: other = term_send_mouse(vterm, 2, 1); break;
828 case K_MIDDLEDRAG: other = term_send_mouse(vterm, 2, 1); break;
829 case K_MIDDLERELEASE: other = term_send_mouse(vterm, 2, 0); break;
830 case K_RIGHTMOUSE: other = term_send_mouse(vterm, 3, 1); break;
831 case K_RIGHTDRAG: other = term_send_mouse(vterm, 3, 1); break;
832 case K_RIGHTRELEASE: other = term_send_mouse(vterm, 3, 0); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200833 case K_X1MOUSE: /* TODO */ return 0;
834 case K_X1DRAG: /* TODO */ return 0;
835 case K_X1RELEASE: /* TODO */ return 0;
836 case K_X2MOUSE: /* TODO */ return 0;
837 case K_X2DRAG: /* TODO */ return 0;
838 case K_X2RELEASE: /* TODO */ return 0;
839
840 case K_IGNORE: return 0;
841 case K_NOP: return 0;
842 case K_UNDO: return 0;
843 case K_HELP: return 0;
844 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
845 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
846 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
847 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
848 case K_SELECT: return 0;
849#ifdef FEAT_GUI
850 case K_VER_SCROLLBAR: return 0;
851 case K_HOR_SCROLLBAR: return 0;
852#endif
853#ifdef FEAT_GUI_TABLINE
854 case K_TABLINE: return 0;
855 case K_TABMENU: return 0;
856#endif
857#ifdef FEAT_NETBEANS_INTG
858 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
859#endif
860#ifdef FEAT_DND
861 case K_DROP: return 0;
862#endif
863#ifdef FEAT_AUTOCMD
864 case K_CURSORHOLD: return 0;
865#endif
Bram Moolenaara42ad572017-11-16 13:08:04 +0100866 case K_PS: vterm_keyboard_start_paste(vterm);
867 other = TRUE;
868 break;
869 case K_PE: vterm_keyboard_end_paste(vterm);
870 other = TRUE;
871 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200872 }
873
874 /*
875 * Convert special keys to vterm keys:
876 * - Write keys to vterm: vterm_keyboard_key()
877 * - Write output to channel.
878 * TODO: use mod_mask
879 */
880 if (key != VTERM_KEY_NONE)
881 /* Special key, let vterm convert it. */
882 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +0100883 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200884 /* Normal character, let vterm convert it. */
885 vterm_keyboard_unichar(vterm, c, mod);
886
887 /* Read back the converted escape sequence. */
888 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
889}
890
891/*
892 * Return TRUE if the job for "term" is still running.
893 */
894 int
895term_job_running(term_T *term)
896{
897 /* Also consider the job finished when the channel is closed, to avoid a
898 * race condition when updating the title. */
899 return term != NULL
900 && term->tl_job != NULL
901 && channel_is_open(term->tl_job->jv_channel)
902 && (term->tl_job->jv_status == JOB_STARTED
903 || term->tl_job->jv_channel->ch_keep_open);
904}
905
906/*
907 * Return TRUE if "term" has an active channel and used ":term NONE".
908 */
909 int
910term_none_open(term_T *term)
911{
912 /* Also consider the job finished when the channel is closed, to avoid a
913 * race condition when updating the title. */
914 return term != NULL
915 && term->tl_job != NULL
916 && channel_is_open(term->tl_job->jv_channel)
917 && term->tl_job->jv_channel->ch_keep_open;
918}
919
920/*
921 * Add the last line of the scrollback buffer to the buffer in the window.
922 */
923 static void
924add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
925{
926 buf_T *buf = term->tl_buffer;
927 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
928 linenr_T lnum = buf->b_ml.ml_line_count;
929
930#ifdef WIN3264
931 if (!enc_utf8 && enc_codepage > 0)
932 {
933 WCHAR *ret = NULL;
934 int length = 0;
935
936 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
937 &ret, &length);
938 if (ret != NULL)
939 {
940 WideCharToMultiByte_alloc(enc_codepage, 0,
941 ret, length, (char **)&text, &len, 0, 0);
942 vim_free(ret);
943 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
944 vim_free(text);
945 }
946 }
947 else
948#endif
949 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
950 if (empty)
951 {
952 /* Delete the empty line that was in the empty buffer. */
953 curbuf = buf;
954 ml_delete(1, FALSE);
955 curbuf = curwin->w_buffer;
956 }
957}
958
959 static void
960cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
961{
962 attr->width = cell->width;
963 attr->attrs = cell->attrs;
964 attr->fg = cell->fg;
965 attr->bg = cell->bg;
966}
967
968 static int
969equal_celattr(cellattr_T *a, cellattr_T *b)
970{
971 /* Comparing the colors should be sufficient. */
972 return a->fg.red == b->fg.red
973 && a->fg.green == b->fg.green
974 && a->fg.blue == b->fg.blue
975 && a->bg.red == b->bg.red
976 && a->bg.green == b->bg.green
977 && a->bg.blue == b->bg.blue;
978}
979
980
981/*
982 * Add the current lines of the terminal to scrollback and to the buffer.
983 * Called after the job has ended and when switching to Terminal-Normal mode.
984 */
985 static void
986move_terminal_to_buffer(term_T *term)
987{
988 win_T *wp;
989 int len;
990 int lines_skipped = 0;
991 VTermPos pos;
992 VTermScreenCell cell;
993 cellattr_T fill_attr, new_fill_attr;
994 cellattr_T *p;
995 VTermScreen *screen;
996
997 if (term->tl_vterm == NULL)
998 return;
999 screen = vterm_obtain_screen(term->tl_vterm);
1000 fill_attr = new_fill_attr = term->tl_default_color;
1001
1002 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1003 {
1004 len = 0;
1005 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1006 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1007 && cell.chars[0] != NUL)
1008 {
1009 len = pos.col + 1;
1010 new_fill_attr = term->tl_default_color;
1011 }
1012 else
1013 /* Assume the last attr is the filler attr. */
1014 cell2cellattr(&cell, &new_fill_attr);
1015
1016 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1017 ++lines_skipped;
1018 else
1019 {
1020 while (lines_skipped > 0)
1021 {
1022 /* Line was skipped, add an empty line. */
1023 --lines_skipped;
1024 if (ga_grow(&term->tl_scrollback, 1) == OK)
1025 {
1026 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1027 + term->tl_scrollback.ga_len;
1028
1029 line->sb_cols = 0;
1030 line->sb_cells = NULL;
1031 line->sb_fill_attr = fill_attr;
1032 ++term->tl_scrollback.ga_len;
1033
1034 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1035 }
1036 }
1037
1038 if (len == 0)
1039 p = NULL;
1040 else
1041 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1042 if ((p != NULL || len == 0)
1043 && ga_grow(&term->tl_scrollback, 1) == OK)
1044 {
1045 garray_T ga;
1046 int width;
1047 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1048 + term->tl_scrollback.ga_len;
1049
1050 ga_init2(&ga, 1, 100);
1051 for (pos.col = 0; pos.col < len; pos.col += width)
1052 {
1053 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1054 {
1055 width = 1;
1056 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1057 if (ga_grow(&ga, 1) == OK)
1058 ga.ga_len += utf_char2bytes(' ',
1059 (char_u *)ga.ga_data + ga.ga_len);
1060 }
1061 else
1062 {
1063 width = cell.width;
1064
1065 cell2cellattr(&cell, &p[pos.col]);
1066
1067 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1068 {
1069 int i;
1070 int c;
1071
1072 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1073 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1074 (char_u *)ga.ga_data + ga.ga_len);
1075 }
1076 }
1077 }
1078 line->sb_cols = len;
1079 line->sb_cells = p;
1080 line->sb_fill_attr = new_fill_attr;
1081 fill_attr = new_fill_attr;
1082 ++term->tl_scrollback.ga_len;
1083
1084 if (ga_grow(&ga, 1) == FAIL)
1085 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1086 else
1087 {
1088 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1089 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1090 }
1091 ga_clear(&ga);
1092 }
1093 else
1094 vim_free(p);
1095 }
1096 }
1097
1098 /* Obtain the current background color. */
1099 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1100 &term->tl_default_color.fg, &term->tl_default_color.bg);
1101
1102 FOR_ALL_WINDOWS(wp)
1103 {
1104 if (wp->w_buffer == term->tl_buffer)
1105 {
1106 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1107 wp->w_cursor.col = 0;
1108 wp->w_valid = 0;
1109 if (wp->w_cursor.lnum >= wp->w_height)
1110 {
1111 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1112
1113 if (wp->w_topline < min_topline)
1114 wp->w_topline = min_topline;
1115 }
1116 redraw_win_later(wp, NOT_VALID);
1117 }
1118 }
1119}
1120
1121 static void
1122set_terminal_mode(term_T *term, int normal_mode)
1123{
1124 term->tl_normal_mode = normal_mode;
1125 vim_free(term->tl_status_text);
1126 term->tl_status_text = NULL;
1127 if (term->tl_buffer == curbuf)
1128 maketitle();
1129}
1130
1131/*
1132 * Called after the job if finished and Terminal mode is not active:
1133 * Move the vterm contents into the scrollback buffer and free the vterm.
1134 */
1135 static void
1136cleanup_vterm(term_T *term)
1137{
1138 if (term->tl_finish != 'c')
1139 move_terminal_to_buffer(term);
1140 term_free_vterm(term);
1141 set_terminal_mode(term, FALSE);
1142}
1143
1144/*
1145 * Switch from Terminal-Job mode to Terminal-Normal mode.
1146 * Suspends updating the terminal window.
1147 */
1148 static void
1149term_enter_normal_mode(void)
1150{
1151 term_T *term = curbuf->b_term;
1152
1153 /* Append the current terminal contents to the buffer. */
1154 move_terminal_to_buffer(term);
1155
1156 set_terminal_mode(term, TRUE);
1157
1158 /* Move the window cursor to the position of the cursor in the
1159 * terminal. */
1160 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1161 + term->tl_cursor_pos.row + 1;
1162 check_cursor();
1163 coladvance(term->tl_cursor_pos.col);
1164
1165 /* Display the same lines as in the terminal. */
1166 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1167}
1168
1169/*
1170 * Returns TRUE if the current window contains a terminal and we are in
1171 * Terminal-Normal mode.
1172 */
1173 int
1174term_in_normal_mode(void)
1175{
1176 term_T *term = curbuf->b_term;
1177
1178 return term != NULL && term->tl_normal_mode;
1179}
1180
1181/*
1182 * Switch from Terminal-Normal mode to Terminal-Job mode.
1183 * Restores updating the terminal window.
1184 */
1185 void
1186term_enter_job_mode()
1187{
1188 term_T *term = curbuf->b_term;
1189 sb_line_T *line;
1190 garray_T *gap;
1191
1192 /* Remove the terminal contents from the scrollback and the buffer. */
1193 gap = &term->tl_scrollback;
1194 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1195 && gap->ga_len > 0)
1196 {
1197 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1198 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1199 vim_free(line->sb_cells);
1200 --gap->ga_len;
1201 }
1202 check_cursor();
1203
1204 set_terminal_mode(term, FALSE);
1205
1206 if (term->tl_channel_closed)
1207 cleanup_vterm(term);
1208 redraw_buf_and_status_later(curbuf, NOT_VALID);
1209}
1210
1211/*
1212 * Get a key from the user without mapping.
1213 * Note: while waiting a terminal may be closed and freed if the channel is
1214 * closed and ++close was used.
1215 * Uses terminal mode mappings.
1216 */
1217 static int
1218term_vgetc()
1219{
1220 int c;
1221 int save_State = State;
1222
1223 State = TERMINAL;
1224 got_int = FALSE;
1225#ifdef WIN3264
1226 ctrl_break_was_pressed = FALSE;
1227#endif
1228 c = vgetc();
1229 got_int = FALSE;
1230 State = save_State;
1231 return c;
1232}
1233
1234/*
1235 * Get the part that is connected to the tty. Normally this is PART_IN, but
1236 * when writing buffer lines to the job it can be another. This makes it
1237 * possible to do "1,5term vim -".
1238 */
1239 static ch_part_T
1240get_tty_part(term_T *term)
1241{
1242#ifdef UNIX
1243 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
1244 int i;
1245
1246 for (i = 0; i < 3; ++i)
1247 {
1248 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
1249
1250 if (isatty(fd))
1251 return parts[i];
1252 }
1253#endif
1254 return PART_IN;
1255}
1256
1257/*
1258 * Send keys to terminal.
1259 * Return FAIL when the key needs to be handled in Normal mode.
1260 * Return OK when the key was dropped or sent to the terminal.
1261 */
1262 int
1263send_keys_to_term(term_T *term, int c, int typed)
1264{
1265 char msg[KEY_BUF_LEN];
1266 size_t len;
1267 static int mouse_was_outside = FALSE;
1268 int dragging_outside = FALSE;
1269
1270 /* Catch keys that need to be handled as in Normal mode. */
1271 switch (c)
1272 {
1273 case NUL:
1274 case K_ZERO:
1275 if (typed)
1276 stuffcharReadbuff(c);
1277 return FAIL;
1278
1279 case K_IGNORE:
1280 return FAIL;
1281
1282 case K_LEFTDRAG:
1283 case K_MIDDLEDRAG:
1284 case K_RIGHTDRAG:
1285 case K_X1DRAG:
1286 case K_X2DRAG:
1287 dragging_outside = mouse_was_outside;
1288 /* FALLTHROUGH */
1289 case K_LEFTMOUSE:
1290 case K_LEFTMOUSE_NM:
1291 case K_LEFTRELEASE:
1292 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001293 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001294 case K_MIDDLEMOUSE:
1295 case K_MIDDLERELEASE:
1296 case K_RIGHTMOUSE:
1297 case K_RIGHTRELEASE:
1298 case K_X1MOUSE:
1299 case K_X1RELEASE:
1300 case K_X2MOUSE:
1301 case K_X2RELEASE:
1302
1303 case K_MOUSEUP:
1304 case K_MOUSEDOWN:
1305 case K_MOUSELEFT:
1306 case K_MOUSERIGHT:
1307 if (mouse_row < W_WINROW(curwin)
Bram Moolenaar73675fb2017-11-20 21:49:19 +01001308 || mouse_row > (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001309 || mouse_col < curwin->w_wincol
Bram Moolenaar73675fb2017-11-20 21:49:19 +01001310 || mouse_col > W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001311 || dragging_outside)
1312 {
1313 /* click or scroll outside the current window */
1314 if (typed)
1315 {
1316 stuffcharReadbuff(c);
1317 mouse_was_outside = TRUE;
1318 }
1319 return FAIL;
1320 }
1321 }
1322 if (typed)
1323 mouse_was_outside = FALSE;
1324
1325 /* Convert the typed key to a sequence of bytes for the job. */
1326 len = term_convert_key(term, c, msg);
1327 if (len > 0)
1328 /* TODO: if FAIL is returned, stop? */
1329 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1330 (char_u *)msg, (int)len, NULL);
1331
1332 return OK;
1333}
1334
1335 static void
1336position_cursor(win_T *wp, VTermPos *pos)
1337{
1338 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1339 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1340 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1341}
1342
1343/*
1344 * Handle CTRL-W "": send register contents to the job.
1345 */
1346 static void
1347term_paste_register(int prev_c UNUSED)
1348{
1349 int c;
1350 list_T *l;
1351 listitem_T *item;
1352 long reglen = 0;
1353 int type;
1354
1355#ifdef FEAT_CMDL_INFO
1356 if (add_to_showcmd(prev_c))
1357 if (add_to_showcmd('"'))
1358 out_flush();
1359#endif
1360 c = term_vgetc();
1361#ifdef FEAT_CMDL_INFO
1362 clear_showcmd();
1363#endif
1364 if (!term_use_loop())
1365 /* job finished while waiting for a character */
1366 return;
1367
1368 /* CTRL-W "= prompt for expression to evaluate. */
1369 if (c == '=' && get_expr_register() != '=')
1370 return;
1371 if (!term_use_loop())
1372 /* job finished while waiting for a character */
1373 return;
1374
1375 l = (list_T *)get_reg_contents(c, GREG_LIST);
1376 if (l != NULL)
1377 {
1378 type = get_reg_type(c, &reglen);
1379 for (item = l->lv_first; item != NULL; item = item->li_next)
1380 {
1381 char_u *s = get_tv_string(&item->li_tv);
1382#ifdef WIN3264
1383 char_u *tmp = s;
1384
1385 if (!enc_utf8 && enc_codepage > 0)
1386 {
1387 WCHAR *ret = NULL;
1388 int length = 0;
1389
1390 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1391 (int)STRLEN(s), &ret, &length);
1392 if (ret != NULL)
1393 {
1394 WideCharToMultiByte_alloc(CP_UTF8, 0,
1395 ret, length, (char **)&s, &length, 0, 0);
1396 vim_free(ret);
1397 }
1398 }
1399#endif
1400 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1401 s, (int)STRLEN(s), NULL);
1402#ifdef WIN3264
1403 if (tmp != s)
1404 vim_free(s);
1405#endif
1406
1407 if (item->li_next != NULL || type == MLINE)
1408 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1409 (char_u *)"\r", 1, NULL);
1410 }
1411 list_free(l);
1412 }
1413}
1414
1415#if defined(FEAT_GUI) || defined(PROTO)
1416/*
1417 * Return TRUE when the cursor of the terminal should be displayed.
1418 */
1419 int
1420terminal_is_active()
1421{
1422 return in_terminal_loop != NULL;
1423}
1424
1425 cursorentry_T *
1426term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1427{
1428 term_T *term = in_terminal_loop;
1429 static cursorentry_T entry;
1430
1431 vim_memset(&entry, 0, sizeof(entry));
1432 entry.shape = entry.mshape =
1433 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1434 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1435 SHAPE_BLOCK;
1436 entry.percentage = 20;
1437 if (term->tl_cursor_blink)
1438 {
1439 entry.blinkwait = 700;
1440 entry.blinkon = 400;
1441 entry.blinkoff = 250;
1442 }
1443 *fg = gui.back_pixel;
1444 if (term->tl_cursor_color == NULL)
1445 *bg = gui.norm_pixel;
1446 else
1447 *bg = color_name2handle(term->tl_cursor_color);
1448 entry.name = "n";
1449 entry.used_for = SHAPE_CURSOR;
1450
1451 return &entry;
1452}
1453#endif
1454
1455static int did_change_cursor = FALSE;
1456
1457 static void
1458may_set_cursor_props(term_T *term)
1459{
1460#ifdef FEAT_GUI
1461 /* For the GUI the cursor properties are obtained with
1462 * term_get_cursor_shape(). */
1463 if (gui.in_use)
1464 return;
1465#endif
1466 if (in_terminal_loop == term)
1467 {
1468 did_change_cursor = TRUE;
1469 if (term->tl_cursor_color != NULL)
1470 term_cursor_color(term->tl_cursor_color);
1471 else
1472 term_cursor_color((char_u *)"");
1473 term_cursor_shape(term->tl_cursor_shape, term->tl_cursor_blink);
1474 }
1475}
1476
1477 static void
1478may_restore_cursor_props(void)
1479{
1480#ifdef FEAT_GUI
1481 if (gui.in_use)
1482 return;
1483#endif
1484 if (did_change_cursor)
1485 {
1486 did_change_cursor = FALSE;
1487 term_cursor_color((char_u *)"");
1488 /* this will restore the initial cursor style, if possible */
1489 ui_cursor_shape_forced(TRUE);
1490 }
1491}
1492
1493/*
1494 * Returns TRUE if the current window contains a terminal and we are sending
1495 * keys to the job.
1496 */
1497 int
1498term_use_loop(void)
1499{
1500 term_T *term = curbuf->b_term;
1501
1502 return term != NULL
1503 && !term->tl_normal_mode
1504 && term->tl_vterm != NULL
1505 && term_job_running(term);
1506}
1507
1508/*
1509 * Wait for input and send it to the job.
1510 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1511 * when there is no more typahead.
1512 * Return when the start of a CTRL-W command is typed or anything else that
1513 * should be handled as a Normal mode command.
1514 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1515 * the terminal was closed.
1516 */
1517 int
1518terminal_loop(int blocking)
1519{
1520 int c;
1521 int termkey = 0;
1522 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001523#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001524 int tty_fd = curbuf->b_term->tl_job->jv_channel
1525 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001526#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001527
1528 /* Remember the terminal we are sending keys to. However, the terminal
1529 * might be closed while waiting for a character, e.g. typing "exit" in a
1530 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1531 * stored reference. */
1532 in_terminal_loop = curbuf->b_term;
1533
1534 if (*curwin->w_p_tk != NUL)
1535 termkey = string_to_key(curwin->w_p_tk, TRUE);
1536 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1537 may_set_cursor_props(curbuf->b_term);
1538
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001539 while (blocking || vpeekc() != NUL)
1540 {
1541 /* TODO: skip screen update when handling a sequence of keys. */
1542 /* Repeat redrawing in case a message is received while redrawing. */
1543 while (must_redraw != 0)
1544 if (update_screen(0) == FAIL)
1545 break;
1546 update_cursor(curbuf->b_term, FALSE);
1547
1548 c = term_vgetc();
1549 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001550 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001551 /* Job finished while waiting for a character. Push back the
1552 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001553 if (c != K_IGNORE)
1554 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001555 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001556 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001557 if (c == K_IGNORE)
1558 continue;
1559
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001560#ifdef UNIX
1561 /*
1562 * The shell or another program may change the tty settings. Getting
1563 * them for every typed character is a bit of overhead, but it's needed
1564 * for the first character typed, e.g. when Vim starts in a shell.
1565 */
1566 if (isatty(tty_fd))
1567 {
1568 ttyinfo_T info;
1569
1570 /* Get the current backspace character of the pty. */
1571 if (get_tty_info(tty_fd, &info) == OK)
1572 term_backspace_char = info.backspace;
1573 }
1574#endif
1575
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001576#ifdef WIN3264
1577 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1578 * Use CTRL-BREAK to kill the job. */
1579 if (ctrl_break_was_pressed)
1580 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1581#endif
1582 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1583 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1584 {
1585 int prev_c = c;
1586
1587#ifdef FEAT_CMDL_INFO
1588 if (add_to_showcmd(c))
1589 out_flush();
1590#endif
1591 c = term_vgetc();
1592#ifdef FEAT_CMDL_INFO
1593 clear_showcmd();
1594#endif
1595 if (!term_use_loop())
1596 /* job finished while waiting for a character */
1597 break;
1598
1599 if (prev_c == Ctrl_BSL)
1600 {
1601 if (c == Ctrl_N)
1602 {
1603 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1604 term_enter_normal_mode();
1605 ret = FAIL;
1606 goto theend;
1607 }
1608 /* Send both keys to the terminal. */
1609 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1610 }
1611 else if (c == Ctrl_C)
1612 {
1613 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1614 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1615 }
1616 else if (termkey == 0 && c == '.')
1617 {
1618 /* "CTRL-W .": send CTRL-W to the job */
1619 c = Ctrl_W;
1620 }
1621 else if (c == 'N')
1622 {
1623 /* CTRL-W N : go to Terminal-Normal mode. */
1624 term_enter_normal_mode();
1625 ret = FAIL;
1626 goto theend;
1627 }
1628 else if (c == '"')
1629 {
1630 term_paste_register(prev_c);
1631 continue;
1632 }
1633 else if (termkey == 0 || c != termkey)
1634 {
1635 stuffcharReadbuff(Ctrl_W);
1636 stuffcharReadbuff(c);
1637 ret = OK;
1638 goto theend;
1639 }
1640 }
1641# ifdef WIN3264
1642 if (!enc_utf8 && has_mbyte && c >= 0x80)
1643 {
1644 WCHAR wc;
1645 char_u mb[3];
1646
1647 mb[0] = (unsigned)c >> 8;
1648 mb[1] = c;
1649 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1650 c = wc;
1651 }
1652# endif
1653 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1654 {
1655 ret = OK;
1656 goto theend;
1657 }
1658 }
1659 ret = FAIL;
1660
1661theend:
1662 in_terminal_loop = NULL;
1663 may_restore_cursor_props();
1664 return ret;
1665}
1666
1667/*
1668 * Called when a job has finished.
1669 * This updates the title and status, but does not close the vterm, because
1670 * there might still be pending output in the channel.
1671 */
1672 void
1673term_job_ended(job_T *job)
1674{
1675 term_T *term;
1676 int did_one = FALSE;
1677
1678 for (term = first_term; term != NULL; term = term->tl_next)
1679 if (term->tl_job == job)
1680 {
1681 vim_free(term->tl_title);
1682 term->tl_title = NULL;
1683 vim_free(term->tl_status_text);
1684 term->tl_status_text = NULL;
1685 redraw_buf_and_status_later(term->tl_buffer, VALID);
1686 did_one = TRUE;
1687 }
1688 if (did_one)
1689 redraw_statuslines();
1690 if (curbuf->b_term != NULL)
1691 {
1692 if (curbuf->b_term->tl_job == job)
1693 maketitle();
1694 update_cursor(curbuf->b_term, TRUE);
1695 }
1696}
1697
1698 static void
1699may_toggle_cursor(term_T *term)
1700{
1701 if (in_terminal_loop == term)
1702 {
1703 if (term->tl_cursor_visible)
1704 cursor_on();
1705 else
1706 cursor_off();
1707 }
1708}
1709
1710/*
1711 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001712 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001713 */
1714 static int
1715color2index(VTermColor *color, int fg, int *boldp)
1716{
1717 int red = color->red;
1718 int blue = color->blue;
1719 int green = color->green;
1720
Bram Moolenaar46359e12017-11-29 22:33:38 +01001721 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001722 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001723 /* First 16 colors and default: use the ANSI index, because these
1724 * colors can be redefined. */
1725 if (t_colors >= 16)
1726 return color->ansi_index;
1727 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001728 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001729 case 0: return 0;
1730 case 1: return lookup_color( 0, fg, boldp) + 1;
1731 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1732 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1733 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1734 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1735 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1736 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1737 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1738 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1739 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1740 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1741 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1742 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1743 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1744 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1745 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001746 }
1747 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001748
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001749 if (t_colors >= 256)
1750 {
1751 if (red == blue && red == green)
1752 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001753 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001754 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001755 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1756 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1757 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001758 int i;
1759
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001760 if (red < 5)
1761 return 17; /* 00/00/00 */
1762 if (red > 245) /* ff/ff/ff */
1763 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001764 for (i = 0; i < 23; ++i)
1765 if (red < cutoff[i])
1766 return i + 233;
1767 return 256;
1768 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001769 {
1770 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1771 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001772
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001773 /* 216-color cube */
1774 for (ri = 0; ri < 5; ++ri)
1775 if (red < cutoff[ri])
1776 break;
1777 for (gi = 0; gi < 5; ++gi)
1778 if (green < cutoff[gi])
1779 break;
1780 for (bi = 0; bi < 5; ++bi)
1781 if (blue < cutoff[bi])
1782 break;
1783 return 17 + ri * 36 + gi * 6 + bi;
1784 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001785 }
1786 return 0;
1787}
1788
1789/*
1790 * Convert the attributes of a vterm cell into an attribute index.
1791 */
1792 static int
1793cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1794{
1795 int attr = 0;
1796
1797 if (cellattrs.bold)
1798 attr |= HL_BOLD;
1799 if (cellattrs.underline)
1800 attr |= HL_UNDERLINE;
1801 if (cellattrs.italic)
1802 attr |= HL_ITALIC;
1803 if (cellattrs.strike)
1804 attr |= HL_STRIKETHROUGH;
1805 if (cellattrs.reverse)
1806 attr |= HL_INVERSE;
1807
1808#ifdef FEAT_GUI
1809 if (gui.in_use)
1810 {
1811 guicolor_T fg, bg;
1812
1813 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1814 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1815 return get_gui_attr_idx(attr, fg, bg);
1816 }
1817 else
1818#endif
1819#ifdef FEAT_TERMGUICOLORS
1820 if (p_tgc)
1821 {
1822 guicolor_T fg, bg;
1823
1824 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1825 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1826
1827 return get_tgc_attr_idx(attr, fg, bg);
1828 }
1829 else
1830#endif
1831 {
1832 int bold = MAYBE;
1833 int fg = color2index(&cellfg, TRUE, &bold);
1834 int bg = color2index(&cellbg, FALSE, &bold);
1835
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001836 /* Use the "Terminal" highlighting for the default colors. */
1837 if (fg == 0 || bg == 0)
1838 {
1839 int id = syn_name2id((char_u *)"Terminal");
1840
1841 if (id != 0 && t_colors >= 16)
1842 {
1843 int cterm_fg, cterm_bg;
1844
1845 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
1846 if (cterm_fg >= 0)
1847 fg = cterm_fg + 1;
1848 if (cterm_bg >= 0)
1849 bg = cterm_bg + 1;
1850 }
1851 }
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];
2473 }
2474 else if (nr < 256)
2475 {
2476 /* 24 grey scale ramp */
2477 idx = nr - 232;
2478 rgb->blue = grey_ramp[idx];
2479 rgb->green = grey_ramp[idx];
2480 rgb->red = grey_ramp[idx];
2481 }
2482}
2483
2484/*
2485 * Create a new vterm and initialize it.
2486 */
2487 static void
2488create_vterm(term_T *term, int rows, int cols)
2489{
2490 VTerm *vterm;
2491 VTermScreen *screen;
2492 VTermValue value;
2493 VTermColor *fg, *bg;
2494 int fgval, bgval;
2495 int id;
2496
2497 vterm = vterm_new(rows, cols);
2498 term->tl_vterm = vterm;
2499 screen = vterm_obtain_screen(vterm);
2500 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2501 /* TODO: depends on 'encoding'. */
2502 vterm_set_utf8(vterm, 1);
2503
2504 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2505 term->tl_default_color.width = 1;
2506 fg = &term->tl_default_color.fg;
2507 bg = &term->tl_default_color.bg;
2508
2509 /* Vterm uses a default black background. Set it to white when
2510 * 'background' is "light". */
2511 if (*p_bg == 'l')
2512 {
2513 fgval = 0;
2514 bgval = 255;
2515 }
2516 else
2517 {
2518 fgval = 255;
2519 bgval = 0;
2520 }
2521 fg->red = fg->green = fg->blue = fgval;
2522 bg->red = bg->green = bg->blue = bgval;
2523
2524 /* The "Terminal" highlight group overrules the defaults. */
2525 id = syn_name2id((char_u *)"Terminal");
2526
Bram Moolenaar46359e12017-11-29 22:33:38 +01002527 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002528#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2529 if (0
2530# ifdef FEAT_GUI
2531 || gui.in_use
2532# endif
2533# ifdef FEAT_TERMGUICOLORS
2534 || p_tgc
2535# endif
2536 )
2537 {
2538 guicolor_T fg_rgb = INVALCOLOR;
2539 guicolor_T bg_rgb = INVALCOLOR;
2540
2541 if (id != 0)
2542 syn_id2colors(id, &fg_rgb, &bg_rgb);
2543
2544# ifdef FEAT_GUI
2545 if (gui.in_use)
2546 {
2547 if (fg_rgb == INVALCOLOR)
2548 fg_rgb = gui.norm_pixel;
2549 if (bg_rgb == INVALCOLOR)
2550 bg_rgb = gui.back_pixel;
2551 }
2552# ifdef FEAT_TERMGUICOLORS
2553 else
2554# endif
2555# endif
2556# ifdef FEAT_TERMGUICOLORS
2557 {
2558 if (fg_rgb == INVALCOLOR)
2559 fg_rgb = cterm_normal_fg_gui_color;
2560 if (bg_rgb == INVALCOLOR)
2561 bg_rgb = cterm_normal_bg_gui_color;
2562 }
2563# endif
2564 if (fg_rgb != INVALCOLOR)
2565 {
2566 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2567
2568 fg->red = (unsigned)(rgb >> 16);
2569 fg->green = (unsigned)(rgb >> 8) & 255;
2570 fg->blue = (unsigned)rgb & 255;
2571 }
2572 if (bg_rgb != INVALCOLOR)
2573 {
2574 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2575
2576 bg->red = (unsigned)(rgb >> 16);
2577 bg->green = (unsigned)(rgb >> 8) & 255;
2578 bg->blue = (unsigned)rgb & 255;
2579 }
2580 }
2581 else
2582#endif
2583 if (id != 0 && t_colors >= 16)
2584 {
2585 int cterm_fg, cterm_bg;
2586
2587 syn_id2cterm_bg(id, &cterm_fg, &cterm_bg);
2588 if (cterm_fg >= 0)
2589 cterm_color2rgb(cterm_fg, fg);
2590 if (cterm_bg >= 0)
2591 cterm_color2rgb(cterm_bg, bg);
2592 }
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/*
2708 * Get the buffer from the first argument in "argvars".
2709 * Returns NULL when the buffer is not for a terminal window.
2710 */
2711 static buf_T *
2712term_get_buf(typval_T *argvars)
2713{
2714 buf_T *buf;
2715
2716 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2717 ++emsg_off;
2718 buf = get_buf_tv(&argvars[0], FALSE);
2719 --emsg_off;
2720 if (buf == NULL || buf->b_term == NULL)
2721 return NULL;
2722 return buf;
2723}
2724
2725/*
2726 * "term_getaltscreen(buf)" function
2727 */
2728 void
2729f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2730{
2731 buf_T *buf = term_get_buf(argvars);
2732
2733 if (buf == NULL)
2734 return;
2735 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2736}
2737
2738/*
2739 * "term_getattr(attr, name)" function
2740 */
2741 void
2742f_term_getattr(typval_T *argvars, typval_T *rettv)
2743{
2744 int attr;
2745 size_t i;
2746 char_u *name;
2747
2748 static struct {
2749 char *name;
2750 int attr;
2751 } attrs[] = {
2752 {"bold", HL_BOLD},
2753 {"italic", HL_ITALIC},
2754 {"underline", HL_UNDERLINE},
2755 {"strike", HL_STRIKETHROUGH},
2756 {"reverse", HL_INVERSE},
2757 };
2758
2759 attr = get_tv_number(&argvars[0]);
2760 name = get_tv_string_chk(&argvars[1]);
2761 if (name == NULL)
2762 return;
2763
2764 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2765 if (STRCMP(name, attrs[i].name) == 0)
2766 {
2767 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2768 break;
2769 }
2770}
2771
2772/*
2773 * "term_getcursor(buf)" function
2774 */
2775 void
2776f_term_getcursor(typval_T *argvars, typval_T *rettv)
2777{
2778 buf_T *buf = term_get_buf(argvars);
2779 term_T *term;
2780 list_T *l;
2781 dict_T *d;
2782
2783 if (rettv_list_alloc(rettv) == FAIL)
2784 return;
2785 if (buf == NULL)
2786 return;
2787 term = buf->b_term;
2788
2789 l = rettv->vval.v_list;
2790 list_append_number(l, term->tl_cursor_pos.row + 1);
2791 list_append_number(l, term->tl_cursor_pos.col + 1);
2792
2793 d = dict_alloc();
2794 if (d != NULL)
2795 {
2796 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2797 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2798 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2799 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2800 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2801 ? (char_u *)"" : term->tl_cursor_color);
2802 list_append_dict(l, d);
2803 }
2804}
2805
2806/*
2807 * "term_getjob(buf)" function
2808 */
2809 void
2810f_term_getjob(typval_T *argvars, typval_T *rettv)
2811{
2812 buf_T *buf = term_get_buf(argvars);
2813
2814 rettv->v_type = VAR_JOB;
2815 rettv->vval.v_job = NULL;
2816 if (buf == NULL)
2817 return;
2818
2819 rettv->vval.v_job = buf->b_term->tl_job;
2820 if (rettv->vval.v_job != NULL)
2821 ++rettv->vval.v_job->jv_refcount;
2822}
2823
2824 static int
2825get_row_number(typval_T *tv, term_T *term)
2826{
2827 if (tv->v_type == VAR_STRING
2828 && tv->vval.v_string != NULL
2829 && STRCMP(tv->vval.v_string, ".") == 0)
2830 return term->tl_cursor_pos.row;
2831 return (int)get_tv_number(tv) - 1;
2832}
2833
2834/*
2835 * "term_getline(buf, row)" function
2836 */
2837 void
2838f_term_getline(typval_T *argvars, typval_T *rettv)
2839{
2840 buf_T *buf = term_get_buf(argvars);
2841 term_T *term;
2842 int row;
2843
2844 rettv->v_type = VAR_STRING;
2845 if (buf == NULL)
2846 return;
2847 term = buf->b_term;
2848 row = get_row_number(&argvars[1], term);
2849
2850 if (term->tl_vterm == NULL)
2851 {
2852 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2853
2854 /* vterm is finished, get the text from the buffer */
2855 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2856 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2857 }
2858 else
2859 {
2860 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2861 VTermRect rect;
2862 int len;
2863 char_u *p;
2864
2865 if (row < 0 || row >= term->tl_rows)
2866 return;
2867 len = term->tl_cols * MB_MAXBYTES + 1;
2868 p = alloc(len);
2869 if (p == NULL)
2870 return;
2871 rettv->vval.v_string = p;
2872
2873 rect.start_col = 0;
2874 rect.end_col = term->tl_cols;
2875 rect.start_row = row;
2876 rect.end_row = row + 1;
2877 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2878 }
2879}
2880
2881/*
2882 * "term_getscrolled(buf)" function
2883 */
2884 void
2885f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2886{
2887 buf_T *buf = term_get_buf(argvars);
2888
2889 if (buf == NULL)
2890 return;
2891 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2892}
2893
2894/*
2895 * "term_getsize(buf)" function
2896 */
2897 void
2898f_term_getsize(typval_T *argvars, typval_T *rettv)
2899{
2900 buf_T *buf = term_get_buf(argvars);
2901 list_T *l;
2902
2903 if (rettv_list_alloc(rettv) == FAIL)
2904 return;
2905 if (buf == NULL)
2906 return;
2907
2908 l = rettv->vval.v_list;
2909 list_append_number(l, buf->b_term->tl_rows);
2910 list_append_number(l, buf->b_term->tl_cols);
2911}
2912
2913/*
2914 * "term_getstatus(buf)" function
2915 */
2916 void
2917f_term_getstatus(typval_T *argvars, typval_T *rettv)
2918{
2919 buf_T *buf = term_get_buf(argvars);
2920 term_T *term;
2921 char_u val[100];
2922
2923 rettv->v_type = VAR_STRING;
2924 if (buf == NULL)
2925 return;
2926 term = buf->b_term;
2927
2928 if (term_job_running(term))
2929 STRCPY(val, "running");
2930 else
2931 STRCPY(val, "finished");
2932 if (term->tl_normal_mode)
2933 STRCAT(val, ",normal");
2934 rettv->vval.v_string = vim_strsave(val);
2935}
2936
2937/*
2938 * "term_gettitle(buf)" function
2939 */
2940 void
2941f_term_gettitle(typval_T *argvars, typval_T *rettv)
2942{
2943 buf_T *buf = term_get_buf(argvars);
2944
2945 rettv->v_type = VAR_STRING;
2946 if (buf == NULL)
2947 return;
2948
2949 if (buf->b_term->tl_title != NULL)
2950 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
2951}
2952
2953/*
2954 * "term_gettty(buf)" function
2955 */
2956 void
2957f_term_gettty(typval_T *argvars, typval_T *rettv)
2958{
2959 buf_T *buf = term_get_buf(argvars);
2960 char_u *p;
2961 int num = 0;
2962
2963 rettv->v_type = VAR_STRING;
2964 if (buf == NULL)
2965 return;
2966 if (argvars[1].v_type != VAR_UNKNOWN)
2967 num = get_tv_number(&argvars[1]);
2968
2969 switch (num)
2970 {
2971 case 0:
2972 if (buf->b_term->tl_job != NULL)
2973 p = buf->b_term->tl_job->jv_tty_out;
2974 else
2975 p = buf->b_term->tl_tty_out;
2976 break;
2977 case 1:
2978 if (buf->b_term->tl_job != NULL)
2979 p = buf->b_term->tl_job->jv_tty_in;
2980 else
2981 p = buf->b_term->tl_tty_in;
2982 break;
2983 default:
2984 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
2985 return;
2986 }
2987 if (p != NULL)
2988 rettv->vval.v_string = vim_strsave(p);
2989}
2990
2991/*
2992 * "term_list()" function
2993 */
2994 void
2995f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
2996{
2997 term_T *tp;
2998 list_T *l;
2999
3000 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3001 return;
3002
3003 l = rettv->vval.v_list;
3004 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3005 if (tp != NULL && tp->tl_buffer != NULL)
3006 if (list_append_number(l,
3007 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3008 return;
3009}
3010
3011/*
3012 * "term_scrape(buf, row)" function
3013 */
3014 void
3015f_term_scrape(typval_T *argvars, typval_T *rettv)
3016{
3017 buf_T *buf = term_get_buf(argvars);
3018 VTermScreen *screen = NULL;
3019 VTermPos pos;
3020 list_T *l;
3021 term_T *term;
3022 char_u *p;
3023 sb_line_T *line;
3024
3025 if (rettv_list_alloc(rettv) == FAIL)
3026 return;
3027 if (buf == NULL)
3028 return;
3029 term = buf->b_term;
3030
3031 l = rettv->vval.v_list;
3032 pos.row = get_row_number(&argvars[1], term);
3033
3034 if (term->tl_vterm != NULL)
3035 {
3036 screen = vterm_obtain_screen(term->tl_vterm);
3037 p = NULL;
3038 line = NULL;
3039 }
3040 else
3041 {
3042 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3043
3044 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3045 return;
3046 p = ml_get_buf(buf, lnum + 1, FALSE);
3047 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3048 }
3049
3050 for (pos.col = 0; pos.col < term->tl_cols; )
3051 {
3052 dict_T *dcell;
3053 int width;
3054 VTermScreenCellAttrs attrs;
3055 VTermColor fg, bg;
3056 char_u rgb[8];
3057 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3058 int off = 0;
3059 int i;
3060
3061 if (screen == NULL)
3062 {
3063 cellattr_T *cellattr;
3064 int len;
3065
3066 /* vterm has finished, get the cell from scrollback */
3067 if (pos.col >= line->sb_cols)
3068 break;
3069 cellattr = line->sb_cells + pos.col;
3070 width = cellattr->width;
3071 attrs = cellattr->attrs;
3072 fg = cellattr->fg;
3073 bg = cellattr->bg;
3074 len = MB_PTR2LEN(p);
3075 mch_memmove(mbs, p, len);
3076 mbs[len] = NUL;
3077 p += len;
3078 }
3079 else
3080 {
3081 VTermScreenCell cell;
3082 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3083 break;
3084 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3085 {
3086 if (cell.chars[i] == 0)
3087 break;
3088 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3089 }
3090 mbs[off] = NUL;
3091 width = cell.width;
3092 attrs = cell.attrs;
3093 fg = cell.fg;
3094 bg = cell.bg;
3095 }
3096 dcell = dict_alloc();
3097 list_append_dict(l, dcell);
3098
3099 dict_add_nr_str(dcell, "chars", 0, mbs);
3100
3101 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3102 fg.red, fg.green, fg.blue);
3103 dict_add_nr_str(dcell, "fg", 0, rgb);
3104 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3105 bg.red, bg.green, bg.blue);
3106 dict_add_nr_str(dcell, "bg", 0, rgb);
3107
3108 dict_add_nr_str(dcell, "attr",
3109 cell2attr(attrs, fg, bg), NULL);
3110 dict_add_nr_str(dcell, "width", width, NULL);
3111
3112 ++pos.col;
3113 if (width == 2)
3114 ++pos.col;
3115 }
3116}
3117
3118/*
3119 * "term_sendkeys(buf, keys)" function
3120 */
3121 void
3122f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3123{
3124 buf_T *buf = term_get_buf(argvars);
3125 char_u *msg;
3126 term_T *term;
3127
3128 rettv->v_type = VAR_UNKNOWN;
3129 if (buf == NULL)
3130 return;
3131
3132 msg = get_tv_string_chk(&argvars[1]);
3133 if (msg == NULL)
3134 return;
3135 term = buf->b_term;
3136 if (term->tl_vterm == NULL)
3137 return;
3138
3139 while (*msg != NUL)
3140 {
3141 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003142 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003143 }
3144}
3145
3146/*
3147 * "term_start(command, options)" function
3148 */
3149 void
3150f_term_start(typval_T *argvars, typval_T *rettv)
3151{
3152 jobopt_T opt;
3153 buf_T *buf;
3154
3155 init_job_options(&opt);
3156 if (argvars[1].v_type != VAR_UNKNOWN
3157 && get_job_options(&argvars[1], &opt,
3158 JO_TIMEOUT_ALL + JO_STOPONEXIT
3159 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3160 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3161 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3162 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3163 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3164 return;
3165
3166 if (opt.jo_vertical)
3167 cmdmod.split = WSP_VERT;
3168 buf = term_start(&argvars[0], &opt, FALSE);
3169
3170 if (buf != NULL && buf->b_term != NULL)
3171 rettv->vval.v_number = buf->b_fnum;
3172}
3173
3174/*
3175 * "term_wait" function
3176 */
3177 void
3178f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3179{
3180 buf_T *buf = term_get_buf(argvars);
3181
3182 if (buf == NULL)
3183 {
3184 ch_log(NULL, "term_wait(): invalid argument");
3185 return;
3186 }
3187 if (buf->b_term->tl_job == NULL)
3188 {
3189 ch_log(NULL, "term_wait(): no job to wait for");
3190 return;
3191 }
3192 if (buf->b_term->tl_job->jv_channel == NULL)
3193 /* channel is closed, nothing to do */
3194 return;
3195
3196 /* Get the job status, this will detect a job that finished. */
3197 if ((buf->b_term->tl_job->jv_channel == NULL
3198 || !buf->b_term->tl_job->jv_channel->ch_keep_open)
3199 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3200 {
3201 /* The job is dead, keep reading channel I/O until the channel is
3202 * closed. buf->b_term may become NULL if the terminal was closed while
3203 * waiting. */
3204 ch_log(NULL, "term_wait(): waiting for channel to close");
3205 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3206 {
3207 mch_check_messages();
3208 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01003209 if (!buf_valid(buf))
3210 /* If the terminal is closed when the channel is closed the
3211 * buffer disappears. */
3212 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003213 ui_delay(10L, FALSE);
3214 }
3215 mch_check_messages();
3216 parse_queued_messages();
3217 }
3218 else
3219 {
3220 long wait = 10L;
3221
3222 mch_check_messages();
3223 parse_queued_messages();
3224
3225 /* Wait for some time for any channel I/O. */
3226 if (argvars[1].v_type != VAR_UNKNOWN)
3227 wait = get_tv_number(&argvars[1]);
3228 ui_delay(wait, TRUE);
3229 mch_check_messages();
3230
3231 /* Flushing messages on channels is hopefully sufficient.
3232 * TODO: is there a better way? */
3233 parse_queued_messages();
3234 }
3235}
3236
3237/*
3238 * Called when a channel has sent all the lines to a terminal.
3239 * Send a CTRL-D to mark the end of the text.
3240 */
3241 void
3242term_send_eof(channel_T *ch)
3243{
3244 term_T *term;
3245
3246 for (term = first_term; term != NULL; term = term->tl_next)
3247 if (term->tl_job == ch->ch_job)
3248 {
3249 if (term->tl_eof_chars != NULL)
3250 {
3251 channel_send(ch, PART_IN, term->tl_eof_chars,
3252 (int)STRLEN(term->tl_eof_chars), NULL);
3253 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3254 }
3255# ifdef WIN3264
3256 else
3257 /* Default: CTRL-D */
3258 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3259# endif
3260 }
3261}
3262
3263# if defined(WIN3264) || defined(PROTO)
3264
3265/**************************************
3266 * 2. MS-Windows implementation.
3267 */
3268
3269# ifndef PROTO
3270
3271#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3272#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
3273#define WINPTY_MOUSE_MODE_FORCE 2
3274
3275void* (*winpty_config_new)(UINT64, void*);
3276void* (*winpty_open)(void*, void*);
3277void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3278BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3279void (*winpty_config_set_mouse_mode)(void*, int);
3280void (*winpty_config_set_initial_size)(void*, int, int);
3281LPCWSTR (*winpty_conin_name)(void*);
3282LPCWSTR (*winpty_conout_name)(void*);
3283LPCWSTR (*winpty_conerr_name)(void*);
3284void (*winpty_free)(void*);
3285void (*winpty_config_free)(void*);
3286void (*winpty_spawn_config_free)(void*);
3287void (*winpty_error_free)(void*);
3288LPCWSTR (*winpty_error_msg)(void*);
3289BOOL (*winpty_set_size)(void*, int, int, void*);
3290HANDLE (*winpty_agent_process)(void*);
3291
3292#define WINPTY_DLL "winpty.dll"
3293
3294static HINSTANCE hWinPtyDLL = NULL;
3295# endif
3296
3297 static int
3298dyn_winpty_init(int verbose)
3299{
3300 int i;
3301 static struct
3302 {
3303 char *name;
3304 FARPROC *ptr;
3305 } winpty_entry[] =
3306 {
3307 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3308 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3309 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3310 {"winpty_config_set_mouse_mode",
3311 (FARPROC*)&winpty_config_set_mouse_mode},
3312 {"winpty_config_set_initial_size",
3313 (FARPROC*)&winpty_config_set_initial_size},
3314 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3315 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3316 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3317 {"winpty_free", (FARPROC*)&winpty_free},
3318 {"winpty_open", (FARPROC*)&winpty_open},
3319 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3320 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3321 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3322 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3323 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3324 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3325 {NULL, NULL}
3326 };
3327
3328 /* No need to initialize twice. */
3329 if (hWinPtyDLL)
3330 return OK;
3331 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3332 * winpty.dll. */
3333 if (*p_winptydll != NUL)
3334 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3335 if (!hWinPtyDLL)
3336 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3337 if (!hWinPtyDLL)
3338 {
3339 if (verbose)
3340 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3341 : (char_u *)WINPTY_DLL);
3342 return FAIL;
3343 }
3344 for (i = 0; winpty_entry[i].name != NULL
3345 && winpty_entry[i].ptr != NULL; ++i)
3346 {
3347 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3348 winpty_entry[i].name)) == NULL)
3349 {
3350 if (verbose)
3351 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3352 return FAIL;
3353 }
3354 }
3355
3356 return OK;
3357}
3358
3359/*
3360 * Create a new terminal of "rows" by "cols" cells.
3361 * Store a reference in "term".
3362 * Return OK or FAIL.
3363 */
3364 static int
3365term_and_job_init(
3366 term_T *term,
3367 typval_T *argvar,
3368 jobopt_T *opt)
3369{
3370 WCHAR *cmd_wchar = NULL;
3371 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003372 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003373 channel_T *channel = NULL;
3374 job_T *job = NULL;
3375 DWORD error;
3376 HANDLE jo = NULL;
3377 HANDLE child_process_handle;
3378 HANDLE child_thread_handle;
3379 void *winpty_err;
3380 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003381 garray_T ga_cmd, ga_env;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003382 char_u *cmd;
3383
3384 if (dyn_winpty_init(TRUE) == FAIL)
3385 return FAIL;
3386
3387 if (argvar->v_type == VAR_STRING)
3388 cmd = argvar->vval.v_string;
3389 else
3390 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003391 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
3392 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003393 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003394 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003395 }
3396
3397 cmd_wchar = enc_to_utf16(cmd, NULL);
3398 if (cmd_wchar == NULL)
3399 return FAIL;
3400 if (opt->jo_cwd != NULL)
3401 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003402
3403 ga_init2(&ga_env, (int)sizeof(char*), 20);
3404 win32_build_env(opt->jo_env, &ga_env, TRUE);
3405 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003406
3407 job = job_alloc();
3408 if (job == NULL)
3409 goto failed;
3410
3411 channel = add_channel();
3412 if (channel == NULL)
3413 goto failed;
3414
3415 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3416 if (term->tl_winpty_config == NULL)
3417 goto failed;
3418
3419 winpty_config_set_mouse_mode(term->tl_winpty_config,
3420 WINPTY_MOUSE_MODE_FORCE);
3421 winpty_config_set_initial_size(term->tl_winpty_config,
3422 term->tl_cols, term->tl_rows);
3423 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3424 if (term->tl_winpty == NULL)
3425 goto failed;
3426
3427 spawn_config = winpty_spawn_config_new(
3428 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3429 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3430 NULL,
3431 cmd_wchar,
3432 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003433 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003434 &winpty_err);
3435 if (spawn_config == NULL)
3436 goto failed;
3437
3438 channel = add_channel();
3439 if (channel == NULL)
3440 goto failed;
3441
3442 job = job_alloc();
3443 if (job == NULL)
3444 goto failed;
3445
3446 if (opt->jo_set & JO_IN_BUF)
3447 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3448
3449 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3450 &child_thread_handle, &error, &winpty_err))
3451 goto failed;
3452
3453 channel_set_pipes(channel,
3454 (sock_T)CreateFileW(
3455 winpty_conin_name(term->tl_winpty),
3456 GENERIC_WRITE, 0, NULL,
3457 OPEN_EXISTING, 0, NULL),
3458 (sock_T)CreateFileW(
3459 winpty_conout_name(term->tl_winpty),
3460 GENERIC_READ, 0, NULL,
3461 OPEN_EXISTING, 0, NULL),
3462 (sock_T)CreateFileW(
3463 winpty_conerr_name(term->tl_winpty),
3464 GENERIC_READ, 0, NULL,
3465 OPEN_EXISTING, 0, NULL));
3466
3467 /* Write lines with CR instead of NL. */
3468 channel->ch_write_text_mode = TRUE;
3469
3470 jo = CreateJobObject(NULL, NULL);
3471 if (jo == NULL)
3472 goto failed;
3473
3474 if (!AssignProcessToJobObject(jo, child_process_handle))
3475 {
3476 /* Failed, switch the way to terminate process with TerminateProcess. */
3477 CloseHandle(jo);
3478 jo = NULL;
3479 }
3480
3481 winpty_spawn_config_free(spawn_config);
3482 vim_free(cmd_wchar);
3483 vim_free(cwd_wchar);
3484
3485 create_vterm(term, term->tl_rows, term->tl_cols);
3486
3487 channel_set_job(channel, job, opt);
3488 job_set_options(job, opt);
3489
3490 job->jv_channel = channel;
3491 job->jv_proc_info.hProcess = child_process_handle;
3492 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3493 job->jv_job_object = jo;
3494 job->jv_status = JOB_STARTED;
3495 job->jv_tty_in = utf16_to_enc(
3496 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3497 job->jv_tty_out = utf16_to_enc(
3498 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3499 ++job->jv_refcount;
3500 term->tl_job = job;
3501
3502 return OK;
3503
3504failed:
3505 if (argvar->v_type == VAR_LIST)
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003506 vim_free(ga_cmd.ga_data);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003507 vim_free(ga_env.ga_data);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003508 vim_free(cmd_wchar);
3509 vim_free(cwd_wchar);
3510 if (spawn_config != NULL)
3511 winpty_spawn_config_free(spawn_config);
3512 if (channel != NULL)
3513 channel_clear(channel);
3514 if (job != NULL)
3515 {
3516 job->jv_channel = NULL;
3517 job_cleanup(job);
3518 }
3519 term->tl_job = NULL;
3520 if (jo != NULL)
3521 CloseHandle(jo);
3522 if (term->tl_winpty != NULL)
3523 winpty_free(term->tl_winpty);
3524 term->tl_winpty = NULL;
3525 if (term->tl_winpty_config != NULL)
3526 winpty_config_free(term->tl_winpty_config);
3527 term->tl_winpty_config = NULL;
3528 if (winpty_err != NULL)
3529 {
3530 char_u *msg = utf16_to_enc(
3531 (short_u *)winpty_error_msg(winpty_err), NULL);
3532
3533 EMSG(msg);
3534 winpty_error_free(winpty_err);
3535 }
3536 return FAIL;
3537}
3538
3539 static int
3540create_pty_only(term_T *term, jobopt_T *options)
3541{
3542 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3543 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3544 char in_name[80], out_name[80];
3545 channel_T *channel = NULL;
3546
3547 create_vterm(term, term->tl_rows, term->tl_cols);
3548
3549 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3550 GetCurrentProcessId(),
3551 curbuf->b_fnum);
3552 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3553 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3554 PIPE_UNLIMITED_INSTANCES,
3555 0, 0, NMPWAIT_NOWAIT, NULL);
3556 if (hPipeIn == INVALID_HANDLE_VALUE)
3557 goto failed;
3558
3559 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3560 GetCurrentProcessId(),
3561 curbuf->b_fnum);
3562 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3563 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3564 PIPE_UNLIMITED_INSTANCES,
3565 0, 0, 0, NULL);
3566 if (hPipeOut == INVALID_HANDLE_VALUE)
3567 goto failed;
3568
3569 ConnectNamedPipe(hPipeIn, NULL);
3570 ConnectNamedPipe(hPipeOut, NULL);
3571
3572 term->tl_job = job_alloc();
3573 if (term->tl_job == NULL)
3574 goto failed;
3575 ++term->tl_job->jv_refcount;
3576
3577 /* behave like the job is already finished */
3578 term->tl_job->jv_status = JOB_FINISHED;
3579
3580 channel = add_channel();
3581 if (channel == NULL)
3582 goto failed;
3583 term->tl_job->jv_channel = channel;
3584 channel->ch_keep_open = TRUE;
3585 channel->ch_named_pipe = TRUE;
3586
3587 channel_set_pipes(channel,
3588 (sock_T)hPipeIn,
3589 (sock_T)hPipeOut,
3590 (sock_T)hPipeOut);
3591 channel_set_job(channel, term->tl_job, options);
3592 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3593 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3594
3595 return OK;
3596
3597failed:
3598 if (hPipeIn != NULL)
3599 CloseHandle(hPipeIn);
3600 if (hPipeOut != NULL)
3601 CloseHandle(hPipeOut);
3602 return FAIL;
3603}
3604
3605/*
3606 * Free the terminal emulator part of "term".
3607 */
3608 static void
3609term_free_vterm(term_T *term)
3610{
3611 if (term->tl_winpty != NULL)
3612 winpty_free(term->tl_winpty);
3613 term->tl_winpty = NULL;
3614 if (term->tl_winpty_config != NULL)
3615 winpty_config_free(term->tl_winpty_config);
3616 term->tl_winpty_config = NULL;
3617 if (term->tl_vterm != NULL)
3618 vterm_free(term->tl_vterm);
3619 term->tl_vterm = NULL;
3620}
3621
3622/*
3623 * Request size to terminal.
3624 */
3625 static void
3626term_report_winsize(term_T *term, int rows, int cols)
3627{
3628 if (term->tl_winpty)
3629 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3630}
3631
3632 int
3633terminal_enabled(void)
3634{
3635 return dyn_winpty_init(FALSE) == OK;
3636}
3637
3638# else
3639
3640/**************************************
3641 * 3. Unix-like implementation.
3642 */
3643
3644/*
3645 * Create a new terminal of "rows" by "cols" cells.
3646 * Start job for "cmd".
3647 * Store the pointers in "term".
3648 * Return OK or FAIL.
3649 */
3650 static int
3651term_and_job_init(
3652 term_T *term,
3653 typval_T *argvar,
3654 jobopt_T *opt)
3655{
3656 create_vterm(term, term->tl_rows, term->tl_cols);
3657
3658 term->tl_job = job_start(argvar, opt);
3659 if (term->tl_job != NULL)
3660 ++term->tl_job->jv_refcount;
3661
3662 return term->tl_job != NULL
3663 && term->tl_job->jv_channel != NULL
3664 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3665}
3666
3667 static int
3668create_pty_only(term_T *term, jobopt_T *opt)
3669{
3670 create_vterm(term, term->tl_rows, term->tl_cols);
3671
3672 term->tl_job = job_alloc();
3673 if (term->tl_job == NULL)
3674 return FAIL;
3675 ++term->tl_job->jv_refcount;
3676
3677 /* behave like the job is already finished */
3678 term->tl_job->jv_status = JOB_FINISHED;
3679
3680 return mch_create_pty_channel(term->tl_job, opt);
3681}
3682
3683/*
3684 * Free the terminal emulator part of "term".
3685 */
3686 static void
3687term_free_vterm(term_T *term)
3688{
3689 if (term->tl_vterm != NULL)
3690 vterm_free(term->tl_vterm);
3691 term->tl_vterm = NULL;
3692}
3693
3694/*
3695 * Request size to terminal.
3696 */
3697 static void
3698term_report_winsize(term_T *term, int rows, int cols)
3699{
3700 /* Use an ioctl() to report the new window size to the job. */
3701 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3702 {
3703 int fd = -1;
3704 int part;
3705
3706 for (part = PART_OUT; part < PART_COUNT; ++part)
3707 {
3708 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3709 if (isatty(fd))
3710 break;
3711 }
3712 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3713 mch_signal_job(term->tl_job, (char_u *)"winch");
3714 }
3715}
3716
3717# endif
3718
3719#endif /* FEAT_TERMINAL */