blob: 5a2ebf8655ece282810b504d4990eec8d63fc941 [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 Moolenaarce6179c2017-12-05 13:06:16 +01001311 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001312 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001313 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001314 || dragging_outside)
1315 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001316 /* click or scroll outside the current window or on status line
1317 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001318 if (typed)
1319 {
1320 stuffcharReadbuff(c);
1321 mouse_was_outside = TRUE;
1322 }
1323 return FAIL;
1324 }
1325 }
1326 if (typed)
1327 mouse_was_outside = FALSE;
1328
1329 /* Convert the typed key to a sequence of bytes for the job. */
1330 len = term_convert_key(term, c, msg);
1331 if (len > 0)
1332 /* TODO: if FAIL is returned, stop? */
1333 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1334 (char_u *)msg, (int)len, NULL);
1335
1336 return OK;
1337}
1338
1339 static void
1340position_cursor(win_T *wp, VTermPos *pos)
1341{
1342 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1343 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1344 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1345}
1346
1347/*
1348 * Handle CTRL-W "": send register contents to the job.
1349 */
1350 static void
1351term_paste_register(int prev_c UNUSED)
1352{
1353 int c;
1354 list_T *l;
1355 listitem_T *item;
1356 long reglen = 0;
1357 int type;
1358
1359#ifdef FEAT_CMDL_INFO
1360 if (add_to_showcmd(prev_c))
1361 if (add_to_showcmd('"'))
1362 out_flush();
1363#endif
1364 c = term_vgetc();
1365#ifdef FEAT_CMDL_INFO
1366 clear_showcmd();
1367#endif
1368 if (!term_use_loop())
1369 /* job finished while waiting for a character */
1370 return;
1371
1372 /* CTRL-W "= prompt for expression to evaluate. */
1373 if (c == '=' && get_expr_register() != '=')
1374 return;
1375 if (!term_use_loop())
1376 /* job finished while waiting for a character */
1377 return;
1378
1379 l = (list_T *)get_reg_contents(c, GREG_LIST);
1380 if (l != NULL)
1381 {
1382 type = get_reg_type(c, &reglen);
1383 for (item = l->lv_first; item != NULL; item = item->li_next)
1384 {
1385 char_u *s = get_tv_string(&item->li_tv);
1386#ifdef WIN3264
1387 char_u *tmp = s;
1388
1389 if (!enc_utf8 && enc_codepage > 0)
1390 {
1391 WCHAR *ret = NULL;
1392 int length = 0;
1393
1394 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1395 (int)STRLEN(s), &ret, &length);
1396 if (ret != NULL)
1397 {
1398 WideCharToMultiByte_alloc(CP_UTF8, 0,
1399 ret, length, (char **)&s, &length, 0, 0);
1400 vim_free(ret);
1401 }
1402 }
1403#endif
1404 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1405 s, (int)STRLEN(s), NULL);
1406#ifdef WIN3264
1407 if (tmp != s)
1408 vim_free(s);
1409#endif
1410
1411 if (item->li_next != NULL || type == MLINE)
1412 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1413 (char_u *)"\r", 1, NULL);
1414 }
1415 list_free(l);
1416 }
1417}
1418
1419#if defined(FEAT_GUI) || defined(PROTO)
1420/*
1421 * Return TRUE when the cursor of the terminal should be displayed.
1422 */
1423 int
1424terminal_is_active()
1425{
1426 return in_terminal_loop != NULL;
1427}
1428
1429 cursorentry_T *
1430term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1431{
1432 term_T *term = in_terminal_loop;
1433 static cursorentry_T entry;
1434
1435 vim_memset(&entry, 0, sizeof(entry));
1436 entry.shape = entry.mshape =
1437 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1438 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1439 SHAPE_BLOCK;
1440 entry.percentage = 20;
1441 if (term->tl_cursor_blink)
1442 {
1443 entry.blinkwait = 700;
1444 entry.blinkon = 400;
1445 entry.blinkoff = 250;
1446 }
1447 *fg = gui.back_pixel;
1448 if (term->tl_cursor_color == NULL)
1449 *bg = gui.norm_pixel;
1450 else
1451 *bg = color_name2handle(term->tl_cursor_color);
1452 entry.name = "n";
1453 entry.used_for = SHAPE_CURSOR;
1454
1455 return &entry;
1456}
1457#endif
1458
1459static int did_change_cursor = FALSE;
1460
1461 static void
1462may_set_cursor_props(term_T *term)
1463{
1464#ifdef FEAT_GUI
1465 /* For the GUI the cursor properties are obtained with
1466 * term_get_cursor_shape(). */
1467 if (gui.in_use)
1468 return;
1469#endif
1470 if (in_terminal_loop == term)
1471 {
1472 did_change_cursor = TRUE;
1473 if (term->tl_cursor_color != NULL)
1474 term_cursor_color(term->tl_cursor_color);
1475 else
1476 term_cursor_color((char_u *)"");
1477 term_cursor_shape(term->tl_cursor_shape, term->tl_cursor_blink);
1478 }
1479}
1480
1481 static void
1482may_restore_cursor_props(void)
1483{
1484#ifdef FEAT_GUI
1485 if (gui.in_use)
1486 return;
1487#endif
1488 if (did_change_cursor)
1489 {
1490 did_change_cursor = FALSE;
1491 term_cursor_color((char_u *)"");
1492 /* this will restore the initial cursor style, if possible */
1493 ui_cursor_shape_forced(TRUE);
1494 }
1495}
1496
1497/*
1498 * Returns TRUE if the current window contains a terminal and we are sending
1499 * keys to the job.
1500 */
1501 int
1502term_use_loop(void)
1503{
1504 term_T *term = curbuf->b_term;
1505
1506 return term != NULL
1507 && !term->tl_normal_mode
1508 && term->tl_vterm != NULL
1509 && term_job_running(term);
1510}
1511
1512/*
1513 * Wait for input and send it to the job.
1514 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1515 * when there is no more typahead.
1516 * Return when the start of a CTRL-W command is typed or anything else that
1517 * should be handled as a Normal mode command.
1518 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1519 * the terminal was closed.
1520 */
1521 int
1522terminal_loop(int blocking)
1523{
1524 int c;
1525 int termkey = 0;
1526 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001527#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001528 int tty_fd = curbuf->b_term->tl_job->jv_channel
1529 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001530#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001531
1532 /* Remember the terminal we are sending keys to. However, the terminal
1533 * might be closed while waiting for a character, e.g. typing "exit" in a
1534 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1535 * stored reference. */
1536 in_terminal_loop = curbuf->b_term;
1537
1538 if (*curwin->w_p_tk != NUL)
1539 termkey = string_to_key(curwin->w_p_tk, TRUE);
1540 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1541 may_set_cursor_props(curbuf->b_term);
1542
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001543 while (blocking || vpeekc() != NUL)
1544 {
1545 /* TODO: skip screen update when handling a sequence of keys. */
1546 /* Repeat redrawing in case a message is received while redrawing. */
1547 while (must_redraw != 0)
1548 if (update_screen(0) == FAIL)
1549 break;
1550 update_cursor(curbuf->b_term, FALSE);
1551
1552 c = term_vgetc();
1553 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001554 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001555 /* Job finished while waiting for a character. Push back the
1556 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001557 if (c != K_IGNORE)
1558 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001559 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001560 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001561 if (c == K_IGNORE)
1562 continue;
1563
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001564#ifdef UNIX
1565 /*
1566 * The shell or another program may change the tty settings. Getting
1567 * them for every typed character is a bit of overhead, but it's needed
1568 * for the first character typed, e.g. when Vim starts in a shell.
1569 */
1570 if (isatty(tty_fd))
1571 {
1572 ttyinfo_T info;
1573
1574 /* Get the current backspace character of the pty. */
1575 if (get_tty_info(tty_fd, &info) == OK)
1576 term_backspace_char = info.backspace;
1577 }
1578#endif
1579
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580#ifdef WIN3264
1581 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1582 * Use CTRL-BREAK to kill the job. */
1583 if (ctrl_break_was_pressed)
1584 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1585#endif
1586 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1587 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1588 {
1589 int prev_c = c;
1590
1591#ifdef FEAT_CMDL_INFO
1592 if (add_to_showcmd(c))
1593 out_flush();
1594#endif
1595 c = term_vgetc();
1596#ifdef FEAT_CMDL_INFO
1597 clear_showcmd();
1598#endif
1599 if (!term_use_loop())
1600 /* job finished while waiting for a character */
1601 break;
1602
1603 if (prev_c == Ctrl_BSL)
1604 {
1605 if (c == Ctrl_N)
1606 {
1607 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1608 term_enter_normal_mode();
1609 ret = FAIL;
1610 goto theend;
1611 }
1612 /* Send both keys to the terminal. */
1613 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1614 }
1615 else if (c == Ctrl_C)
1616 {
1617 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1618 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1619 }
1620 else if (termkey == 0 && c == '.')
1621 {
1622 /* "CTRL-W .": send CTRL-W to the job */
1623 c = Ctrl_W;
1624 }
1625 else if (c == 'N')
1626 {
1627 /* CTRL-W N : go to Terminal-Normal mode. */
1628 term_enter_normal_mode();
1629 ret = FAIL;
1630 goto theend;
1631 }
1632 else if (c == '"')
1633 {
1634 term_paste_register(prev_c);
1635 continue;
1636 }
1637 else if (termkey == 0 || c != termkey)
1638 {
1639 stuffcharReadbuff(Ctrl_W);
1640 stuffcharReadbuff(c);
1641 ret = OK;
1642 goto theend;
1643 }
1644 }
1645# ifdef WIN3264
1646 if (!enc_utf8 && has_mbyte && c >= 0x80)
1647 {
1648 WCHAR wc;
1649 char_u mb[3];
1650
1651 mb[0] = (unsigned)c >> 8;
1652 mb[1] = c;
1653 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
1654 c = wc;
1655 }
1656# endif
1657 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
1658 {
1659 ret = OK;
1660 goto theend;
1661 }
1662 }
1663 ret = FAIL;
1664
1665theend:
1666 in_terminal_loop = NULL;
1667 may_restore_cursor_props();
1668 return ret;
1669}
1670
1671/*
1672 * Called when a job has finished.
1673 * This updates the title and status, but does not close the vterm, because
1674 * there might still be pending output in the channel.
1675 */
1676 void
1677term_job_ended(job_T *job)
1678{
1679 term_T *term;
1680 int did_one = FALSE;
1681
1682 for (term = first_term; term != NULL; term = term->tl_next)
1683 if (term->tl_job == job)
1684 {
1685 vim_free(term->tl_title);
1686 term->tl_title = NULL;
1687 vim_free(term->tl_status_text);
1688 term->tl_status_text = NULL;
1689 redraw_buf_and_status_later(term->tl_buffer, VALID);
1690 did_one = TRUE;
1691 }
1692 if (did_one)
1693 redraw_statuslines();
1694 if (curbuf->b_term != NULL)
1695 {
1696 if (curbuf->b_term->tl_job == job)
1697 maketitle();
1698 update_cursor(curbuf->b_term, TRUE);
1699 }
1700}
1701
1702 static void
1703may_toggle_cursor(term_T *term)
1704{
1705 if (in_terminal_loop == term)
1706 {
1707 if (term->tl_cursor_visible)
1708 cursor_on();
1709 else
1710 cursor_off();
1711 }
1712}
1713
1714/*
1715 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01001716 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001717 */
1718 static int
1719color2index(VTermColor *color, int fg, int *boldp)
1720{
1721 int red = color->red;
1722 int blue = color->blue;
1723 int green = color->green;
1724
Bram Moolenaar46359e12017-11-29 22:33:38 +01001725 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001726 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001727 /* First 16 colors and default: use the ANSI index, because these
1728 * colors can be redefined. */
1729 if (t_colors >= 16)
1730 return color->ansi_index;
1731 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001732 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01001733 case 0: return 0;
1734 case 1: return lookup_color( 0, fg, boldp) + 1;
1735 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
1736 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
1737 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
1738 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
1739 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
1740 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
1741 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
1742 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
1743 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
1744 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
1745 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
1746 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
1747 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
1748 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
1749 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001750 }
1751 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01001752
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001753 if (t_colors >= 256)
1754 {
1755 if (red == blue && red == green)
1756 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001757 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001758 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001759 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
1760 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
1761 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001762 int i;
1763
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001764 if (red < 5)
1765 return 17; /* 00/00/00 */
1766 if (red > 245) /* ff/ff/ff */
1767 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001768 for (i = 0; i < 23; ++i)
1769 if (red < cutoff[i])
1770 return i + 233;
1771 return 256;
1772 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001773 {
1774 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
1775 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001776
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02001777 /* 216-color cube */
1778 for (ri = 0; ri < 5; ++ri)
1779 if (red < cutoff[ri])
1780 break;
1781 for (gi = 0; gi < 5; ++gi)
1782 if (green < cutoff[gi])
1783 break;
1784 for (bi = 0; bi < 5; ++bi)
1785 if (blue < cutoff[bi])
1786 break;
1787 return 17 + ri * 36 + gi * 6 + bi;
1788 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001789 }
1790 return 0;
1791}
1792
1793/*
1794 * Convert the attributes of a vterm cell into an attribute index.
1795 */
1796 static int
1797cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
1798{
1799 int attr = 0;
1800
1801 if (cellattrs.bold)
1802 attr |= HL_BOLD;
1803 if (cellattrs.underline)
1804 attr |= HL_UNDERLINE;
1805 if (cellattrs.italic)
1806 attr |= HL_ITALIC;
1807 if (cellattrs.strike)
1808 attr |= HL_STRIKETHROUGH;
1809 if (cellattrs.reverse)
1810 attr |= HL_INVERSE;
1811
1812#ifdef FEAT_GUI
1813 if (gui.in_use)
1814 {
1815 guicolor_T fg, bg;
1816
1817 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
1818 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
1819 return get_gui_attr_idx(attr, fg, bg);
1820 }
1821 else
1822#endif
1823#ifdef FEAT_TERMGUICOLORS
1824 if (p_tgc)
1825 {
1826 guicolor_T fg, bg;
1827
1828 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
1829 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
1830
1831 return get_tgc_attr_idx(attr, fg, bg);
1832 }
1833 else
1834#endif
1835 {
1836 int bold = MAYBE;
1837 int fg = color2index(&cellfg, TRUE, &bold);
1838 int bg = color2index(&cellbg, FALSE, &bold);
1839
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001840 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001841 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001842 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01001843 if (fg == 0 && term_default_cterm_fg >= 0)
1844 fg = term_default_cterm_fg + 1;
1845 if (bg == 0 && term_default_cterm_bg >= 0)
1846 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01001847 }
1848
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001849 /* with 8 colors set the bold attribute to get a bright foreground */
1850 if (bold == TRUE)
1851 attr |= HL_BOLD;
1852 return get_cterm_attr_idx(attr, fg, bg);
1853 }
1854 return 0;
1855}
1856
1857 static int
1858handle_damage(VTermRect rect, void *user)
1859{
1860 term_T *term = (term_T *)user;
1861
1862 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
1863 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
1864 redraw_buf_later(term->tl_buffer, NOT_VALID);
1865 return 1;
1866}
1867
1868 static int
1869handle_moverect(VTermRect dest, VTermRect src, void *user)
1870{
1871 term_T *term = (term_T *)user;
1872
1873 /* Scrolling up is done much more efficiently by deleting lines instead of
1874 * redrawing the text. */
1875 if (dest.start_col == src.start_col
1876 && dest.end_col == src.end_col
1877 && dest.start_row < src.start_row)
1878 {
1879 win_T *wp;
1880 VTermColor fg, bg;
1881 VTermScreenCellAttrs attr;
1882 int clear_attr;
1883
1884 /* Set the color to clear lines with. */
1885 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1886 &fg, &bg);
1887 vim_memset(&attr, 0, sizeof(attr));
1888 clear_attr = cell2attr(attr, fg, bg);
1889
1890 FOR_ALL_WINDOWS(wp)
1891 {
1892 if (wp->w_buffer == term->tl_buffer)
1893 win_del_lines(wp, dest.start_row,
1894 src.start_row - dest.start_row, FALSE, FALSE,
1895 clear_attr);
1896 }
1897 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02001898
1899 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
1900 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
1901
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001902 redraw_buf_later(term->tl_buffer, NOT_VALID);
1903 return 1;
1904}
1905
1906 static int
1907handle_movecursor(
1908 VTermPos pos,
1909 VTermPos oldpos UNUSED,
1910 int visible,
1911 void *user)
1912{
1913 term_T *term = (term_T *)user;
1914 win_T *wp;
1915
1916 term->tl_cursor_pos = pos;
1917 term->tl_cursor_visible = visible;
1918
1919 FOR_ALL_WINDOWS(wp)
1920 {
1921 if (wp->w_buffer == term->tl_buffer)
1922 position_cursor(wp, &pos);
1923 }
1924 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
1925 {
1926 may_toggle_cursor(term);
1927 update_cursor(term, term->tl_cursor_visible);
1928 }
1929
1930 return 1;
1931}
1932
1933 static int
1934handle_settermprop(
1935 VTermProp prop,
1936 VTermValue *value,
1937 void *user)
1938{
1939 term_T *term = (term_T *)user;
1940
1941 switch (prop)
1942 {
1943 case VTERM_PROP_TITLE:
1944 vim_free(term->tl_title);
1945 /* a blank title isn't useful, make it empty, so that "running" is
1946 * displayed */
1947 if (*skipwhite((char_u *)value->string) == NUL)
1948 term->tl_title = NULL;
1949#ifdef WIN3264
1950 else if (!enc_utf8 && enc_codepage > 0)
1951 {
1952 WCHAR *ret = NULL;
1953 int length = 0;
1954
1955 MultiByteToWideChar_alloc(CP_UTF8, 0,
1956 (char*)value->string, (int)STRLEN(value->string),
1957 &ret, &length);
1958 if (ret != NULL)
1959 {
1960 WideCharToMultiByte_alloc(enc_codepage, 0,
1961 ret, length, (char**)&term->tl_title,
1962 &length, 0, 0);
1963 vim_free(ret);
1964 }
1965 }
1966#endif
1967 else
1968 term->tl_title = vim_strsave((char_u *)value->string);
1969 vim_free(term->tl_status_text);
1970 term->tl_status_text = NULL;
1971 if (term == curbuf->b_term)
1972 maketitle();
1973 break;
1974
1975 case VTERM_PROP_CURSORVISIBLE:
1976 term->tl_cursor_visible = value->boolean;
1977 may_toggle_cursor(term);
1978 out_flush();
1979 break;
1980
1981 case VTERM_PROP_CURSORBLINK:
1982 term->tl_cursor_blink = value->boolean;
1983 may_set_cursor_props(term);
1984 break;
1985
1986 case VTERM_PROP_CURSORSHAPE:
1987 term->tl_cursor_shape = value->number;
1988 may_set_cursor_props(term);
1989 break;
1990
1991 case VTERM_PROP_CURSORCOLOR:
1992 vim_free(term->tl_cursor_color);
1993 if (*value->string == NUL)
1994 term->tl_cursor_color = NULL;
1995 else
1996 term->tl_cursor_color = vim_strsave((char_u *)value->string);
1997 may_set_cursor_props(term);
1998 break;
1999
2000 case VTERM_PROP_ALTSCREEN:
2001 /* TODO: do anything else? */
2002 term->tl_using_altscreen = value->boolean;
2003 break;
2004
2005 default:
2006 break;
2007 }
2008 /* Always return 1, otherwise vterm doesn't store the value internally. */
2009 return 1;
2010}
2011
2012/*
2013 * The job running in the terminal resized the terminal.
2014 */
2015 static int
2016handle_resize(int rows, int cols, void *user)
2017{
2018 term_T *term = (term_T *)user;
2019 win_T *wp;
2020
2021 term->tl_rows = rows;
2022 term->tl_cols = cols;
2023 if (term->tl_vterm_size_changed)
2024 /* Size was set by vterm_set_size(), don't set the window size. */
2025 term->tl_vterm_size_changed = FALSE;
2026 else
2027 {
2028 FOR_ALL_WINDOWS(wp)
2029 {
2030 if (wp->w_buffer == term->tl_buffer)
2031 {
2032 win_setheight_win(rows, wp);
2033 win_setwidth_win(cols, wp);
2034 }
2035 }
2036 redraw_buf_later(term->tl_buffer, NOT_VALID);
2037 }
2038 return 1;
2039}
2040
2041/*
2042 * Handle a line that is pushed off the top of the screen.
2043 */
2044 static int
2045handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2046{
2047 term_T *term = (term_T *)user;
2048
2049 /* TODO: Limit the number of lines that are stored. */
2050 if (ga_grow(&term->tl_scrollback, 1) == OK)
2051 {
2052 cellattr_T *p = NULL;
2053 int len = 0;
2054 int i;
2055 int c;
2056 int col;
2057 sb_line_T *line;
2058 garray_T ga;
2059 cellattr_T fill_attr = term->tl_default_color;
2060
2061 /* do not store empty cells at the end */
2062 for (i = 0; i < cols; ++i)
2063 if (cells[i].chars[0] != 0)
2064 len = i + 1;
2065 else
2066 cell2cellattr(&cells[i], &fill_attr);
2067
2068 ga_init2(&ga, 1, 100);
2069 if (len > 0)
2070 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2071 if (p != NULL)
2072 {
2073 for (col = 0; col < len; col += cells[col].width)
2074 {
2075 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2076 {
2077 ga.ga_len = 0;
2078 break;
2079 }
2080 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2081 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2082 (char_u *)ga.ga_data + ga.ga_len);
2083 cell2cellattr(&cells[col], &p[col]);
2084 }
2085 }
2086 if (ga_grow(&ga, 1) == FAIL)
2087 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2088 else
2089 {
2090 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2091 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2092 }
2093 ga_clear(&ga);
2094
2095 line = (sb_line_T *)term->tl_scrollback.ga_data
2096 + term->tl_scrollback.ga_len;
2097 line->sb_cols = len;
2098 line->sb_cells = p;
2099 line->sb_fill_attr = fill_attr;
2100 ++term->tl_scrollback.ga_len;
2101 ++term->tl_scrollback_scrolled;
2102 }
2103 return 0; /* ignored */
2104}
2105
2106static VTermScreenCallbacks screen_callbacks = {
2107 handle_damage, /* damage */
2108 handle_moverect, /* moverect */
2109 handle_movecursor, /* movecursor */
2110 handle_settermprop, /* settermprop */
2111 NULL, /* bell */
2112 handle_resize, /* resize */
2113 handle_pushline, /* sb_pushline */
2114 NULL /* sb_popline */
2115};
2116
2117/*
2118 * Called when a channel has been closed.
2119 * If this was a channel for a terminal window then finish it up.
2120 */
2121 void
2122term_channel_closed(channel_T *ch)
2123{
2124 term_T *term;
2125 int did_one = FALSE;
2126
2127 for (term = first_term; term != NULL; term = term->tl_next)
2128 if (term->tl_job == ch->ch_job)
2129 {
2130 term->tl_channel_closed = TRUE;
2131 did_one = TRUE;
2132
2133 vim_free(term->tl_title);
2134 term->tl_title = NULL;
2135 vim_free(term->tl_status_text);
2136 term->tl_status_text = NULL;
2137
2138 /* Unless in Terminal-Normal mode: clear the vterm. */
2139 if (!term->tl_normal_mode)
2140 {
2141 int fnum = term->tl_buffer->b_fnum;
2142
2143 cleanup_vterm(term);
2144
2145 if (term->tl_finish == 'c')
2146 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002147 aco_save_T aco;
2148
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002149 /* ++close or term_finish == "close" */
2150 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002151 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002152 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002153 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002154 break;
2155 }
2156 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2157 {
2158 char buf[50];
2159
2160 /* TODO: use term_opencmd */
2161 ch_log(NULL, "terminal job finished, opening window");
2162 vim_snprintf(buf, sizeof(buf),
2163 term->tl_opencmd == NULL
2164 ? "botright sbuf %d"
2165 : (char *)term->tl_opencmd, fnum);
2166 do_cmdline_cmd((char_u *)buf);
2167 }
2168 else
2169 ch_log(NULL, "terminal job finished");
2170 }
2171
2172 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2173 }
2174 if (did_one)
2175 {
2176 redraw_statuslines();
2177
2178 /* Need to break out of vgetc(). */
2179 ins_char_typebuf(K_IGNORE);
2180 typebuf_was_filled = TRUE;
2181
2182 term = curbuf->b_term;
2183 if (term != NULL)
2184 {
2185 if (term->tl_job == ch->ch_job)
2186 maketitle();
2187 update_cursor(term, term->tl_cursor_visible);
2188 }
2189 }
2190}
2191
2192/*
2193 * Called to update a window that contains an active terminal.
2194 * Returns FAIL when there is no terminal running in this window or in
2195 * Terminal-Normal mode.
2196 */
2197 int
2198term_update_window(win_T *wp)
2199{
2200 term_T *term = wp->w_buffer->b_term;
2201 VTerm *vterm;
2202 VTermScreen *screen;
2203 VTermState *state;
2204 VTermPos pos;
2205
2206 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2207 return FAIL;
2208
2209 vterm = term->tl_vterm;
2210 screen = vterm_obtain_screen(vterm);
2211 state = vterm_obtain_state(vterm);
2212
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002213 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002214 {
2215 term->tl_dirty_row_start = 0;
2216 term->tl_dirty_row_end = MAX_ROW;
2217 }
2218
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002219 /*
2220 * If the window was resized a redraw will be triggered and we get here.
2221 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2222 */
2223 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2224 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2225 {
2226 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2227 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2228 win_T *twp;
2229
2230 FOR_ALL_WINDOWS(twp)
2231 {
2232 /* When more than one window shows the same terminal, use the
2233 * smallest size. */
2234 if (twp->w_buffer == term->tl_buffer)
2235 {
2236 if (!term->tl_rows_fixed && rows > twp->w_height)
2237 rows = twp->w_height;
2238 if (!term->tl_cols_fixed && cols > twp->w_width)
2239 cols = twp->w_width;
2240 }
2241 }
2242
2243 term->tl_vterm_size_changed = TRUE;
2244 vterm_set_size(vterm, rows, cols);
2245 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2246 rows);
2247 term_report_winsize(term, rows, cols);
2248 }
2249
2250 /* The cursor may have been moved when resizing. */
2251 vterm_state_get_cursorpos(state, &pos);
2252 position_cursor(wp, &pos);
2253
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002254 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2255 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002256 {
2257 int off = screen_get_current_line_off();
2258 int max_col = MIN(wp->w_width, term->tl_cols);
2259
2260 if (pos.row < term->tl_rows)
2261 {
2262 for (pos.col = 0; pos.col < max_col; )
2263 {
2264 VTermScreenCell cell;
2265 int c;
2266
2267 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2268 vim_memset(&cell, 0, sizeof(cell));
2269
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002270 c = cell.chars[0];
2271 if (c == NUL)
2272 {
2273 ScreenLines[off] = ' ';
2274 if (enc_utf8)
2275 ScreenLinesUC[off] = NUL;
2276 }
2277 else
2278 {
2279 if (enc_utf8)
2280 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002281 int i;
2282
2283 /* composing chars */
2284 for (i = 0; i < Screen_mco
2285 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2286 {
2287 ScreenLinesC[i][off] = cell.chars[i + 1];
2288 if (cell.chars[i + 1] == 0)
2289 break;
2290 }
2291 if (c >= 0x80 || (Screen_mco > 0
2292 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002293 {
2294 ScreenLines[off] = ' ';
2295 ScreenLinesUC[off] = c;
2296 }
2297 else
2298 {
2299 ScreenLines[off] = c;
2300 ScreenLinesUC[off] = NUL;
2301 }
2302 }
2303#ifdef WIN3264
2304 else if (has_mbyte && c >= 0x80)
2305 {
2306 char_u mb[MB_MAXBYTES+1];
2307 WCHAR wc = c;
2308
2309 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2310 (char*)mb, 2, 0, 0) > 1)
2311 {
2312 ScreenLines[off] = mb[0];
2313 ScreenLines[off + 1] = mb[1];
2314 cell.width = mb_ptr2cells(mb);
2315 }
2316 else
2317 ScreenLines[off] = c;
2318 }
2319#endif
2320 else
2321 ScreenLines[off] = c;
2322 }
2323 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2324
2325 ++pos.col;
2326 ++off;
2327 if (cell.width == 2)
2328 {
2329 if (enc_utf8)
2330 ScreenLinesUC[off] = NUL;
2331
2332 /* don't set the second byte to NUL for a DBCS encoding, it
2333 * has been set above */
2334 if (enc_utf8 || !has_mbyte)
2335 ScreenLines[off] = NUL;
2336
2337 ++pos.col;
2338 ++off;
2339 }
2340 }
2341 }
2342 else
2343 pos.col = 0;
2344
2345 screen_line(wp->w_winrow + pos.row, wp->w_wincol,
2346 pos.col, wp->w_width, FALSE);
2347 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002348 term->tl_dirty_row_start = MAX_ROW;
2349 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002350
2351 return OK;
2352}
2353
2354/*
2355 * Return TRUE if "wp" is a terminal window where the job has finished.
2356 */
2357 int
2358term_is_finished(buf_T *buf)
2359{
2360 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2361}
2362
2363/*
2364 * Return TRUE if "wp" is a terminal window where the job has finished or we
2365 * are in Terminal-Normal mode, thus we show the buffer contents.
2366 */
2367 int
2368term_show_buffer(buf_T *buf)
2369{
2370 term_T *term = buf->b_term;
2371
2372 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2373}
2374
2375/*
2376 * The current buffer is going to be changed. If there is terminal
2377 * highlighting remove it now.
2378 */
2379 void
2380term_change_in_curbuf(void)
2381{
2382 term_T *term = curbuf->b_term;
2383
2384 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2385 {
2386 free_scrollback(term);
2387 redraw_buf_later(term->tl_buffer, NOT_VALID);
2388
2389 /* The buffer is now like a normal buffer, it cannot be easily
2390 * abandoned when changed. */
2391 set_string_option_direct((char_u *)"buftype", -1,
2392 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2393 }
2394}
2395
2396/*
2397 * Get the screen attribute for a position in the buffer.
2398 * Use a negative "col" to get the filler background color.
2399 */
2400 int
2401term_get_attr(buf_T *buf, linenr_T lnum, int col)
2402{
2403 term_T *term = buf->b_term;
2404 sb_line_T *line;
2405 cellattr_T *cellattr;
2406
2407 if (lnum > term->tl_scrollback.ga_len)
2408 cellattr = &term->tl_default_color;
2409 else
2410 {
2411 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2412 if (col < 0 || col >= line->sb_cols)
2413 cellattr = &line->sb_fill_attr;
2414 else
2415 cellattr = line->sb_cells + col;
2416 }
2417 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2418}
2419
2420static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002421 { 0, 0, 0, 1}, /* black */
2422 {224, 0, 0, 2}, /* dark red */
2423 { 0, 224, 0, 3}, /* dark green */
2424 {224, 224, 0, 4}, /* dark yellow / brown */
2425 { 0, 0, 224, 5}, /* dark blue */
2426 {224, 0, 224, 6}, /* dark magenta */
2427 { 0, 224, 224, 7}, /* dark cyan */
2428 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002429
Bram Moolenaar46359e12017-11-29 22:33:38 +01002430 {128, 128, 128, 9}, /* dark grey */
2431 {255, 64, 64, 10}, /* light red */
2432 { 64, 255, 64, 11}, /* light green */
2433 {255, 255, 64, 12}, /* yellow */
2434 { 64, 64, 255, 13}, /* light blue */
2435 {255, 64, 255, 14}, /* light magenta */
2436 { 64, 255, 255, 15}, /* light cyan */
2437 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002438};
2439
2440static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002441 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002442};
2443
2444static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002445 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2446 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002447};
2448
2449/*
2450 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002451 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002452 */
2453 static void
2454cterm_color2rgb(int nr, VTermColor *rgb)
2455{
2456 int idx;
2457
2458 if (nr < 16)
2459 {
2460 *rgb = ansi_table[nr];
2461 }
2462 else if (nr < 232)
2463 {
2464 /* 216 color cube */
2465 idx = nr - 16;
2466 rgb->blue = cube_value[idx % 6];
2467 rgb->green = cube_value[idx / 6 % 6];
2468 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002469 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002470 }
2471 else if (nr < 256)
2472 {
2473 /* 24 grey scale ramp */
2474 idx = nr - 232;
2475 rgb->blue = grey_ramp[idx];
2476 rgb->green = grey_ramp[idx];
2477 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002478 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002479 }
2480}
2481
2482/*
2483 * Create a new vterm and initialize it.
2484 */
2485 static void
2486create_vterm(term_T *term, int rows, int cols)
2487{
2488 VTerm *vterm;
2489 VTermScreen *screen;
2490 VTermValue value;
2491 VTermColor *fg, *bg;
2492 int fgval, bgval;
2493 int id;
2494
2495 vterm = vterm_new(rows, cols);
2496 term->tl_vterm = vterm;
2497 screen = vterm_obtain_screen(vterm);
2498 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2499 /* TODO: depends on 'encoding'. */
2500 vterm_set_utf8(vterm, 1);
2501
2502 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2503 term->tl_default_color.width = 1;
2504 fg = &term->tl_default_color.fg;
2505 bg = &term->tl_default_color.bg;
2506
2507 /* Vterm uses a default black background. Set it to white when
2508 * 'background' is "light". */
2509 if (*p_bg == 'l')
2510 {
2511 fgval = 0;
2512 bgval = 255;
2513 }
2514 else
2515 {
2516 fgval = 255;
2517 bgval = 0;
2518 }
2519 fg->red = fg->green = fg->blue = fgval;
2520 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002521 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002522
2523 /* The "Terminal" highlight group overrules the defaults. */
2524 id = syn_name2id((char_u *)"Terminal");
2525
Bram Moolenaar46359e12017-11-29 22:33:38 +01002526 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002527#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2528 if (0
2529# ifdef FEAT_GUI
2530 || gui.in_use
2531# endif
2532# ifdef FEAT_TERMGUICOLORS
2533 || p_tgc
2534# endif
2535 )
2536 {
2537 guicolor_T fg_rgb = INVALCOLOR;
2538 guicolor_T bg_rgb = INVALCOLOR;
2539
2540 if (id != 0)
2541 syn_id2colors(id, &fg_rgb, &bg_rgb);
2542
2543# ifdef FEAT_GUI
2544 if (gui.in_use)
2545 {
2546 if (fg_rgb == INVALCOLOR)
2547 fg_rgb = gui.norm_pixel;
2548 if (bg_rgb == INVALCOLOR)
2549 bg_rgb = gui.back_pixel;
2550 }
2551# ifdef FEAT_TERMGUICOLORS
2552 else
2553# endif
2554# endif
2555# ifdef FEAT_TERMGUICOLORS
2556 {
2557 if (fg_rgb == INVALCOLOR)
2558 fg_rgb = cterm_normal_fg_gui_color;
2559 if (bg_rgb == INVALCOLOR)
2560 bg_rgb = cterm_normal_bg_gui_color;
2561 }
2562# endif
2563 if (fg_rgb != INVALCOLOR)
2564 {
2565 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2566
2567 fg->red = (unsigned)(rgb >> 16);
2568 fg->green = (unsigned)(rgb >> 8) & 255;
2569 fg->blue = (unsigned)rgb & 255;
2570 }
2571 if (bg_rgb != INVALCOLOR)
2572 {
2573 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2574
2575 bg->red = (unsigned)(rgb >> 16);
2576 bg->green = (unsigned)(rgb >> 8) & 255;
2577 bg->blue = (unsigned)rgb & 255;
2578 }
2579 }
2580 else
2581#endif
2582 if (id != 0 && t_colors >= 16)
2583 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002584 if (term_default_cterm_fg >= 0)
2585 cterm_color2rgb(term_default_cterm_fg, fg);
2586 if (term_default_cterm_bg >= 0)
2587 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002588 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002589 else
2590 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002591#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002592 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002593#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002594
2595 /* In an MS-Windows console we know the normal colors. */
2596 if (cterm_normal_fg_color > 0)
2597 {
2598 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002599# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002600 tmp = fg->red;
2601 fg->red = fg->blue;
2602 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002603# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002604 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002605# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002606 else
2607 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002608# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002609
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002610 if (cterm_normal_bg_color > 0)
2611 {
2612 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002613# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002614 tmp = bg->red;
2615 bg->red = bg->blue;
2616 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002617# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002618 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02002619# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002620 else
2621 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02002622# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002623 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002624
2625 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
2626
2627 /* Required to initialize most things. */
2628 vterm_screen_reset(screen, 1 /* hard */);
2629
2630 /* Allow using alternate screen. */
2631 vterm_screen_enable_altscreen(screen, 1);
2632
2633 /* For unix do not use a blinking cursor. In an xterm this causes the
2634 * cursor to blink if it's blinking in the xterm.
2635 * For Windows we respect the system wide setting. */
2636#ifdef WIN3264
2637 if (GetCaretBlinkTime() == INFINITE)
2638 value.boolean = 0;
2639 else
2640 value.boolean = 1;
2641#else
2642 value.boolean = 0;
2643#endif
2644 vterm_state_set_termprop(vterm_obtain_state(vterm),
2645 VTERM_PROP_CURSORBLINK, &value);
2646}
2647
2648/*
2649 * Return the text to show for the buffer name and status.
2650 */
2651 char_u *
2652term_get_status_text(term_T *term)
2653{
2654 if (term->tl_status_text == NULL)
2655 {
2656 char_u *txt;
2657 size_t len;
2658
2659 if (term->tl_normal_mode)
2660 {
2661 if (term_job_running(term))
2662 txt = (char_u *)_("Terminal");
2663 else
2664 txt = (char_u *)_("Terminal-finished");
2665 }
2666 else if (term->tl_title != NULL)
2667 txt = term->tl_title;
2668 else if (term_none_open(term))
2669 txt = (char_u *)_("active");
2670 else if (term_job_running(term))
2671 txt = (char_u *)_("running");
2672 else
2673 txt = (char_u *)_("finished");
2674 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
2675 term->tl_status_text = alloc((int)len);
2676 if (term->tl_status_text != NULL)
2677 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
2678 term->tl_buffer->b_fname, txt);
2679 }
2680 return term->tl_status_text;
2681}
2682
2683/*
2684 * Mark references in jobs of terminals.
2685 */
2686 int
2687set_ref_in_term(int copyID)
2688{
2689 int abort = FALSE;
2690 term_T *term;
2691 typval_T tv;
2692
2693 for (term = first_term; term != NULL; term = term->tl_next)
2694 if (term->tl_job != NULL)
2695 {
2696 tv.v_type = VAR_JOB;
2697 tv.vval.v_job = term->tl_job;
2698 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
2699 }
2700 return abort;
2701}
2702
2703/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002704 * Cache "Terminal" highlight group colors.
2705 */
2706 void
2707set_terminal_default_colors(int cterm_fg, int cterm_bg)
2708{
2709 term_default_cterm_fg = cterm_fg - 1;
2710 term_default_cterm_bg = cterm_bg - 1;
2711}
2712
2713/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002714 * Get the buffer from the first argument in "argvars".
2715 * Returns NULL when the buffer is not for a terminal window.
2716 */
2717 static buf_T *
2718term_get_buf(typval_T *argvars)
2719{
2720 buf_T *buf;
2721
2722 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
2723 ++emsg_off;
2724 buf = get_buf_tv(&argvars[0], FALSE);
2725 --emsg_off;
2726 if (buf == NULL || buf->b_term == NULL)
2727 return NULL;
2728 return buf;
2729}
2730
2731/*
2732 * "term_getaltscreen(buf)" function
2733 */
2734 void
2735f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
2736{
2737 buf_T *buf = term_get_buf(argvars);
2738
2739 if (buf == NULL)
2740 return;
2741 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
2742}
2743
2744/*
2745 * "term_getattr(attr, name)" function
2746 */
2747 void
2748f_term_getattr(typval_T *argvars, typval_T *rettv)
2749{
2750 int attr;
2751 size_t i;
2752 char_u *name;
2753
2754 static struct {
2755 char *name;
2756 int attr;
2757 } attrs[] = {
2758 {"bold", HL_BOLD},
2759 {"italic", HL_ITALIC},
2760 {"underline", HL_UNDERLINE},
2761 {"strike", HL_STRIKETHROUGH},
2762 {"reverse", HL_INVERSE},
2763 };
2764
2765 attr = get_tv_number(&argvars[0]);
2766 name = get_tv_string_chk(&argvars[1]);
2767 if (name == NULL)
2768 return;
2769
2770 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
2771 if (STRCMP(name, attrs[i].name) == 0)
2772 {
2773 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
2774 break;
2775 }
2776}
2777
2778/*
2779 * "term_getcursor(buf)" function
2780 */
2781 void
2782f_term_getcursor(typval_T *argvars, typval_T *rettv)
2783{
2784 buf_T *buf = term_get_buf(argvars);
2785 term_T *term;
2786 list_T *l;
2787 dict_T *d;
2788
2789 if (rettv_list_alloc(rettv) == FAIL)
2790 return;
2791 if (buf == NULL)
2792 return;
2793 term = buf->b_term;
2794
2795 l = rettv->vval.v_list;
2796 list_append_number(l, term->tl_cursor_pos.row + 1);
2797 list_append_number(l, term->tl_cursor_pos.col + 1);
2798
2799 d = dict_alloc();
2800 if (d != NULL)
2801 {
2802 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
2803 dict_add_nr_str(d, "blink", blink_state_is_inverted()
2804 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
2805 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
2806 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
2807 ? (char_u *)"" : term->tl_cursor_color);
2808 list_append_dict(l, d);
2809 }
2810}
2811
2812/*
2813 * "term_getjob(buf)" function
2814 */
2815 void
2816f_term_getjob(typval_T *argvars, typval_T *rettv)
2817{
2818 buf_T *buf = term_get_buf(argvars);
2819
2820 rettv->v_type = VAR_JOB;
2821 rettv->vval.v_job = NULL;
2822 if (buf == NULL)
2823 return;
2824
2825 rettv->vval.v_job = buf->b_term->tl_job;
2826 if (rettv->vval.v_job != NULL)
2827 ++rettv->vval.v_job->jv_refcount;
2828}
2829
2830 static int
2831get_row_number(typval_T *tv, term_T *term)
2832{
2833 if (tv->v_type == VAR_STRING
2834 && tv->vval.v_string != NULL
2835 && STRCMP(tv->vval.v_string, ".") == 0)
2836 return term->tl_cursor_pos.row;
2837 return (int)get_tv_number(tv) - 1;
2838}
2839
2840/*
2841 * "term_getline(buf, row)" function
2842 */
2843 void
2844f_term_getline(typval_T *argvars, typval_T *rettv)
2845{
2846 buf_T *buf = term_get_buf(argvars);
2847 term_T *term;
2848 int row;
2849
2850 rettv->v_type = VAR_STRING;
2851 if (buf == NULL)
2852 return;
2853 term = buf->b_term;
2854 row = get_row_number(&argvars[1], term);
2855
2856 if (term->tl_vterm == NULL)
2857 {
2858 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
2859
2860 /* vterm is finished, get the text from the buffer */
2861 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
2862 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
2863 }
2864 else
2865 {
2866 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
2867 VTermRect rect;
2868 int len;
2869 char_u *p;
2870
2871 if (row < 0 || row >= term->tl_rows)
2872 return;
2873 len = term->tl_cols * MB_MAXBYTES + 1;
2874 p = alloc(len);
2875 if (p == NULL)
2876 return;
2877 rettv->vval.v_string = p;
2878
2879 rect.start_col = 0;
2880 rect.end_col = term->tl_cols;
2881 rect.start_row = row;
2882 rect.end_row = row + 1;
2883 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
2884 }
2885}
2886
2887/*
2888 * "term_getscrolled(buf)" function
2889 */
2890 void
2891f_term_getscrolled(typval_T *argvars, typval_T *rettv)
2892{
2893 buf_T *buf = term_get_buf(argvars);
2894
2895 if (buf == NULL)
2896 return;
2897 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
2898}
2899
2900/*
2901 * "term_getsize(buf)" function
2902 */
2903 void
2904f_term_getsize(typval_T *argvars, typval_T *rettv)
2905{
2906 buf_T *buf = term_get_buf(argvars);
2907 list_T *l;
2908
2909 if (rettv_list_alloc(rettv) == FAIL)
2910 return;
2911 if (buf == NULL)
2912 return;
2913
2914 l = rettv->vval.v_list;
2915 list_append_number(l, buf->b_term->tl_rows);
2916 list_append_number(l, buf->b_term->tl_cols);
2917}
2918
2919/*
2920 * "term_getstatus(buf)" function
2921 */
2922 void
2923f_term_getstatus(typval_T *argvars, typval_T *rettv)
2924{
2925 buf_T *buf = term_get_buf(argvars);
2926 term_T *term;
2927 char_u val[100];
2928
2929 rettv->v_type = VAR_STRING;
2930 if (buf == NULL)
2931 return;
2932 term = buf->b_term;
2933
2934 if (term_job_running(term))
2935 STRCPY(val, "running");
2936 else
2937 STRCPY(val, "finished");
2938 if (term->tl_normal_mode)
2939 STRCAT(val, ",normal");
2940 rettv->vval.v_string = vim_strsave(val);
2941}
2942
2943/*
2944 * "term_gettitle(buf)" function
2945 */
2946 void
2947f_term_gettitle(typval_T *argvars, typval_T *rettv)
2948{
2949 buf_T *buf = term_get_buf(argvars);
2950
2951 rettv->v_type = VAR_STRING;
2952 if (buf == NULL)
2953 return;
2954
2955 if (buf->b_term->tl_title != NULL)
2956 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
2957}
2958
2959/*
2960 * "term_gettty(buf)" function
2961 */
2962 void
2963f_term_gettty(typval_T *argvars, typval_T *rettv)
2964{
2965 buf_T *buf = term_get_buf(argvars);
2966 char_u *p;
2967 int num = 0;
2968
2969 rettv->v_type = VAR_STRING;
2970 if (buf == NULL)
2971 return;
2972 if (argvars[1].v_type != VAR_UNKNOWN)
2973 num = get_tv_number(&argvars[1]);
2974
2975 switch (num)
2976 {
2977 case 0:
2978 if (buf->b_term->tl_job != NULL)
2979 p = buf->b_term->tl_job->jv_tty_out;
2980 else
2981 p = buf->b_term->tl_tty_out;
2982 break;
2983 case 1:
2984 if (buf->b_term->tl_job != NULL)
2985 p = buf->b_term->tl_job->jv_tty_in;
2986 else
2987 p = buf->b_term->tl_tty_in;
2988 break;
2989 default:
2990 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
2991 return;
2992 }
2993 if (p != NULL)
2994 rettv->vval.v_string = vim_strsave(p);
2995}
2996
2997/*
2998 * "term_list()" function
2999 */
3000 void
3001f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
3002{
3003 term_T *tp;
3004 list_T *l;
3005
3006 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
3007 return;
3008
3009 l = rettv->vval.v_list;
3010 for (tp = first_term; tp != NULL; tp = tp->tl_next)
3011 if (tp != NULL && tp->tl_buffer != NULL)
3012 if (list_append_number(l,
3013 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
3014 return;
3015}
3016
3017/*
3018 * "term_scrape(buf, row)" function
3019 */
3020 void
3021f_term_scrape(typval_T *argvars, typval_T *rettv)
3022{
3023 buf_T *buf = term_get_buf(argvars);
3024 VTermScreen *screen = NULL;
3025 VTermPos pos;
3026 list_T *l;
3027 term_T *term;
3028 char_u *p;
3029 sb_line_T *line;
3030
3031 if (rettv_list_alloc(rettv) == FAIL)
3032 return;
3033 if (buf == NULL)
3034 return;
3035 term = buf->b_term;
3036
3037 l = rettv->vval.v_list;
3038 pos.row = get_row_number(&argvars[1], term);
3039
3040 if (term->tl_vterm != NULL)
3041 {
3042 screen = vterm_obtain_screen(term->tl_vterm);
3043 p = NULL;
3044 line = NULL;
3045 }
3046 else
3047 {
3048 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
3049
3050 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
3051 return;
3052 p = ml_get_buf(buf, lnum + 1, FALSE);
3053 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
3054 }
3055
3056 for (pos.col = 0; pos.col < term->tl_cols; )
3057 {
3058 dict_T *dcell;
3059 int width;
3060 VTermScreenCellAttrs attrs;
3061 VTermColor fg, bg;
3062 char_u rgb[8];
3063 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
3064 int off = 0;
3065 int i;
3066
3067 if (screen == NULL)
3068 {
3069 cellattr_T *cellattr;
3070 int len;
3071
3072 /* vterm has finished, get the cell from scrollback */
3073 if (pos.col >= line->sb_cols)
3074 break;
3075 cellattr = line->sb_cells + pos.col;
3076 width = cellattr->width;
3077 attrs = cellattr->attrs;
3078 fg = cellattr->fg;
3079 bg = cellattr->bg;
3080 len = MB_PTR2LEN(p);
3081 mch_memmove(mbs, p, len);
3082 mbs[len] = NUL;
3083 p += len;
3084 }
3085 else
3086 {
3087 VTermScreenCell cell;
3088 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3089 break;
3090 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3091 {
3092 if (cell.chars[i] == 0)
3093 break;
3094 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
3095 }
3096 mbs[off] = NUL;
3097 width = cell.width;
3098 attrs = cell.attrs;
3099 fg = cell.fg;
3100 bg = cell.bg;
3101 }
3102 dcell = dict_alloc();
3103 list_append_dict(l, dcell);
3104
3105 dict_add_nr_str(dcell, "chars", 0, mbs);
3106
3107 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3108 fg.red, fg.green, fg.blue);
3109 dict_add_nr_str(dcell, "fg", 0, rgb);
3110 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
3111 bg.red, bg.green, bg.blue);
3112 dict_add_nr_str(dcell, "bg", 0, rgb);
3113
3114 dict_add_nr_str(dcell, "attr",
3115 cell2attr(attrs, fg, bg), NULL);
3116 dict_add_nr_str(dcell, "width", width, NULL);
3117
3118 ++pos.col;
3119 if (width == 2)
3120 ++pos.col;
3121 }
3122}
3123
3124/*
3125 * "term_sendkeys(buf, keys)" function
3126 */
3127 void
3128f_term_sendkeys(typval_T *argvars, typval_T *rettv)
3129{
3130 buf_T *buf = term_get_buf(argvars);
3131 char_u *msg;
3132 term_T *term;
3133
3134 rettv->v_type = VAR_UNKNOWN;
3135 if (buf == NULL)
3136 return;
3137
3138 msg = get_tv_string_chk(&argvars[1]);
3139 if (msg == NULL)
3140 return;
3141 term = buf->b_term;
3142 if (term->tl_vterm == NULL)
3143 return;
3144
3145 while (*msg != NUL)
3146 {
3147 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02003148 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003149 }
3150}
3151
3152/*
3153 * "term_start(command, options)" function
3154 */
3155 void
3156f_term_start(typval_T *argvars, typval_T *rettv)
3157{
3158 jobopt_T opt;
3159 buf_T *buf;
3160
3161 init_job_options(&opt);
3162 if (argvars[1].v_type != VAR_UNKNOWN
3163 && get_job_options(&argvars[1], &opt,
3164 JO_TIMEOUT_ALL + JO_STOPONEXIT
3165 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
3166 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
3167 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
3168 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
3169 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS) == FAIL)
3170 return;
3171
3172 if (opt.jo_vertical)
3173 cmdmod.split = WSP_VERT;
3174 buf = term_start(&argvars[0], &opt, FALSE);
3175
3176 if (buf != NULL && buf->b_term != NULL)
3177 rettv->vval.v_number = buf->b_fnum;
3178}
3179
3180/*
3181 * "term_wait" function
3182 */
3183 void
3184f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
3185{
3186 buf_T *buf = term_get_buf(argvars);
3187
3188 if (buf == NULL)
3189 {
3190 ch_log(NULL, "term_wait(): invalid argument");
3191 return;
3192 }
3193 if (buf->b_term->tl_job == NULL)
3194 {
3195 ch_log(NULL, "term_wait(): no job to wait for");
3196 return;
3197 }
3198 if (buf->b_term->tl_job->jv_channel == NULL)
3199 /* channel is closed, nothing to do */
3200 return;
3201
3202 /* Get the job status, this will detect a job that finished. */
3203 if ((buf->b_term->tl_job->jv_channel == NULL
3204 || !buf->b_term->tl_job->jv_channel->ch_keep_open)
3205 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
3206 {
3207 /* The job is dead, keep reading channel I/O until the channel is
3208 * closed. buf->b_term may become NULL if the terminal was closed while
3209 * waiting. */
3210 ch_log(NULL, "term_wait(): waiting for channel to close");
3211 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
3212 {
3213 mch_check_messages();
3214 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01003215 if (!buf_valid(buf))
3216 /* If the terminal is closed when the channel is closed the
3217 * buffer disappears. */
3218 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003219 ui_delay(10L, FALSE);
3220 }
3221 mch_check_messages();
3222 parse_queued_messages();
3223 }
3224 else
3225 {
3226 long wait = 10L;
3227
3228 mch_check_messages();
3229 parse_queued_messages();
3230
3231 /* Wait for some time for any channel I/O. */
3232 if (argvars[1].v_type != VAR_UNKNOWN)
3233 wait = get_tv_number(&argvars[1]);
3234 ui_delay(wait, TRUE);
3235 mch_check_messages();
3236
3237 /* Flushing messages on channels is hopefully sufficient.
3238 * TODO: is there a better way? */
3239 parse_queued_messages();
3240 }
3241}
3242
3243/*
3244 * Called when a channel has sent all the lines to a terminal.
3245 * Send a CTRL-D to mark the end of the text.
3246 */
3247 void
3248term_send_eof(channel_T *ch)
3249{
3250 term_T *term;
3251
3252 for (term = first_term; term != NULL; term = term->tl_next)
3253 if (term->tl_job == ch->ch_job)
3254 {
3255 if (term->tl_eof_chars != NULL)
3256 {
3257 channel_send(ch, PART_IN, term->tl_eof_chars,
3258 (int)STRLEN(term->tl_eof_chars), NULL);
3259 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
3260 }
3261# ifdef WIN3264
3262 else
3263 /* Default: CTRL-D */
3264 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
3265# endif
3266 }
3267}
3268
3269# if defined(WIN3264) || defined(PROTO)
3270
3271/**************************************
3272 * 2. MS-Windows implementation.
3273 */
3274
3275# ifndef PROTO
3276
3277#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
3278#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
3279#define WINPTY_MOUSE_MODE_FORCE 2
3280
3281void* (*winpty_config_new)(UINT64, void*);
3282void* (*winpty_open)(void*, void*);
3283void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
3284BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
3285void (*winpty_config_set_mouse_mode)(void*, int);
3286void (*winpty_config_set_initial_size)(void*, int, int);
3287LPCWSTR (*winpty_conin_name)(void*);
3288LPCWSTR (*winpty_conout_name)(void*);
3289LPCWSTR (*winpty_conerr_name)(void*);
3290void (*winpty_free)(void*);
3291void (*winpty_config_free)(void*);
3292void (*winpty_spawn_config_free)(void*);
3293void (*winpty_error_free)(void*);
3294LPCWSTR (*winpty_error_msg)(void*);
3295BOOL (*winpty_set_size)(void*, int, int, void*);
3296HANDLE (*winpty_agent_process)(void*);
3297
3298#define WINPTY_DLL "winpty.dll"
3299
3300static HINSTANCE hWinPtyDLL = NULL;
3301# endif
3302
3303 static int
3304dyn_winpty_init(int verbose)
3305{
3306 int i;
3307 static struct
3308 {
3309 char *name;
3310 FARPROC *ptr;
3311 } winpty_entry[] =
3312 {
3313 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
3314 {"winpty_config_free", (FARPROC*)&winpty_config_free},
3315 {"winpty_config_new", (FARPROC*)&winpty_config_new},
3316 {"winpty_config_set_mouse_mode",
3317 (FARPROC*)&winpty_config_set_mouse_mode},
3318 {"winpty_config_set_initial_size",
3319 (FARPROC*)&winpty_config_set_initial_size},
3320 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
3321 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
3322 {"winpty_error_free", (FARPROC*)&winpty_error_free},
3323 {"winpty_free", (FARPROC*)&winpty_free},
3324 {"winpty_open", (FARPROC*)&winpty_open},
3325 {"winpty_spawn", (FARPROC*)&winpty_spawn},
3326 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
3327 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
3328 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
3329 {"winpty_set_size", (FARPROC*)&winpty_set_size},
3330 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
3331 {NULL, NULL}
3332 };
3333
3334 /* No need to initialize twice. */
3335 if (hWinPtyDLL)
3336 return OK;
3337 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
3338 * winpty.dll. */
3339 if (*p_winptydll != NUL)
3340 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
3341 if (!hWinPtyDLL)
3342 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
3343 if (!hWinPtyDLL)
3344 {
3345 if (verbose)
3346 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
3347 : (char_u *)WINPTY_DLL);
3348 return FAIL;
3349 }
3350 for (i = 0; winpty_entry[i].name != NULL
3351 && winpty_entry[i].ptr != NULL; ++i)
3352 {
3353 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
3354 winpty_entry[i].name)) == NULL)
3355 {
3356 if (verbose)
3357 EMSG2(_(e_loadfunc), winpty_entry[i].name);
3358 return FAIL;
3359 }
3360 }
3361
3362 return OK;
3363}
3364
3365/*
3366 * Create a new terminal of "rows" by "cols" cells.
3367 * Store a reference in "term".
3368 * Return OK or FAIL.
3369 */
3370 static int
3371term_and_job_init(
3372 term_T *term,
3373 typval_T *argvar,
3374 jobopt_T *opt)
3375{
3376 WCHAR *cmd_wchar = NULL;
3377 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003378 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003379 channel_T *channel = NULL;
3380 job_T *job = NULL;
3381 DWORD error;
3382 HANDLE jo = NULL;
3383 HANDLE child_process_handle;
3384 HANDLE child_thread_handle;
3385 void *winpty_err;
3386 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003387 garray_T ga_cmd, ga_env;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003388 char_u *cmd;
3389
3390 if (dyn_winpty_init(TRUE) == FAIL)
3391 return FAIL;
3392
3393 if (argvar->v_type == VAR_STRING)
3394 cmd = argvar->vval.v_string;
3395 else
3396 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003397 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
3398 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003399 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003400 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003401 }
3402
3403 cmd_wchar = enc_to_utf16(cmd, NULL);
3404 if (cmd_wchar == NULL)
3405 return FAIL;
3406 if (opt->jo_cwd != NULL)
3407 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003408
3409 ga_init2(&ga_env, (int)sizeof(char*), 20);
3410 win32_build_env(opt->jo_env, &ga_env, TRUE);
3411 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003412
3413 job = job_alloc();
3414 if (job == NULL)
3415 goto failed;
3416
3417 channel = add_channel();
3418 if (channel == NULL)
3419 goto failed;
3420
3421 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
3422 if (term->tl_winpty_config == NULL)
3423 goto failed;
3424
3425 winpty_config_set_mouse_mode(term->tl_winpty_config,
3426 WINPTY_MOUSE_MODE_FORCE);
3427 winpty_config_set_initial_size(term->tl_winpty_config,
3428 term->tl_cols, term->tl_rows);
3429 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
3430 if (term->tl_winpty == NULL)
3431 goto failed;
3432
3433 spawn_config = winpty_spawn_config_new(
3434 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
3435 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
3436 NULL,
3437 cmd_wchar,
3438 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003439 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003440 &winpty_err);
3441 if (spawn_config == NULL)
3442 goto failed;
3443
3444 channel = add_channel();
3445 if (channel == NULL)
3446 goto failed;
3447
3448 job = job_alloc();
3449 if (job == NULL)
3450 goto failed;
3451
3452 if (opt->jo_set & JO_IN_BUF)
3453 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
3454
3455 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
3456 &child_thread_handle, &error, &winpty_err))
3457 goto failed;
3458
3459 channel_set_pipes(channel,
3460 (sock_T)CreateFileW(
3461 winpty_conin_name(term->tl_winpty),
3462 GENERIC_WRITE, 0, NULL,
3463 OPEN_EXISTING, 0, NULL),
3464 (sock_T)CreateFileW(
3465 winpty_conout_name(term->tl_winpty),
3466 GENERIC_READ, 0, NULL,
3467 OPEN_EXISTING, 0, NULL),
3468 (sock_T)CreateFileW(
3469 winpty_conerr_name(term->tl_winpty),
3470 GENERIC_READ, 0, NULL,
3471 OPEN_EXISTING, 0, NULL));
3472
3473 /* Write lines with CR instead of NL. */
3474 channel->ch_write_text_mode = TRUE;
3475
3476 jo = CreateJobObject(NULL, NULL);
3477 if (jo == NULL)
3478 goto failed;
3479
3480 if (!AssignProcessToJobObject(jo, child_process_handle))
3481 {
3482 /* Failed, switch the way to terminate process with TerminateProcess. */
3483 CloseHandle(jo);
3484 jo = NULL;
3485 }
3486
3487 winpty_spawn_config_free(spawn_config);
3488 vim_free(cmd_wchar);
3489 vim_free(cwd_wchar);
3490
3491 create_vterm(term, term->tl_rows, term->tl_cols);
3492
3493 channel_set_job(channel, job, opt);
3494 job_set_options(job, opt);
3495
3496 job->jv_channel = channel;
3497 job->jv_proc_info.hProcess = child_process_handle;
3498 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
3499 job->jv_job_object = jo;
3500 job->jv_status = JOB_STARTED;
3501 job->jv_tty_in = utf16_to_enc(
3502 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
3503 job->jv_tty_out = utf16_to_enc(
3504 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
3505 ++job->jv_refcount;
3506 term->tl_job = job;
3507
3508 return OK;
3509
3510failed:
3511 if (argvar->v_type == VAR_LIST)
Bram Moolenaarba6febd2017-10-30 21:56:23 +01003512 vim_free(ga_cmd.ga_data);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01003513 vim_free(ga_env.ga_data);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003514 vim_free(cmd_wchar);
3515 vim_free(cwd_wchar);
3516 if (spawn_config != NULL)
3517 winpty_spawn_config_free(spawn_config);
3518 if (channel != NULL)
3519 channel_clear(channel);
3520 if (job != NULL)
3521 {
3522 job->jv_channel = NULL;
3523 job_cleanup(job);
3524 }
3525 term->tl_job = NULL;
3526 if (jo != NULL)
3527 CloseHandle(jo);
3528 if (term->tl_winpty != NULL)
3529 winpty_free(term->tl_winpty);
3530 term->tl_winpty = NULL;
3531 if (term->tl_winpty_config != NULL)
3532 winpty_config_free(term->tl_winpty_config);
3533 term->tl_winpty_config = NULL;
3534 if (winpty_err != NULL)
3535 {
3536 char_u *msg = utf16_to_enc(
3537 (short_u *)winpty_error_msg(winpty_err), NULL);
3538
3539 EMSG(msg);
3540 winpty_error_free(winpty_err);
3541 }
3542 return FAIL;
3543}
3544
3545 static int
3546create_pty_only(term_T *term, jobopt_T *options)
3547{
3548 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
3549 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
3550 char in_name[80], out_name[80];
3551 channel_T *channel = NULL;
3552
3553 create_vterm(term, term->tl_rows, term->tl_cols);
3554
3555 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
3556 GetCurrentProcessId(),
3557 curbuf->b_fnum);
3558 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
3559 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3560 PIPE_UNLIMITED_INSTANCES,
3561 0, 0, NMPWAIT_NOWAIT, NULL);
3562 if (hPipeIn == INVALID_HANDLE_VALUE)
3563 goto failed;
3564
3565 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
3566 GetCurrentProcessId(),
3567 curbuf->b_fnum);
3568 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
3569 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
3570 PIPE_UNLIMITED_INSTANCES,
3571 0, 0, 0, NULL);
3572 if (hPipeOut == INVALID_HANDLE_VALUE)
3573 goto failed;
3574
3575 ConnectNamedPipe(hPipeIn, NULL);
3576 ConnectNamedPipe(hPipeOut, NULL);
3577
3578 term->tl_job = job_alloc();
3579 if (term->tl_job == NULL)
3580 goto failed;
3581 ++term->tl_job->jv_refcount;
3582
3583 /* behave like the job is already finished */
3584 term->tl_job->jv_status = JOB_FINISHED;
3585
3586 channel = add_channel();
3587 if (channel == NULL)
3588 goto failed;
3589 term->tl_job->jv_channel = channel;
3590 channel->ch_keep_open = TRUE;
3591 channel->ch_named_pipe = TRUE;
3592
3593 channel_set_pipes(channel,
3594 (sock_T)hPipeIn,
3595 (sock_T)hPipeOut,
3596 (sock_T)hPipeOut);
3597 channel_set_job(channel, term->tl_job, options);
3598 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
3599 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
3600
3601 return OK;
3602
3603failed:
3604 if (hPipeIn != NULL)
3605 CloseHandle(hPipeIn);
3606 if (hPipeOut != NULL)
3607 CloseHandle(hPipeOut);
3608 return FAIL;
3609}
3610
3611/*
3612 * Free the terminal emulator part of "term".
3613 */
3614 static void
3615term_free_vterm(term_T *term)
3616{
3617 if (term->tl_winpty != NULL)
3618 winpty_free(term->tl_winpty);
3619 term->tl_winpty = NULL;
3620 if (term->tl_winpty_config != NULL)
3621 winpty_config_free(term->tl_winpty_config);
3622 term->tl_winpty_config = NULL;
3623 if (term->tl_vterm != NULL)
3624 vterm_free(term->tl_vterm);
3625 term->tl_vterm = NULL;
3626}
3627
3628/*
3629 * Request size to terminal.
3630 */
3631 static void
3632term_report_winsize(term_T *term, int rows, int cols)
3633{
3634 if (term->tl_winpty)
3635 winpty_set_size(term->tl_winpty, cols, rows, NULL);
3636}
3637
3638 int
3639terminal_enabled(void)
3640{
3641 return dyn_winpty_init(FALSE) == OK;
3642}
3643
3644# else
3645
3646/**************************************
3647 * 3. Unix-like implementation.
3648 */
3649
3650/*
3651 * Create a new terminal of "rows" by "cols" cells.
3652 * Start job for "cmd".
3653 * Store the pointers in "term".
3654 * Return OK or FAIL.
3655 */
3656 static int
3657term_and_job_init(
3658 term_T *term,
3659 typval_T *argvar,
3660 jobopt_T *opt)
3661{
3662 create_vterm(term, term->tl_rows, term->tl_cols);
3663
3664 term->tl_job = job_start(argvar, opt);
3665 if (term->tl_job != NULL)
3666 ++term->tl_job->jv_refcount;
3667
3668 return term->tl_job != NULL
3669 && term->tl_job->jv_channel != NULL
3670 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
3671}
3672
3673 static int
3674create_pty_only(term_T *term, jobopt_T *opt)
3675{
3676 create_vterm(term, term->tl_rows, term->tl_cols);
3677
3678 term->tl_job = job_alloc();
3679 if (term->tl_job == NULL)
3680 return FAIL;
3681 ++term->tl_job->jv_refcount;
3682
3683 /* behave like the job is already finished */
3684 term->tl_job->jv_status = JOB_FINISHED;
3685
3686 return mch_create_pty_channel(term->tl_job, opt);
3687}
3688
3689/*
3690 * Free the terminal emulator part of "term".
3691 */
3692 static void
3693term_free_vterm(term_T *term)
3694{
3695 if (term->tl_vterm != NULL)
3696 vterm_free(term->tl_vterm);
3697 term->tl_vterm = NULL;
3698}
3699
3700/*
3701 * Request size to terminal.
3702 */
3703 static void
3704term_report_winsize(term_T *term, int rows, int cols)
3705{
3706 /* Use an ioctl() to report the new window size to the job. */
3707 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
3708 {
3709 int fd = -1;
3710 int part;
3711
3712 for (part = PART_OUT; part < PART_COUNT; ++part)
3713 {
3714 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
3715 if (isatty(fd))
3716 break;
3717 }
3718 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
3719 mch_signal_job(term->tl_job, (char_u *)"winch");
3720 }
3721}
3722
3723# endif
3724
3725#endif /* FEAT_TERMINAL */