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