blob: 1bef460607084ed94eea300879dc9cd9ef15e922 [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
Bram Moolenaarb852c3e2018-03-11 16:55:36 +010042 * - In the GUI use a terminal emulator for :!cmd. Make the height the same as
43 * the window and position it higher up when it gets filled, so it looks like
44 * the text scrolls up.
45 * - implement term_setsize()
46 * - Copy text in the vterm to the Vim buffer once in a while, so that
47 * completion works.
Bram Moolenaar4d8bac82018-03-09 21:33:34 +010048 * - Adding WinBar to terminal window doesn't display, text isn't shifted down.
Bram Moolenaar46359e12017-11-29 22:33:38 +010049 * a job that uses 16 colors while Vim is using > 256.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020050 * - in GUI vertical split causes problems. Cursor is flickering. (Hirohito
51 * Higashi, 2017 Sep 19)
Bram Moolenaar3a497e12017-09-30 20:40:27 +020052 * - after resizing windows overlap. (Boris Staletic, #2164)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020053 * - Redirecting output does not work on MS-Windows, Test_terminal_redir_file()
54 * is disabled.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020055 * - cursor blinks in terminal on widows with a timer. (xtal8, #2142)
Bram Moolenaarba6febd2017-10-30 21:56:23 +010056 * - Termdebug does not work when Vim build with mzscheme. gdb hangs.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +020057 * - MS-Windows GUI: WinBar has tearoff item
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020058 * - MS-Windows GUI: still need to type a key after shell exits? #1924
Bram Moolenaar51b0f372017-11-18 18:52:04 +010059 * - After executing a shell command the status line isn't redraw.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020060 * - add test for giving error for invalid 'termsize' value.
61 * - support minimal size when 'termsize' is "rows*cols".
62 * - support minimal size when 'termsize' is empty?
63 * - GUI: when using tabs, focus in terminal, click on tab does not work.
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +020064 * - Redrawing is slow with Athena and Motif. Also other GUI? (Ramel Eshed)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020065 * - For the GUI fill termios with default values, perhaps like pangoterm:
66 * http://bazaar.launchpad.net/~leonerd/pangoterm/trunk/view/head:/main.c#L134
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020067 * - when 'encoding' is not utf-8, or the job is using another encoding, setup
68 * conversions.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020069 * - add an optional limit for the scrollback size. When reaching it remove
70 * 10% at the start.
71 */
72
73#include "vim.h"
74
75#if defined(FEAT_TERMINAL) || defined(PROTO)
76
77#ifndef MIN
78# define MIN(x,y) ((x) < (y) ? (x) : (y))
79#endif
80#ifndef MAX
81# define MAX(x,y) ((x) > (y) ? (x) : (y))
82#endif
83
84#include "libvterm/include/vterm.h"
85
86/* This is VTermScreenCell without the characters, thus much smaller. */
87typedef struct {
88 VTermScreenCellAttrs attrs;
89 char width;
Bram Moolenaard96ff162018-02-18 22:13:29 +010090 VTermColor fg;
91 VTermColor bg;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +020092} cellattr_T;
93
94typedef struct sb_line_S {
95 int sb_cols; /* can differ per line */
96 cellattr_T *sb_cells; /* allocated */
97 cellattr_T sb_fill_attr; /* for short line */
98} sb_line_T;
99
100/* typedef term_T in structs.h */
101struct terminal_S {
102 term_T *tl_next;
103
104 VTerm *tl_vterm;
105 job_T *tl_job;
106 buf_T *tl_buffer;
107
108 /* Set when setting the size of a vterm, reset after redrawing. */
109 int tl_vterm_size_changed;
110
111 /* used when tl_job is NULL and only a pty was created */
112 int tl_tty_fd;
113 char_u *tl_tty_in;
114 char_u *tl_tty_out;
115
116 int tl_normal_mode; /* TRUE: Terminal-Normal mode */
117 int tl_channel_closed;
118 int tl_finish; /* 'c' for ++close, 'o' for ++open */
119 char_u *tl_opencmd;
120 char_u *tl_eof_chars;
121
122#ifdef WIN3264
123 void *tl_winpty_config;
124 void *tl_winpty;
125#endif
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100126#if defined(FEAT_SESSION)
127 char_u *tl_command;
128#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100129 char_u *tl_kill;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200130
131 /* last known vterm size */
132 int tl_rows;
133 int tl_cols;
134 /* vterm size does not follow window size */
135 int tl_rows_fixed;
136 int tl_cols_fixed;
137
138 char_u *tl_title; /* NULL or allocated */
139 char_u *tl_status_text; /* NULL or allocated */
140
141 /* Range of screen rows to update. Zero based. */
Bram Moolenaar3a497e12017-09-30 20:40:27 +0200142 int tl_dirty_row_start; /* MAX_ROW if nothing dirty */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200143 int tl_dirty_row_end; /* row below last one to update */
144
145 garray_T tl_scrollback;
146 int tl_scrollback_scrolled;
147 cellattr_T tl_default_color;
148
Bram Moolenaard96ff162018-02-18 22:13:29 +0100149 linenr_T tl_top_diff_rows; /* rows of top diff file or zero */
150 linenr_T tl_bot_diff_rows; /* rows of bottom diff file */
151
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200152 VTermPos tl_cursor_pos;
153 int tl_cursor_visible;
154 int tl_cursor_blink;
155 int tl_cursor_shape; /* 1: block, 2: underline, 3: bar */
156 char_u *tl_cursor_color; /* NULL or allocated */
157
158 int tl_using_altscreen;
159};
160
161#define TMODE_ONCE 1 /* CTRL-\ CTRL-N used */
162#define TMODE_LOOP 2 /* CTRL-W N used */
163
164/*
165 * List of all active terminals.
166 */
167static term_T *first_term = NULL;
168
169/* Terminal active in terminal_loop(). */
170static term_T *in_terminal_loop = NULL;
171
172#define MAX_ROW 999999 /* used for tl_dirty_row_end to update all rows */
173#define KEY_BUF_LEN 200
174
175/*
176 * Functions with separate implementation for MS-Windows and Unix-like systems.
177 */
178static int term_and_job_init(term_T *term, typval_T *argvar, jobopt_T *opt);
179static int create_pty_only(term_T *term, jobopt_T *opt);
180static void term_report_winsize(term_T *term, int rows, int cols);
181static void term_free_vterm(term_T *term);
182
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100183/* The character that we know (or assume) that the terminal expects for the
184 * backspace key. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200185static int term_backspace_char = BS;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200186
Bram Moolenaara7c54cf2017-12-01 21:07:20 +0100187/* "Terminal" highlight group colors. */
188static int term_default_cterm_fg = -1;
189static int term_default_cterm_bg = -1;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200190
Bram Moolenaard317b382018-02-08 22:33:31 +0100191/* Store the last set and the desired cursor properties, so that we only update
192 * them when needed. Doing it unnecessary may result in flicker. */
193static char_u *last_set_cursor_color = (char_u *)"";
194static char_u *desired_cursor_color = (char_u *)"";
195static int last_set_cursor_shape = -1;
196static int desired_cursor_shape = -1;
197static int last_set_cursor_blink = -1;
198static int desired_cursor_blink = -1;
199
200
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200201/**************************************
202 * 1. Generic code for all systems.
203 */
204
205/*
206 * Determine the terminal size from 'termsize' and the current window.
207 * Assumes term->tl_rows and term->tl_cols are zero.
208 */
209 static void
210set_term_and_win_size(term_T *term)
211{
212 if (*curwin->w_p_tms != NUL)
213 {
214 char_u *p = vim_strchr(curwin->w_p_tms, 'x') + 1;
215
216 term->tl_rows = atoi((char *)curwin->w_p_tms);
217 term->tl_cols = atoi((char *)p);
218 }
219 if (term->tl_rows == 0)
220 term->tl_rows = curwin->w_height;
221 else
222 {
223 win_setheight_win(term->tl_rows, curwin);
224 term->tl_rows_fixed = TRUE;
225 }
226 if (term->tl_cols == 0)
227 term->tl_cols = curwin->w_width;
228 else
229 {
230 win_setwidth_win(term->tl_cols, curwin);
231 term->tl_cols_fixed = TRUE;
232 }
233}
234
235/*
236 * Initialize job options for a terminal job.
237 * Caller may overrule some of them.
238 */
239 static void
240init_job_options(jobopt_T *opt)
241{
242 clear_job_options(opt);
243
244 opt->jo_mode = MODE_RAW;
245 opt->jo_out_mode = MODE_RAW;
246 opt->jo_err_mode = MODE_RAW;
247 opt->jo_set = JO_MODE | JO_OUT_MODE | JO_ERR_MODE;
248}
249
250/*
251 * Set job options mandatory for a terminal job.
252 */
253 static void
254setup_job_options(jobopt_T *opt, int rows, int cols)
255{
256 if (!(opt->jo_set & JO_OUT_IO))
257 {
258 /* Connect stdout to the terminal. */
259 opt->jo_io[PART_OUT] = JIO_BUFFER;
260 opt->jo_io_buf[PART_OUT] = curbuf->b_fnum;
261 opt->jo_modifiable[PART_OUT] = 0;
262 opt->jo_set |= JO_OUT_IO + JO_OUT_BUF + JO_OUT_MODIFIABLE;
263 }
264
265 if (!(opt->jo_set & JO_ERR_IO))
266 {
267 /* Connect stderr to the terminal. */
268 opt->jo_io[PART_ERR] = JIO_BUFFER;
269 opt->jo_io_buf[PART_ERR] = curbuf->b_fnum;
270 opt->jo_modifiable[PART_ERR] = 0;
271 opt->jo_set |= JO_ERR_IO + JO_ERR_BUF + JO_ERR_MODIFIABLE;
272 }
273
274 opt->jo_pty = TRUE;
275 if ((opt->jo_set2 & JO2_TERM_ROWS) == 0)
276 opt->jo_term_rows = rows;
277 if ((opt->jo_set2 & JO2_TERM_COLS) == 0)
278 opt->jo_term_cols = cols;
279}
280
281/*
Bram Moolenaard96ff162018-02-18 22:13:29 +0100282 * Close a terminal buffer (and its window). Used when creating the terminal
283 * fails.
284 */
285 static void
286term_close_buffer(buf_T *buf, buf_T *old_curbuf)
287{
288 free_terminal(buf);
289 if (old_curbuf != NULL)
290 {
291 --curbuf->b_nwindows;
292 curbuf = old_curbuf;
293 curwin->w_buffer = curbuf;
294 ++curbuf->b_nwindows;
295 }
296
297 /* Wiping out the buffer will also close the window and call
298 * free_terminal(). */
299 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
300}
301
302/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200303 * Start a terminal window and return its buffer.
Bram Moolenaard96ff162018-02-18 22:13:29 +0100304 * When "without_job" is TRUE only create the buffer, b_term and open the
305 * window.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200306 * Returns NULL when failed.
307 */
308 static buf_T *
Bram Moolenaard96ff162018-02-18 22:13:29 +0100309term_start(typval_T *argvar, jobopt_T *opt, int without_job, int forceit)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200310{
311 exarg_T split_ea;
312 win_T *old_curwin = curwin;
313 term_T *term;
314 buf_T *old_curbuf = NULL;
315 int res;
316 buf_T *newbuf;
317
318 if (check_restricted() || check_secure())
319 return NULL;
320
321 if ((opt->jo_set & (JO_IN_IO + JO_OUT_IO + JO_ERR_IO))
322 == (JO_IN_IO + JO_OUT_IO + JO_ERR_IO)
323 || (!(opt->jo_set & JO_OUT_IO) && (opt->jo_set & JO_OUT_BUF))
324 || (!(opt->jo_set & JO_ERR_IO) && (opt->jo_set & JO_ERR_BUF)))
325 {
326 EMSG(_(e_invarg));
327 return NULL;
328 }
329
330 term = (term_T *)alloc_clear(sizeof(term_T));
331 if (term == NULL)
332 return NULL;
333 term->tl_dirty_row_end = MAX_ROW;
334 term->tl_cursor_visible = TRUE;
335 term->tl_cursor_shape = VTERM_PROP_CURSORSHAPE_BLOCK;
336 term->tl_finish = opt->jo_term_finish;
337 ga_init2(&term->tl_scrollback, sizeof(sb_line_T), 300);
338
339 vim_memset(&split_ea, 0, sizeof(split_ea));
340 if (opt->jo_curwin)
341 {
342 /* Create a new buffer in the current window. */
343 if (!can_abandon(curbuf, forceit))
344 {
345 no_write_message();
346 vim_free(term);
347 return NULL;
348 }
349 if (do_ecmd(0, NULL, NULL, &split_ea, ECMD_ONE,
350 ECMD_HIDE + (forceit ? ECMD_FORCEIT : 0), curwin) == FAIL)
351 {
352 vim_free(term);
353 return NULL;
354 }
355 }
356 else if (opt->jo_hidden)
357 {
358 buf_T *buf;
359
360 /* Create a new buffer without a window. Make it the current buffer for
361 * a moment to be able to do the initialisations. */
362 buf = buflist_new((char_u *)"", NULL, (linenr_T)0,
363 BLN_NEW | BLN_LISTED);
364 if (buf == NULL || ml_open(buf) == FAIL)
365 {
366 vim_free(term);
367 return NULL;
368 }
369 old_curbuf = curbuf;
370 --curbuf->b_nwindows;
371 curbuf = buf;
372 curwin->w_buffer = buf;
373 ++curbuf->b_nwindows;
374 }
375 else
376 {
377 /* Open a new window or tab. */
378 split_ea.cmdidx = CMD_new;
379 split_ea.cmd = (char_u *)"new";
380 split_ea.arg = (char_u *)"";
381 if (opt->jo_term_rows > 0 && !(cmdmod.split & WSP_VERT))
382 {
383 split_ea.line2 = opt->jo_term_rows;
384 split_ea.addr_count = 1;
385 }
386 if (opt->jo_term_cols > 0 && (cmdmod.split & WSP_VERT))
387 {
388 split_ea.line2 = opt->jo_term_cols;
389 split_ea.addr_count = 1;
390 }
391
392 ex_splitview(&split_ea);
393 if (curwin == old_curwin)
394 {
395 /* split failed */
396 vim_free(term);
397 return NULL;
398 }
399 }
400 term->tl_buffer = curbuf;
401 curbuf->b_term = term;
402
403 if (!opt->jo_hidden)
404 {
Bram Moolenaarda650582018-02-20 15:51:40 +0100405 /* Only one size was taken care of with :new, do the other one. With
406 * "curwin" both need to be done. */
407 if (opt->jo_term_rows > 0 && (opt->jo_curwin
408 || (cmdmod.split & WSP_VERT)))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200409 win_setheight(opt->jo_term_rows);
Bram Moolenaarda650582018-02-20 15:51:40 +0100410 if (opt->jo_term_cols > 0 && (opt->jo_curwin
411 || !(cmdmod.split & WSP_VERT)))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200412 win_setwidth(opt->jo_term_cols);
413 }
414
415 /* Link the new terminal in the list of active terminals. */
416 term->tl_next = first_term;
417 first_term = term;
418
419 if (opt->jo_term_name != NULL)
420 curbuf->b_ffname = vim_strsave(opt->jo_term_name);
421 else
422 {
423 int i;
424 size_t len;
425 char_u *cmd, *p;
426
427 if (argvar->v_type == VAR_STRING)
428 {
429 cmd = argvar->vval.v_string;
430 if (cmd == NULL)
431 cmd = (char_u *)"";
432 else if (STRCMP(cmd, "NONE") == 0)
433 cmd = (char_u *)"pty";
434 }
435 else if (argvar->v_type != VAR_LIST
436 || argvar->vval.v_list == NULL
437 || argvar->vval.v_list->lv_len < 1
438 || (cmd = get_tv_string_chk(
439 &argvar->vval.v_list->lv_first->li_tv)) == NULL)
440 cmd = (char_u*)"";
441
442 len = STRLEN(cmd) + 10;
443 p = alloc((int)len);
444
445 for (i = 0; p != NULL; ++i)
446 {
447 /* Prepend a ! to the command name to avoid the buffer name equals
448 * the executable, otherwise ":w!" would overwrite it. */
449 if (i == 0)
450 vim_snprintf((char *)p, len, "!%s", cmd);
451 else
452 vim_snprintf((char *)p, len, "!%s (%d)", cmd, i);
453 if (buflist_findname(p) == NULL)
454 {
455 vim_free(curbuf->b_ffname);
456 curbuf->b_ffname = p;
457 break;
458 }
459 }
460 }
461 curbuf->b_fname = curbuf->b_ffname;
462
463 if (opt->jo_term_opencmd != NULL)
464 term->tl_opencmd = vim_strsave(opt->jo_term_opencmd);
465
466 if (opt->jo_eof_chars != NULL)
467 term->tl_eof_chars = vim_strsave(opt->jo_eof_chars);
468
469 set_string_option_direct((char_u *)"buftype", -1,
470 (char_u *)"terminal", OPT_FREE|OPT_LOCAL, 0);
471
472 /* Mark the buffer as not modifiable. It can only be made modifiable after
473 * the job finished. */
474 curbuf->b_p_ma = FALSE;
475
476 set_term_and_win_size(term);
477 setup_job_options(opt, term->tl_rows, term->tl_cols);
478
Bram Moolenaard96ff162018-02-18 22:13:29 +0100479 if (without_job)
480 return curbuf;
481
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100482#if defined(FEAT_SESSION)
483 /* Remember the command for the session file. */
484 if (opt->jo_term_norestore)
485 {
486 term->tl_command = vim_strsave((char_u *)"NONE");
487 }
488 else if (argvar->v_type == VAR_STRING)
489 {
490 char_u *cmd = argvar->vval.v_string;
491
492 if (cmd != NULL && STRCMP(cmd, p_sh) != 0)
493 term->tl_command = vim_strsave(cmd);
494 }
495 else if (argvar->v_type == VAR_LIST
496 && argvar->vval.v_list != NULL
497 && argvar->vval.v_list->lv_len > 0)
498 {
499 garray_T ga;
500 listitem_T *item;
501
502 ga_init2(&ga, 1, 100);
503 for (item = argvar->vval.v_list->lv_first;
504 item != NULL; item = item->li_next)
505 {
506 char_u *s = get_tv_string_chk(&item->li_tv);
507 char_u *p;
508
509 if (s == NULL)
510 break;
511 p = vim_strsave_fnameescape(s, FALSE);
512 if (p == NULL)
513 break;
514 ga_concat(&ga, p);
515 vim_free(p);
516 ga_append(&ga, ' ');
517 }
518 if (item == NULL)
519 {
520 ga_append(&ga, NUL);
521 term->tl_command = ga.ga_data;
522 }
523 else
524 ga_clear(&ga);
525 }
526#endif
527
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100528 if (opt->jo_term_kill != NULL)
529 {
530 char_u *p = skiptowhite(opt->jo_term_kill);
531
532 term->tl_kill = vim_strnsave(opt->jo_term_kill, p - opt->jo_term_kill);
533 }
534
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200535 /* System dependent: setup the vterm and maybe start the job in it. */
536 if (argvar->v_type == VAR_STRING
537 && argvar->vval.v_string != NULL
538 && STRCMP(argvar->vval.v_string, "NONE") == 0)
539 res = create_pty_only(term, opt);
540 else
541 res = term_and_job_init(term, argvar, opt);
542
543 newbuf = curbuf;
544 if (res == OK)
545 {
546 /* Get and remember the size we ended up with. Update the pty. */
547 vterm_get_size(term->tl_vterm, &term->tl_rows, &term->tl_cols);
548 term_report_winsize(term, term->tl_rows, term->tl_cols);
549
550 /* Make sure we don't get stuck on sending keys to the job, it leads to
551 * a deadlock if the job is waiting for Vim to read. */
552 channel_set_nonblock(term->tl_job->jv_channel, PART_IN);
553
Bram Moolenaarab5e7c32018-02-13 14:07:18 +0100554 if (!opt->jo_hidden)
555 {
556 ++curbuf->b_locked;
557 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
558 --curbuf->b_locked;
559 }
Bram Moolenaar8b21de32017-09-22 11:13:52 +0200560
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200561 if (old_curbuf != NULL)
562 {
563 --curbuf->b_nwindows;
564 curbuf = old_curbuf;
565 curwin->w_buffer = curbuf;
566 ++curbuf->b_nwindows;
567 }
568 }
569 else
570 {
Bram Moolenaard96ff162018-02-18 22:13:29 +0100571 term_close_buffer(curbuf, old_curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200572 return NULL;
573 }
Bram Moolenaarb852c3e2018-03-11 16:55:36 +0100574
575 apply_autocmds(EVENT_TERMINALOPEN, NULL, NULL, FALSE, curbuf);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200576 return newbuf;
577}
578
579/*
580 * ":terminal": open a terminal window and execute a job in it.
581 */
582 void
583ex_terminal(exarg_T *eap)
584{
585 typval_T argvar[2];
586 jobopt_T opt;
587 char_u *cmd;
588 char_u *tofree = NULL;
589
590 init_job_options(&opt);
591
592 cmd = eap->arg;
Bram Moolenaara15ef452018-02-09 16:46:00 +0100593 while (*cmd == '+' && *(cmd + 1) == '+')
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200594 {
595 char_u *p, *ep;
596
597 cmd += 2;
598 p = skiptowhite(cmd);
599 ep = vim_strchr(cmd, '=');
600 if (ep != NULL && ep < p)
601 p = ep;
602
603 if ((int)(p - cmd) == 5 && STRNICMP(cmd, "close", 5) == 0)
604 opt.jo_term_finish = 'c';
605 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "open", 4) == 0)
606 opt.jo_term_finish = 'o';
607 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "curwin", 6) == 0)
608 opt.jo_curwin = 1;
609 else if ((int)(p - cmd) == 6 && STRNICMP(cmd, "hidden", 6) == 0)
610 opt.jo_hidden = 1;
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100611 else if ((int)(p - cmd) == 9 && STRNICMP(cmd, "norestore", 9) == 0)
612 opt.jo_term_norestore = 1;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100613 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "kill", 4) == 0
614 && ep != NULL)
615 {
616 opt.jo_set2 |= JO2_TERM_KILL;
617 opt.jo_term_kill = ep + 1;
618 p = skiptowhite(cmd);
619 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200620 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "rows", 4) == 0
621 && ep != NULL && isdigit(ep[1]))
622 {
623 opt.jo_set2 |= JO2_TERM_ROWS;
624 opt.jo_term_rows = atoi((char *)ep + 1);
625 p = skiptowhite(cmd);
626 }
627 else if ((int)(p - cmd) == 4 && STRNICMP(cmd, "cols", 4) == 0
628 && ep != NULL && isdigit(ep[1]))
629 {
630 opt.jo_set2 |= JO2_TERM_COLS;
631 opt.jo_term_cols = atoi((char *)ep + 1);
632 p = skiptowhite(cmd);
633 }
634 else if ((int)(p - cmd) == 3 && STRNICMP(cmd, "eof", 3) == 0
635 && ep != NULL)
636 {
637 char_u *buf = NULL;
638 char_u *keys;
639
640 p = skiptowhite(cmd);
641 *p = NUL;
642 keys = replace_termcodes(ep + 1, &buf, TRUE, TRUE, TRUE);
643 opt.jo_set2 |= JO2_EOF_CHARS;
644 opt.jo_eof_chars = vim_strsave(keys);
645 vim_free(buf);
646 *p = ' ';
647 }
648 else
649 {
650 if (*p)
651 *p = NUL;
652 EMSG2(_("E181: Invalid attribute: %s"), cmd);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100653 goto theend;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200654 }
655 cmd = skipwhite(p);
656 }
657 if (*cmd == NUL)
658 /* Make a copy of 'shell', an autocommand may change the option. */
659 tofree = cmd = vim_strsave(p_sh);
660
661 if (eap->addr_count > 0)
662 {
663 /* Write lines from current buffer to the job. */
664 opt.jo_set |= JO_IN_IO | JO_IN_BUF | JO_IN_TOP | JO_IN_BOT;
665 opt.jo_io[PART_IN] = JIO_BUFFER;
666 opt.jo_io_buf[PART_IN] = curbuf->b_fnum;
667 opt.jo_in_top = eap->line1;
668 opt.jo_in_bot = eap->line2;
669 }
670
671 argvar[0].v_type = VAR_STRING;
672 argvar[0].vval.v_string = cmd;
673 argvar[1].v_type = VAR_UNKNOWN;
Bram Moolenaard96ff162018-02-18 22:13:29 +0100674 term_start(argvar, &opt, FALSE, eap->forceit);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200675 vim_free(tofree);
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100676
677theend:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200678 vim_free(opt.jo_eof_chars);
679}
680
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100681#if defined(FEAT_SESSION) || defined(PROTO)
682/*
683 * Write a :terminal command to the session file to restore the terminal in
684 * window "wp".
685 * Return FAIL if writing fails.
686 */
687 int
688term_write_session(FILE *fd, win_T *wp)
689{
690 term_T *term = wp->w_buffer->b_term;
691
692 /* Create the terminal and run the command. This is not without
693 * risk, but let's assume the user only creates a session when this
694 * will be OK. */
695 if (fprintf(fd, "terminal ++curwin ++cols=%d ++rows=%d ",
696 term->tl_cols, term->tl_rows) < 0)
697 return FAIL;
698 if (term->tl_command != NULL && fputs((char *)term->tl_command, fd) < 0)
699 return FAIL;
700
701 return put_eol(fd);
702}
703
704/*
705 * Return TRUE if "buf" has a terminal that should be restored.
706 */
707 int
708term_should_restore(buf_T *buf)
709{
710 term_T *term = buf->b_term;
711
712 return term != NULL && (term->tl_command == NULL
713 || STRCMP(term->tl_command, "NONE") != 0);
714}
715#endif
716
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200717/*
718 * Free the scrollback buffer for "term".
719 */
720 static void
721free_scrollback(term_T *term)
722{
723 int i;
724
725 for (i = 0; i < term->tl_scrollback.ga_len; ++i)
726 vim_free(((sb_line_T *)term->tl_scrollback.ga_data + i)->sb_cells);
727 ga_clear(&term->tl_scrollback);
728}
729
730/*
731 * Free a terminal and everything it refers to.
732 * Kills the job if there is one.
733 * Called when wiping out a buffer.
734 */
735 void
736free_terminal(buf_T *buf)
737{
738 term_T *term = buf->b_term;
739 term_T *tp;
740
741 if (term == NULL)
742 return;
743 if (first_term == term)
744 first_term = term->tl_next;
745 else
746 for (tp = first_term; tp->tl_next != NULL; tp = tp->tl_next)
747 if (tp->tl_next == term)
748 {
749 tp->tl_next = term->tl_next;
750 break;
751 }
752
753 if (term->tl_job != NULL)
754 {
755 if (term->tl_job->jv_status != JOB_ENDED
756 && term->tl_job->jv_status != JOB_FINISHED
Bram Moolenaard317b382018-02-08 22:33:31 +0100757 && term->tl_job->jv_status != JOB_FAILED)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200758 job_stop(term->tl_job, NULL, "kill");
759 job_unref(term->tl_job);
760 }
761
762 free_scrollback(term);
763
764 term_free_vterm(term);
765 vim_free(term->tl_title);
Bram Moolenaar4d8bac82018-03-09 21:33:34 +0100766#ifdef FEAT_SESSION
767 vim_free(term->tl_command);
768#endif
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +0100769 vim_free(term->tl_kill);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200770 vim_free(term->tl_status_text);
771 vim_free(term->tl_opencmd);
772 vim_free(term->tl_eof_chars);
Bram Moolenaard317b382018-02-08 22:33:31 +0100773 if (desired_cursor_color == term->tl_cursor_color)
774 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200775 vim_free(term->tl_cursor_color);
776 vim_free(term);
777 buf->b_term = NULL;
778 if (in_terminal_loop == term)
779 in_terminal_loop = NULL;
780}
781
782/*
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100783 * Get the part that is connected to the tty. Normally this is PART_IN, but
784 * when writing buffer lines to the job it can be another. This makes it
785 * possible to do "1,5term vim -".
786 */
787 static ch_part_T
788get_tty_part(term_T *term)
789{
790#ifdef UNIX
791 ch_part_T parts[3] = {PART_IN, PART_OUT, PART_ERR};
792 int i;
793
794 for (i = 0; i < 3; ++i)
795 {
796 int fd = term->tl_job->jv_channel->ch_part[parts[i]].ch_fd;
797
798 if (isatty(fd))
799 return parts[i];
800 }
801#endif
802 return PART_IN;
803}
804
805/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200806 * Write job output "msg[len]" to the vterm.
807 */
808 static void
809term_write_job_output(term_T *term, char_u *msg, size_t len)
810{
811 VTerm *vterm = term->tl_vterm;
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100812 size_t prevlen = vterm_output_get_buffer_current(vterm);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200813
Bram Moolenaar26d205d2017-11-09 17:33:11 +0100814 vterm_input_write(vterm, (char *)msg, len);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200815
Bram Moolenaarb50773c2018-01-30 22:31:19 +0100816 /* flush vterm buffer when vterm responded to control sequence */
817 if (prevlen != vterm_output_get_buffer_current(vterm))
818 {
819 char buf[KEY_BUF_LEN];
820 size_t curlen = vterm_output_read(vterm, buf, KEY_BUF_LEN);
821
822 if (curlen > 0)
823 channel_send(term->tl_job->jv_channel, get_tty_part(term),
824 (char_u *)buf, (int)curlen, NULL);
825 }
826
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200827 /* this invokes the damage callbacks */
828 vterm_screen_flush_damage(vterm_obtain_screen(vterm));
829}
830
831 static void
832update_cursor(term_T *term, int redraw)
833{
834 if (term->tl_normal_mode)
835 return;
836 setcursor();
837 if (redraw)
838 {
839 if (term->tl_buffer == curbuf && term->tl_cursor_visible)
840 cursor_on();
841 out_flush();
842#ifdef FEAT_GUI
843 if (gui.in_use)
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100844 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200845 gui_update_cursor(FALSE, FALSE);
Bram Moolenaar23c1b2b2017-12-05 21:32:33 +0100846 gui_mch_flush();
847 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200848#endif
849 }
850}
851
852/*
853 * Invoked when "msg" output from a job was received. Write it to the terminal
854 * of "buffer".
855 */
856 void
857write_to_term(buf_T *buffer, char_u *msg, channel_T *channel)
858{
859 size_t len = STRLEN(msg);
860 term_T *term = buffer->b_term;
861
862 if (term->tl_vterm == NULL)
863 {
864 ch_log(channel, "NOT writing %d bytes to terminal", (int)len);
865 return;
866 }
867 ch_log(channel, "writing %d bytes to terminal", (int)len);
868 term_write_job_output(term, msg, len);
869
870 /* In Terminal-Normal mode we are displaying the buffer, not the terminal
871 * contents, thus no screen update is needed. */
872 if (!term->tl_normal_mode)
873 {
874 /* TODO: only update once in a while. */
875 ch_log(term->tl_job->jv_channel, "updating screen");
876 if (buffer == curbuf)
877 {
878 update_screen(0);
879 update_cursor(term, TRUE);
880 }
881 else
882 redraw_after_callback(TRUE);
883 }
884}
885
886/*
887 * Send a mouse position and click to the vterm
888 */
889 static int
890term_send_mouse(VTerm *vterm, int button, int pressed)
891{
892 VTermModifier mod = VTERM_MOD_NONE;
893
894 vterm_mouse_move(vterm, mouse_row - W_WINROW(curwin),
Bram Moolenaar53f81742017-09-22 14:35:51 +0200895 mouse_col - curwin->w_wincol, mod);
Bram Moolenaar51b0f372017-11-18 18:52:04 +0100896 if (button != 0)
897 vterm_mouse_button(vterm, button, pressed, mod);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +0200898 return TRUE;
899}
900
Bram Moolenaarc48369c2018-03-11 19:30:45 +0100901static int enter_mouse_col = -1;
902static int enter_mouse_row = -1;
903
904/*
905 * Handle a mouse click, drag or release.
906 * Return TRUE when a mouse event is sent to the terminal.
907 */
908 static int
909term_mouse_click(VTerm *vterm, int key)
910{
911#if defined(FEAT_CLIPBOARD)
912 /* For modeless selection mouse drag and release events are ignored, unless
913 * they are preceded with a mouse down event */
914 static int ignore_drag_release = TRUE;
915 VTermMouseState mouse_state;
916
917 vterm_state_get_mousestate(vterm_obtain_state(vterm), &mouse_state);
918 if (mouse_state.flags == 0)
919 {
920 /* Terminal is not using the mouse, use modeless selection. */
921 switch (key)
922 {
923 case K_LEFTDRAG:
924 case K_LEFTRELEASE:
925 case K_RIGHTDRAG:
926 case K_RIGHTRELEASE:
927 /* Ignore drag and release events when the button-down wasn't
928 * seen before. */
929 if (ignore_drag_release)
930 {
931 int save_mouse_col, save_mouse_row;
932
933 if (enter_mouse_col < 0)
934 break;
935
936 /* mouse click in the window gave us focus, handle that
937 * click now */
938 save_mouse_col = mouse_col;
939 save_mouse_row = mouse_row;
940 mouse_col = enter_mouse_col;
941 mouse_row = enter_mouse_row;
942 clip_modeless(MOUSE_LEFT, TRUE, FALSE);
943 mouse_col = save_mouse_col;
944 mouse_row = save_mouse_row;
945 }
946 /* FALLTHROUGH */
947 case K_LEFTMOUSE:
948 case K_RIGHTMOUSE:
949 if (key == K_LEFTRELEASE || key == K_RIGHTRELEASE)
950 ignore_drag_release = TRUE;
951 else
952 ignore_drag_release = FALSE;
953 /* Should we call mouse_has() here? */
954 if (clip_star.available)
955 {
956 int button, is_click, is_drag;
957
958 button = get_mouse_button(KEY2TERMCAP1(key),
959 &is_click, &is_drag);
960 if (mouse_model_popup() && button == MOUSE_LEFT
961 && (mod_mask & MOD_MASK_SHIFT))
962 {
963 /* Translate shift-left to right button. */
964 button = MOUSE_RIGHT;
965 mod_mask &= ~MOD_MASK_SHIFT;
966 }
967 clip_modeless(button, is_click, is_drag);
968 }
969 break;
970
971 case K_MIDDLEMOUSE:
972 if (clip_star.available)
973 insert_reg('*', TRUE);
974 break;
975 }
976 enter_mouse_col = -1;
977 return FALSE;
978 }
979#endif
980 enter_mouse_col = -1;
981
982 switch (key)
983 {
984 case K_LEFTMOUSE:
985 case K_LEFTMOUSE_NM: term_send_mouse(vterm, 1, 1); break;
986 case K_LEFTDRAG: term_send_mouse(vterm, 1, 1); break;
987 case K_LEFTRELEASE:
988 case K_LEFTRELEASE_NM: term_send_mouse(vterm, 1, 0); break;
989 case K_MOUSEMOVE: term_send_mouse(vterm, 0, 0); break;
990 case K_MIDDLEMOUSE: term_send_mouse(vterm, 2, 1); break;
991 case K_MIDDLEDRAG: term_send_mouse(vterm, 2, 1); break;
992 case K_MIDDLERELEASE: term_send_mouse(vterm, 2, 0); break;
993 case K_RIGHTMOUSE: term_send_mouse(vterm, 3, 1); break;
994 case K_RIGHTDRAG: term_send_mouse(vterm, 3, 1); break;
995 case K_RIGHTRELEASE: term_send_mouse(vterm, 3, 0); break;
996 }
997 return TRUE;
998}
999
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001000/*
1001 * Convert typed key "c" into bytes to send to the job.
1002 * Return the number of bytes in "buf".
1003 */
1004 static int
1005term_convert_key(term_T *term, int c, char *buf)
1006{
1007 VTerm *vterm = term->tl_vterm;
1008 VTermKey key = VTERM_KEY_NONE;
1009 VTermModifier mod = VTERM_MOD_NONE;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001010 int other = FALSE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001011
1012 switch (c)
1013 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001014 /* don't use VTERM_KEY_ENTER, it may do an unwanted conversion */
1015
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001016 /* don't use VTERM_KEY_BACKSPACE, it always
1017 * becomes 0x7f DEL */
1018 case K_BS: c = term_backspace_char; break;
1019
1020 case ESC: key = VTERM_KEY_ESCAPE; break;
1021 case K_DEL: key = VTERM_KEY_DEL; break;
1022 case K_DOWN: key = VTERM_KEY_DOWN; break;
1023 case K_S_DOWN: mod = VTERM_MOD_SHIFT;
1024 key = VTERM_KEY_DOWN; break;
1025 case K_END: key = VTERM_KEY_END; break;
1026 case K_S_END: mod = VTERM_MOD_SHIFT;
1027 key = VTERM_KEY_END; break;
1028 case K_C_END: mod = VTERM_MOD_CTRL;
1029 key = VTERM_KEY_END; break;
1030 case K_F10: key = VTERM_KEY_FUNCTION(10); break;
1031 case K_F11: key = VTERM_KEY_FUNCTION(11); break;
1032 case K_F12: key = VTERM_KEY_FUNCTION(12); break;
1033 case K_F1: key = VTERM_KEY_FUNCTION(1); break;
1034 case K_F2: key = VTERM_KEY_FUNCTION(2); break;
1035 case K_F3: key = VTERM_KEY_FUNCTION(3); break;
1036 case K_F4: key = VTERM_KEY_FUNCTION(4); break;
1037 case K_F5: key = VTERM_KEY_FUNCTION(5); break;
1038 case K_F6: key = VTERM_KEY_FUNCTION(6); break;
1039 case K_F7: key = VTERM_KEY_FUNCTION(7); break;
1040 case K_F8: key = VTERM_KEY_FUNCTION(8); break;
1041 case K_F9: key = VTERM_KEY_FUNCTION(9); break;
1042 case K_HOME: key = VTERM_KEY_HOME; break;
1043 case K_S_HOME: mod = VTERM_MOD_SHIFT;
1044 key = VTERM_KEY_HOME; break;
1045 case K_C_HOME: mod = VTERM_MOD_CTRL;
1046 key = VTERM_KEY_HOME; break;
1047 case K_INS: key = VTERM_KEY_INS; break;
1048 case K_K0: key = VTERM_KEY_KP_0; break;
1049 case K_K1: key = VTERM_KEY_KP_1; break;
1050 case K_K2: key = VTERM_KEY_KP_2; break;
1051 case K_K3: key = VTERM_KEY_KP_3; break;
1052 case K_K4: key = VTERM_KEY_KP_4; break;
1053 case K_K5: key = VTERM_KEY_KP_5; break;
1054 case K_K6: key = VTERM_KEY_KP_6; break;
1055 case K_K7: key = VTERM_KEY_KP_7; break;
1056 case K_K8: key = VTERM_KEY_KP_8; break;
1057 case K_K9: key = VTERM_KEY_KP_9; break;
1058 case K_KDEL: key = VTERM_KEY_DEL; break; /* TODO */
1059 case K_KDIVIDE: key = VTERM_KEY_KP_DIVIDE; break;
1060 case K_KEND: key = VTERM_KEY_KP_1; break; /* TODO */
1061 case K_KENTER: key = VTERM_KEY_KP_ENTER; break;
1062 case K_KHOME: key = VTERM_KEY_KP_7; break; /* TODO */
1063 case K_KINS: key = VTERM_KEY_KP_0; break; /* TODO */
1064 case K_KMINUS: key = VTERM_KEY_KP_MINUS; break;
1065 case K_KMULTIPLY: key = VTERM_KEY_KP_MULT; break;
1066 case K_KPAGEDOWN: key = VTERM_KEY_KP_3; break; /* TODO */
1067 case K_KPAGEUP: key = VTERM_KEY_KP_9; break; /* TODO */
1068 case K_KPLUS: key = VTERM_KEY_KP_PLUS; break;
1069 case K_KPOINT: key = VTERM_KEY_KP_PERIOD; break;
1070 case K_LEFT: key = VTERM_KEY_LEFT; break;
1071 case K_S_LEFT: mod = VTERM_MOD_SHIFT;
1072 key = VTERM_KEY_LEFT; break;
1073 case K_C_LEFT: mod = VTERM_MOD_CTRL;
1074 key = VTERM_KEY_LEFT; break;
1075 case K_PAGEDOWN: key = VTERM_KEY_PAGEDOWN; break;
1076 case K_PAGEUP: key = VTERM_KEY_PAGEUP; break;
1077 case K_RIGHT: key = VTERM_KEY_RIGHT; break;
1078 case K_S_RIGHT: mod = VTERM_MOD_SHIFT;
1079 key = VTERM_KEY_RIGHT; break;
1080 case K_C_RIGHT: mod = VTERM_MOD_CTRL;
1081 key = VTERM_KEY_RIGHT; break;
1082 case K_UP: key = VTERM_KEY_UP; break;
1083 case K_S_UP: mod = VTERM_MOD_SHIFT;
1084 key = VTERM_KEY_UP; break;
1085 case TAB: key = VTERM_KEY_TAB; break;
Bram Moolenaar73cddfd2018-02-16 20:01:04 +01001086 case K_S_TAB: mod = VTERM_MOD_SHIFT;
1087 key = VTERM_KEY_TAB; break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001088
Bram Moolenaara42ad572017-11-16 13:08:04 +01001089 case K_MOUSEUP: other = term_send_mouse(vterm, 5, 1); break;
1090 case K_MOUSEDOWN: other = term_send_mouse(vterm, 4, 1); break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001091 case K_MOUSELEFT: /* TODO */ return 0;
1092 case K_MOUSERIGHT: /* TODO */ return 0;
1093
1094 case K_LEFTMOUSE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001095 case K_LEFTMOUSE_NM:
1096 case K_LEFTDRAG:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001097 case K_LEFTRELEASE:
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001098 case K_LEFTRELEASE_NM:
1099 case K_MOUSEMOVE:
1100 case K_MIDDLEMOUSE:
1101 case K_MIDDLEDRAG:
1102 case K_MIDDLERELEASE:
1103 case K_RIGHTMOUSE:
1104 case K_RIGHTDRAG:
1105 case K_RIGHTRELEASE: if (!term_mouse_click(vterm, c))
1106 return 0;
1107 other = TRUE;
1108 break;
1109
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001110 case K_X1MOUSE: /* TODO */ return 0;
1111 case K_X1DRAG: /* TODO */ return 0;
1112 case K_X1RELEASE: /* TODO */ return 0;
1113 case K_X2MOUSE: /* TODO */ return 0;
1114 case K_X2DRAG: /* TODO */ return 0;
1115 case K_X2RELEASE: /* TODO */ return 0;
1116
1117 case K_IGNORE: return 0;
1118 case K_NOP: return 0;
1119 case K_UNDO: return 0;
1120 case K_HELP: return 0;
1121 case K_XF1: key = VTERM_KEY_FUNCTION(1); break;
1122 case K_XF2: key = VTERM_KEY_FUNCTION(2); break;
1123 case K_XF3: key = VTERM_KEY_FUNCTION(3); break;
1124 case K_XF4: key = VTERM_KEY_FUNCTION(4); break;
1125 case K_SELECT: return 0;
1126#ifdef FEAT_GUI
1127 case K_VER_SCROLLBAR: return 0;
1128 case K_HOR_SCROLLBAR: return 0;
1129#endif
1130#ifdef FEAT_GUI_TABLINE
1131 case K_TABLINE: return 0;
1132 case K_TABMENU: return 0;
1133#endif
1134#ifdef FEAT_NETBEANS_INTG
1135 case K_F21: key = VTERM_KEY_FUNCTION(21); break;
1136#endif
1137#ifdef FEAT_DND
1138 case K_DROP: return 0;
1139#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001140 case K_CURSORHOLD: return 0;
Bram Moolenaara42ad572017-11-16 13:08:04 +01001141 case K_PS: vterm_keyboard_start_paste(vterm);
1142 other = TRUE;
1143 break;
1144 case K_PE: vterm_keyboard_end_paste(vterm);
1145 other = TRUE;
1146 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001147 }
1148
1149 /*
1150 * Convert special keys to vterm keys:
1151 * - Write keys to vterm: vterm_keyboard_key()
1152 * - Write output to channel.
1153 * TODO: use mod_mask
1154 */
1155 if (key != VTERM_KEY_NONE)
1156 /* Special key, let vterm convert it. */
1157 vterm_keyboard_key(vterm, key, mod);
Bram Moolenaara42ad572017-11-16 13:08:04 +01001158 else if (!other)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001159 /* Normal character, let vterm convert it. */
1160 vterm_keyboard_unichar(vterm, c, mod);
1161
1162 /* Read back the converted escape sequence. */
1163 return (int)vterm_output_read(vterm, buf, KEY_BUF_LEN);
1164}
1165
1166/*
1167 * Return TRUE if the job for "term" is still running.
1168 */
1169 int
1170term_job_running(term_T *term)
1171{
1172 /* Also consider the job finished when the channel is closed, to avoid a
1173 * race condition when updating the title. */
1174 return term != NULL
1175 && term->tl_job != NULL
1176 && channel_is_open(term->tl_job->jv_channel)
1177 && (term->tl_job->jv_status == JOB_STARTED
1178 || term->tl_job->jv_channel->ch_keep_open);
1179}
1180
1181/*
1182 * Return TRUE if "term" has an active channel and used ":term NONE".
1183 */
1184 int
1185term_none_open(term_T *term)
1186{
1187 /* Also consider the job finished when the channel is closed, to avoid a
1188 * race condition when updating the title. */
1189 return term != NULL
1190 && term->tl_job != NULL
1191 && channel_is_open(term->tl_job->jv_channel)
1192 && term->tl_job->jv_channel->ch_keep_open;
1193}
1194
1195/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01001196 * Used when exiting: kill the job in "buf" if so desired.
1197 * Return OK when the job finished.
1198 * Return FAIL when the job is still running.
1199 */
1200 int
1201term_try_stop_job(buf_T *buf)
1202{
1203 int count;
1204 char *how = (char *)buf->b_term->tl_kill;
1205
1206#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1207 if ((how == NULL || *how == NUL) && (p_confirm || cmdmod.confirm))
1208 {
1209 char_u buff[DIALOG_MSG_SIZE];
1210 int ret;
1211
1212 dialog_msg(buff, _("Kill job in \"%s\"?"), buf->b_fname);
1213 ret = vim_dialog_yesnocancel(VIM_QUESTION, NULL, buff, 1);
1214 if (ret == VIM_YES)
1215 how = "kill";
1216 else if (ret == VIM_CANCEL)
1217 return FAIL;
1218 }
1219#endif
1220 if (how == NULL || *how == NUL)
1221 return FAIL;
1222
1223 job_stop(buf->b_term->tl_job, NULL, how);
1224
1225 /* wait for up to a second for the job to die */
1226 for (count = 0; count < 100; ++count)
1227 {
1228 /* buffer, terminal and job may be cleaned up while waiting */
1229 if (!buf_valid(buf)
1230 || buf->b_term == NULL
1231 || buf->b_term->tl_job == NULL)
1232 return OK;
1233
1234 /* call job_status() to update jv_status */
1235 job_status(buf->b_term->tl_job);
1236 if (buf->b_term->tl_job->jv_status >= JOB_ENDED)
1237 return OK;
1238 ui_delay(10L, FALSE);
1239 mch_check_messages();
1240 parse_queued_messages();
1241 }
1242 return FAIL;
1243}
1244
1245/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001246 * Add the last line of the scrollback buffer to the buffer in the window.
1247 */
1248 static void
1249add_scrollback_line_to_buffer(term_T *term, char_u *text, int len)
1250{
1251 buf_T *buf = term->tl_buffer;
1252 int empty = (buf->b_ml.ml_flags & ML_EMPTY);
1253 linenr_T lnum = buf->b_ml.ml_line_count;
1254
1255#ifdef WIN3264
1256 if (!enc_utf8 && enc_codepage > 0)
1257 {
1258 WCHAR *ret = NULL;
1259 int length = 0;
1260
1261 MultiByteToWideChar_alloc(CP_UTF8, 0, (char*)text, len + 1,
1262 &ret, &length);
1263 if (ret != NULL)
1264 {
1265 WideCharToMultiByte_alloc(enc_codepage, 0,
1266 ret, length, (char **)&text, &len, 0, 0);
1267 vim_free(ret);
1268 ml_append_buf(term->tl_buffer, lnum, text, len, FALSE);
1269 vim_free(text);
1270 }
1271 }
1272 else
1273#endif
1274 ml_append_buf(term->tl_buffer, lnum, text, len + 1, FALSE);
1275 if (empty)
1276 {
1277 /* Delete the empty line that was in the empty buffer. */
1278 curbuf = buf;
1279 ml_delete(1, FALSE);
1280 curbuf = curwin->w_buffer;
1281 }
1282}
1283
1284 static void
1285cell2cellattr(const VTermScreenCell *cell, cellattr_T *attr)
1286{
1287 attr->width = cell->width;
1288 attr->attrs = cell->attrs;
1289 attr->fg = cell->fg;
1290 attr->bg = cell->bg;
1291}
1292
1293 static int
1294equal_celattr(cellattr_T *a, cellattr_T *b)
1295{
1296 /* Comparing the colors should be sufficient. */
1297 return a->fg.red == b->fg.red
1298 && a->fg.green == b->fg.green
1299 && a->fg.blue == b->fg.blue
1300 && a->bg.red == b->bg.red
1301 && a->bg.green == b->bg.green
1302 && a->bg.blue == b->bg.blue;
1303}
1304
Bram Moolenaard96ff162018-02-18 22:13:29 +01001305/*
1306 * Add an empty scrollback line to "term". When "lnum" is not zero, add the
1307 * line at this position. Otherwise at the end.
1308 */
1309 static int
1310add_empty_scrollback(term_T *term, cellattr_T *fill_attr, int lnum)
1311{
1312 if (ga_grow(&term->tl_scrollback, 1) == OK)
1313 {
1314 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1315 + term->tl_scrollback.ga_len;
1316
1317 if (lnum > 0)
1318 {
1319 int i;
1320
1321 for (i = 0; i < term->tl_scrollback.ga_len - lnum; ++i)
1322 {
1323 *line = *(line - 1);
1324 --line;
1325 }
1326 }
1327 line->sb_cols = 0;
1328 line->sb_cells = NULL;
1329 line->sb_fill_attr = *fill_attr;
1330 ++term->tl_scrollback.ga_len;
1331 return OK;
1332 }
1333 return FALSE;
1334}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001335
1336/*
1337 * Add the current lines of the terminal to scrollback and to the buffer.
1338 * Called after the job has ended and when switching to Terminal-Normal mode.
1339 */
1340 static void
1341move_terminal_to_buffer(term_T *term)
1342{
1343 win_T *wp;
1344 int len;
1345 int lines_skipped = 0;
1346 VTermPos pos;
1347 VTermScreenCell cell;
1348 cellattr_T fill_attr, new_fill_attr;
1349 cellattr_T *p;
1350 VTermScreen *screen;
1351
1352 if (term->tl_vterm == NULL)
1353 return;
1354 screen = vterm_obtain_screen(term->tl_vterm);
1355 fill_attr = new_fill_attr = term->tl_default_color;
1356
1357 for (pos.row = 0; pos.row < term->tl_rows; ++pos.row)
1358 {
1359 len = 0;
1360 for (pos.col = 0; pos.col < term->tl_cols; ++pos.col)
1361 if (vterm_screen_get_cell(screen, pos, &cell) != 0
1362 && cell.chars[0] != NUL)
1363 {
1364 len = pos.col + 1;
1365 new_fill_attr = term->tl_default_color;
1366 }
1367 else
1368 /* Assume the last attr is the filler attr. */
1369 cell2cellattr(&cell, &new_fill_attr);
1370
1371 if (len == 0 && equal_celattr(&new_fill_attr, &fill_attr))
1372 ++lines_skipped;
1373 else
1374 {
1375 while (lines_skipped > 0)
1376 {
1377 /* Line was skipped, add an empty line. */
1378 --lines_skipped;
Bram Moolenaard96ff162018-02-18 22:13:29 +01001379 if (add_empty_scrollback(term, &fill_attr, 0) == OK)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001380 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001381 }
1382
1383 if (len == 0)
1384 p = NULL;
1385 else
1386 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
1387 if ((p != NULL || len == 0)
1388 && ga_grow(&term->tl_scrollback, 1) == OK)
1389 {
1390 garray_T ga;
1391 int width;
1392 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
1393 + term->tl_scrollback.ga_len;
1394
1395 ga_init2(&ga, 1, 100);
1396 for (pos.col = 0; pos.col < len; pos.col += width)
1397 {
1398 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
1399 {
1400 width = 1;
1401 vim_memset(p + pos.col, 0, sizeof(cellattr_T));
1402 if (ga_grow(&ga, 1) == OK)
1403 ga.ga_len += utf_char2bytes(' ',
1404 (char_u *)ga.ga_data + ga.ga_len);
1405 }
1406 else
1407 {
1408 width = cell.width;
1409
1410 cell2cellattr(&cell, &p[pos.col]);
1411
1412 if (ga_grow(&ga, MB_MAXBYTES) == OK)
1413 {
1414 int i;
1415 int c;
1416
1417 for (i = 0; (c = cell.chars[i]) > 0 || i == 0; ++i)
1418 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
1419 (char_u *)ga.ga_data + ga.ga_len);
1420 }
1421 }
1422 }
1423 line->sb_cols = len;
1424 line->sb_cells = p;
1425 line->sb_fill_attr = new_fill_attr;
1426 fill_attr = new_fill_attr;
1427 ++term->tl_scrollback.ga_len;
1428
1429 if (ga_grow(&ga, 1) == FAIL)
1430 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
1431 else
1432 {
1433 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
1434 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
1435 }
1436 ga_clear(&ga);
1437 }
1438 else
1439 vim_free(p);
1440 }
1441 }
1442
1443 /* Obtain the current background color. */
1444 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
1445 &term->tl_default_color.fg, &term->tl_default_color.bg);
1446
1447 FOR_ALL_WINDOWS(wp)
1448 {
1449 if (wp->w_buffer == term->tl_buffer)
1450 {
1451 wp->w_cursor.lnum = term->tl_buffer->b_ml.ml_line_count;
1452 wp->w_cursor.col = 0;
1453 wp->w_valid = 0;
1454 if (wp->w_cursor.lnum >= wp->w_height)
1455 {
1456 linenr_T min_topline = wp->w_cursor.lnum - wp->w_height + 1;
1457
1458 if (wp->w_topline < min_topline)
1459 wp->w_topline = min_topline;
1460 }
1461 redraw_win_later(wp, NOT_VALID);
1462 }
1463 }
1464}
1465
1466 static void
1467set_terminal_mode(term_T *term, int normal_mode)
1468{
1469 term->tl_normal_mode = normal_mode;
Bram Moolenaard23a8232018-02-10 18:45:26 +01001470 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001471 if (term->tl_buffer == curbuf)
1472 maketitle();
1473}
1474
1475/*
1476 * Called after the job if finished and Terminal mode is not active:
1477 * Move the vterm contents into the scrollback buffer and free the vterm.
1478 */
1479 static void
1480cleanup_vterm(term_T *term)
1481{
1482 if (term->tl_finish != 'c')
1483 move_terminal_to_buffer(term);
1484 term_free_vterm(term);
1485 set_terminal_mode(term, FALSE);
1486}
1487
1488/*
1489 * Switch from Terminal-Job mode to Terminal-Normal mode.
1490 * Suspends updating the terminal window.
1491 */
1492 static void
1493term_enter_normal_mode(void)
1494{
1495 term_T *term = curbuf->b_term;
1496
1497 /* Append the current terminal contents to the buffer. */
1498 move_terminal_to_buffer(term);
1499
1500 set_terminal_mode(term, TRUE);
1501
1502 /* Move the window cursor to the position of the cursor in the
1503 * terminal. */
1504 curwin->w_cursor.lnum = term->tl_scrollback_scrolled
1505 + term->tl_cursor_pos.row + 1;
1506 check_cursor();
1507 coladvance(term->tl_cursor_pos.col);
1508
1509 /* Display the same lines as in the terminal. */
1510 curwin->w_topline = term->tl_scrollback_scrolled + 1;
1511}
1512
1513/*
1514 * Returns TRUE if the current window contains a terminal and we are in
1515 * Terminal-Normal mode.
1516 */
1517 int
1518term_in_normal_mode(void)
1519{
1520 term_T *term = curbuf->b_term;
1521
1522 return term != NULL && term->tl_normal_mode;
1523}
1524
1525/*
1526 * Switch from Terminal-Normal mode to Terminal-Job mode.
1527 * Restores updating the terminal window.
1528 */
1529 void
1530term_enter_job_mode()
1531{
1532 term_T *term = curbuf->b_term;
1533 sb_line_T *line;
1534 garray_T *gap;
1535
1536 /* Remove the terminal contents from the scrollback and the buffer. */
1537 gap = &term->tl_scrollback;
1538 while (curbuf->b_ml.ml_line_count > term->tl_scrollback_scrolled
1539 && gap->ga_len > 0)
1540 {
1541 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
1542 line = (sb_line_T *)gap->ga_data + gap->ga_len - 1;
1543 vim_free(line->sb_cells);
1544 --gap->ga_len;
1545 }
1546 check_cursor();
1547
1548 set_terminal_mode(term, FALSE);
1549
1550 if (term->tl_channel_closed)
1551 cleanup_vterm(term);
1552 redraw_buf_and_status_later(curbuf, NOT_VALID);
1553}
1554
1555/*
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001556 * Get a key from the user with terminal mode mappings.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001557 * Note: while waiting a terminal may be closed and freed if the channel is
1558 * closed and ++close was used.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001559 */
1560 static int
1561term_vgetc()
1562{
1563 int c;
1564 int save_State = State;
1565
1566 State = TERMINAL;
1567 got_int = FALSE;
1568#ifdef WIN3264
1569 ctrl_break_was_pressed = FALSE;
1570#endif
1571 c = vgetc();
1572 got_int = FALSE;
1573 State = save_State;
1574 return c;
1575}
1576
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001577static int mouse_was_outside = FALSE;
1578
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001579/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001580 * Send keys to terminal.
1581 * Return FAIL when the key needs to be handled in Normal mode.
1582 * Return OK when the key was dropped or sent to the terminal.
1583 */
1584 int
1585send_keys_to_term(term_T *term, int c, int typed)
1586{
1587 char msg[KEY_BUF_LEN];
1588 size_t len;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001589 int dragging_outside = FALSE;
1590
1591 /* Catch keys that need to be handled as in Normal mode. */
1592 switch (c)
1593 {
1594 case NUL:
1595 case K_ZERO:
1596 if (typed)
1597 stuffcharReadbuff(c);
1598 return FAIL;
1599
1600 case K_IGNORE:
1601 return FAIL;
1602
1603 case K_LEFTDRAG:
1604 case K_MIDDLEDRAG:
1605 case K_RIGHTDRAG:
1606 case K_X1DRAG:
1607 case K_X2DRAG:
1608 dragging_outside = mouse_was_outside;
1609 /* FALLTHROUGH */
1610 case K_LEFTMOUSE:
1611 case K_LEFTMOUSE_NM:
1612 case K_LEFTRELEASE:
1613 case K_LEFTRELEASE_NM:
Bram Moolenaar51b0f372017-11-18 18:52:04 +01001614 case K_MOUSEMOVE:
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001615 case K_MIDDLEMOUSE:
1616 case K_MIDDLERELEASE:
1617 case K_RIGHTMOUSE:
1618 case K_RIGHTRELEASE:
1619 case K_X1MOUSE:
1620 case K_X1RELEASE:
1621 case K_X2MOUSE:
1622 case K_X2RELEASE:
1623
1624 case K_MOUSEUP:
1625 case K_MOUSEDOWN:
1626 case K_MOUSELEFT:
1627 case K_MOUSERIGHT:
1628 if (mouse_row < W_WINROW(curwin)
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001629 || mouse_row >= (W_WINROW(curwin) + curwin->w_height)
Bram Moolenaar53f81742017-09-22 14:35:51 +02001630 || mouse_col < curwin->w_wincol
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001631 || mouse_col >= W_ENDCOL(curwin)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001632 || dragging_outside)
1633 {
Bram Moolenaarce6179c2017-12-05 13:06:16 +01001634 /* click or scroll outside the current window or on status line
1635 * or vertical separator */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001636 if (typed)
1637 {
1638 stuffcharReadbuff(c);
1639 mouse_was_outside = TRUE;
1640 }
1641 return FAIL;
1642 }
1643 }
1644 if (typed)
1645 mouse_was_outside = FALSE;
1646
1647 /* Convert the typed key to a sequence of bytes for the job. */
1648 len = term_convert_key(term, c, msg);
1649 if (len > 0)
1650 /* TODO: if FAIL is returned, stop? */
1651 channel_send(term->tl_job->jv_channel, get_tty_part(term),
1652 (char_u *)msg, (int)len, NULL);
1653
1654 return OK;
1655}
1656
1657 static void
1658position_cursor(win_T *wp, VTermPos *pos)
1659{
1660 wp->w_wrow = MIN(pos->row, MAX(0, wp->w_height - 1));
1661 wp->w_wcol = MIN(pos->col, MAX(0, wp->w_width - 1));
1662 wp->w_valid |= (VALID_WCOL|VALID_WROW);
1663}
1664
1665/*
1666 * Handle CTRL-W "": send register contents to the job.
1667 */
1668 static void
1669term_paste_register(int prev_c UNUSED)
1670{
1671 int c;
1672 list_T *l;
1673 listitem_T *item;
1674 long reglen = 0;
1675 int type;
1676
1677#ifdef FEAT_CMDL_INFO
1678 if (add_to_showcmd(prev_c))
1679 if (add_to_showcmd('"'))
1680 out_flush();
1681#endif
1682 c = term_vgetc();
1683#ifdef FEAT_CMDL_INFO
1684 clear_showcmd();
1685#endif
1686 if (!term_use_loop())
1687 /* job finished while waiting for a character */
1688 return;
1689
1690 /* CTRL-W "= prompt for expression to evaluate. */
1691 if (c == '=' && get_expr_register() != '=')
1692 return;
1693 if (!term_use_loop())
1694 /* job finished while waiting for a character */
1695 return;
1696
1697 l = (list_T *)get_reg_contents(c, GREG_LIST);
1698 if (l != NULL)
1699 {
1700 type = get_reg_type(c, &reglen);
1701 for (item = l->lv_first; item != NULL; item = item->li_next)
1702 {
1703 char_u *s = get_tv_string(&item->li_tv);
1704#ifdef WIN3264
1705 char_u *tmp = s;
1706
1707 if (!enc_utf8 && enc_codepage > 0)
1708 {
1709 WCHAR *ret = NULL;
1710 int length = 0;
1711
1712 MultiByteToWideChar_alloc(enc_codepage, 0, (char *)s,
1713 (int)STRLEN(s), &ret, &length);
1714 if (ret != NULL)
1715 {
1716 WideCharToMultiByte_alloc(CP_UTF8, 0,
1717 ret, length, (char **)&s, &length, 0, 0);
1718 vim_free(ret);
1719 }
1720 }
1721#endif
1722 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1723 s, (int)STRLEN(s), NULL);
1724#ifdef WIN3264
1725 if (tmp != s)
1726 vim_free(s);
1727#endif
1728
1729 if (item->li_next != NULL || type == MLINE)
1730 channel_send(curbuf->b_term->tl_job->jv_channel, PART_IN,
1731 (char_u *)"\r", 1, NULL);
1732 }
1733 list_free(l);
1734 }
1735}
1736
1737#if defined(FEAT_GUI) || defined(PROTO)
1738/*
1739 * Return TRUE when the cursor of the terminal should be displayed.
1740 */
1741 int
1742terminal_is_active()
1743{
1744 return in_terminal_loop != NULL;
1745}
1746
1747 cursorentry_T *
1748term_get_cursor_shape(guicolor_T *fg, guicolor_T *bg)
1749{
1750 term_T *term = in_terminal_loop;
1751 static cursorentry_T entry;
1752
1753 vim_memset(&entry, 0, sizeof(entry));
1754 entry.shape = entry.mshape =
1755 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_UNDERLINE ? SHAPE_HOR :
1756 term->tl_cursor_shape == VTERM_PROP_CURSORSHAPE_BAR_LEFT ? SHAPE_VER :
1757 SHAPE_BLOCK;
1758 entry.percentage = 20;
1759 if (term->tl_cursor_blink)
1760 {
1761 entry.blinkwait = 700;
1762 entry.blinkon = 400;
1763 entry.blinkoff = 250;
1764 }
1765 *fg = gui.back_pixel;
1766 if (term->tl_cursor_color == NULL)
1767 *bg = gui.norm_pixel;
1768 else
1769 *bg = color_name2handle(term->tl_cursor_color);
1770 entry.name = "n";
1771 entry.used_for = SHAPE_CURSOR;
1772
1773 return &entry;
1774}
1775#endif
1776
Bram Moolenaard317b382018-02-08 22:33:31 +01001777 static void
1778may_output_cursor_props(void)
1779{
1780 if (STRCMP(last_set_cursor_color, desired_cursor_color) != 0
1781 || last_set_cursor_shape != desired_cursor_shape
1782 || last_set_cursor_blink != desired_cursor_blink)
1783 {
1784 last_set_cursor_color = desired_cursor_color;
1785 last_set_cursor_shape = desired_cursor_shape;
1786 last_set_cursor_blink = desired_cursor_blink;
1787 term_cursor_color(desired_cursor_color);
1788 if (desired_cursor_shape == -1 || desired_cursor_blink == -1)
1789 /* this will restore the initial cursor style, if possible */
1790 ui_cursor_shape_forced(TRUE);
1791 else
1792 term_cursor_shape(desired_cursor_shape, desired_cursor_blink);
1793 }
1794}
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001795
Bram Moolenaard317b382018-02-08 22:33:31 +01001796/*
1797 * Set the cursor color and shape, if not last set to these.
1798 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001799 static void
1800may_set_cursor_props(term_T *term)
1801{
1802#ifdef FEAT_GUI
1803 /* For the GUI the cursor properties are obtained with
1804 * term_get_cursor_shape(). */
1805 if (gui.in_use)
1806 return;
1807#endif
1808 if (in_terminal_loop == term)
1809 {
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001810 if (term->tl_cursor_color != NULL)
Bram Moolenaard317b382018-02-08 22:33:31 +01001811 desired_cursor_color = term->tl_cursor_color;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001812 else
Bram Moolenaard317b382018-02-08 22:33:31 +01001813 desired_cursor_color = (char_u *)"";
1814 desired_cursor_shape = term->tl_cursor_shape;
1815 desired_cursor_blink = term->tl_cursor_blink;
1816 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001817 }
1818}
1819
Bram Moolenaard317b382018-02-08 22:33:31 +01001820/*
1821 * Reset the desired cursor properties and restore them when needed.
1822 */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001823 static void
Bram Moolenaard317b382018-02-08 22:33:31 +01001824prepare_restore_cursor_props(void)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001825{
1826#ifdef FEAT_GUI
1827 if (gui.in_use)
1828 return;
1829#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001830 desired_cursor_color = (char_u *)"";
1831 desired_cursor_shape = -1;
1832 desired_cursor_blink = -1;
1833 may_output_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001834}
1835
1836/*
Bram Moolenaarc48369c2018-03-11 19:30:45 +01001837 * Called when entering a window with the mouse. If this is a terminal window
1838 * we may want to change state.
1839 */
1840 void
1841term_win_entered()
1842{
1843 term_T *term = curbuf->b_term;
1844
1845 if (term != NULL)
1846 {
1847 if (term_use_loop())
1848 {
1849 reset_VIsual_and_resel();
1850 if (State & INSERT)
1851 stop_insert_mode = TRUE;
1852 }
1853 mouse_was_outside = FALSE;
1854 enter_mouse_col = mouse_col;
1855 enter_mouse_row = mouse_row;
1856 }
1857}
1858
1859/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001860 * Returns TRUE if the current window contains a terminal and we are sending
1861 * keys to the job.
1862 */
1863 int
1864term_use_loop(void)
1865{
1866 term_T *term = curbuf->b_term;
1867
1868 return term != NULL
1869 && !term->tl_normal_mode
1870 && term->tl_vterm != NULL
1871 && term_job_running(term);
1872}
1873
1874/*
1875 * Wait for input and send it to the job.
1876 * When "blocking" is TRUE wait for a character to be typed. Otherwise return
1877 * when there is no more typahead.
1878 * Return when the start of a CTRL-W command is typed or anything else that
1879 * should be handled as a Normal mode command.
1880 * Returns OK if a typed character is to be handled in Normal mode, FAIL if
1881 * the terminal was closed.
1882 */
1883 int
1884terminal_loop(int blocking)
1885{
1886 int c;
1887 int termkey = 0;
1888 int ret;
Bram Moolenaar12326242017-11-04 20:12:14 +01001889#ifdef UNIX
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001890 int tty_fd = curbuf->b_term->tl_job->jv_channel
1891 ->ch_part[get_tty_part(curbuf->b_term)].ch_fd;
Bram Moolenaar12326242017-11-04 20:12:14 +01001892#endif
Bram Moolenaard317b382018-02-08 22:33:31 +01001893 int restore_cursor;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001894
1895 /* Remember the terminal we are sending keys to. However, the terminal
1896 * might be closed while waiting for a character, e.g. typing "exit" in a
1897 * shell and ++close was used. Therefore use curbuf->b_term instead of a
1898 * stored reference. */
1899 in_terminal_loop = curbuf->b_term;
1900
1901 if (*curwin->w_p_tk != NUL)
1902 termkey = string_to_key(curwin->w_p_tk, TRUE);
1903 position_cursor(curwin, &curbuf->b_term->tl_cursor_pos);
1904 may_set_cursor_props(curbuf->b_term);
1905
Bram Moolenaarc8bcfe72018-02-27 16:29:28 +01001906 while (blocking || vpeekc_nomap() != NUL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001907 {
1908 /* TODO: skip screen update when handling a sequence of keys. */
1909 /* Repeat redrawing in case a message is received while redrawing. */
1910 while (must_redraw != 0)
1911 if (update_screen(0) == FAIL)
1912 break;
1913 update_cursor(curbuf->b_term, FALSE);
Bram Moolenaard317b382018-02-08 22:33:31 +01001914 restore_cursor = TRUE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001915
1916 c = term_vgetc();
1917 if (!term_use_loop())
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001918 {
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001919 /* Job finished while waiting for a character. Push back the
1920 * received character. */
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001921 if (c != K_IGNORE)
1922 vungetc(c);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001923 break;
Bram Moolenaara3f7e582017-11-09 13:21:58 +01001924 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001925 if (c == K_IGNORE)
1926 continue;
1927
Bram Moolenaar26d205d2017-11-09 17:33:11 +01001928#ifdef UNIX
1929 /*
1930 * The shell or another program may change the tty settings. Getting
1931 * them for every typed character is a bit of overhead, but it's needed
1932 * for the first character typed, e.g. when Vim starts in a shell.
1933 */
1934 if (isatty(tty_fd))
1935 {
1936 ttyinfo_T info;
1937
1938 /* Get the current backspace character of the pty. */
1939 if (get_tty_info(tty_fd, &info) == OK)
1940 term_backspace_char = info.backspace;
1941 }
1942#endif
1943
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02001944#ifdef WIN3264
1945 /* On Windows winpty handles CTRL-C, don't send a CTRL_C_EVENT.
1946 * Use CTRL-BREAK to kill the job. */
1947 if (ctrl_break_was_pressed)
1948 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1949#endif
1950 /* Was either CTRL-W (termkey) or CTRL-\ pressed? */
1951 if (c == (termkey == 0 ? Ctrl_W : termkey) || c == Ctrl_BSL)
1952 {
1953 int prev_c = c;
1954
1955#ifdef FEAT_CMDL_INFO
1956 if (add_to_showcmd(c))
1957 out_flush();
1958#endif
1959 c = term_vgetc();
1960#ifdef FEAT_CMDL_INFO
1961 clear_showcmd();
1962#endif
1963 if (!term_use_loop())
1964 /* job finished while waiting for a character */
1965 break;
1966
1967 if (prev_c == Ctrl_BSL)
1968 {
1969 if (c == Ctrl_N)
1970 {
1971 /* CTRL-\ CTRL-N : go to Terminal-Normal mode. */
1972 term_enter_normal_mode();
1973 ret = FAIL;
1974 goto theend;
1975 }
1976 /* Send both keys to the terminal. */
1977 send_keys_to_term(curbuf->b_term, prev_c, TRUE);
1978 }
1979 else if (c == Ctrl_C)
1980 {
1981 /* "CTRL-W CTRL-C" or 'termkey' CTRL-C: end the job */
1982 mch_signal_job(curbuf->b_term->tl_job, (char_u *)"kill");
1983 }
1984 else if (termkey == 0 && c == '.')
1985 {
1986 /* "CTRL-W .": send CTRL-W to the job */
1987 c = Ctrl_W;
1988 }
1989 else if (c == 'N')
1990 {
1991 /* CTRL-W N : go to Terminal-Normal mode. */
1992 term_enter_normal_mode();
1993 ret = FAIL;
1994 goto theend;
1995 }
1996 else if (c == '"')
1997 {
1998 term_paste_register(prev_c);
1999 continue;
2000 }
2001 else if (termkey == 0 || c != termkey)
2002 {
2003 stuffcharReadbuff(Ctrl_W);
2004 stuffcharReadbuff(c);
2005 ret = OK;
2006 goto theend;
2007 }
2008 }
2009# ifdef WIN3264
2010 if (!enc_utf8 && has_mbyte && c >= 0x80)
2011 {
2012 WCHAR wc;
2013 char_u mb[3];
2014
2015 mb[0] = (unsigned)c >> 8;
2016 mb[1] = c;
2017 if (MultiByteToWideChar(GetACP(), 0, (char*)mb, 2, &wc, 1) > 0)
2018 c = wc;
2019 }
2020# endif
2021 if (send_keys_to_term(curbuf->b_term, c, TRUE) != OK)
2022 {
Bram Moolenaard317b382018-02-08 22:33:31 +01002023 if (c == K_MOUSEMOVE)
2024 /* We are sure to come back here, don't reset the cursor color
2025 * and shape to avoid flickering. */
2026 restore_cursor = FALSE;
2027
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002028 ret = OK;
2029 goto theend;
2030 }
2031 }
2032 ret = FAIL;
2033
2034theend:
2035 in_terminal_loop = NULL;
Bram Moolenaard317b382018-02-08 22:33:31 +01002036 if (restore_cursor)
2037 prepare_restore_cursor_props();
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002038 return ret;
2039}
2040
2041/*
2042 * Called when a job has finished.
2043 * This updates the title and status, but does not close the vterm, because
2044 * there might still be pending output in the channel.
2045 */
2046 void
2047term_job_ended(job_T *job)
2048{
2049 term_T *term;
2050 int did_one = FALSE;
2051
2052 for (term = first_term; term != NULL; term = term->tl_next)
2053 if (term->tl_job == job)
2054 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002055 VIM_CLEAR(term->tl_title);
2056 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002057 redraw_buf_and_status_later(term->tl_buffer, VALID);
2058 did_one = TRUE;
2059 }
2060 if (did_one)
2061 redraw_statuslines();
2062 if (curbuf->b_term != NULL)
2063 {
2064 if (curbuf->b_term->tl_job == job)
2065 maketitle();
2066 update_cursor(curbuf->b_term, TRUE);
2067 }
2068}
2069
2070 static void
2071may_toggle_cursor(term_T *term)
2072{
2073 if (in_terminal_loop == term)
2074 {
2075 if (term->tl_cursor_visible)
2076 cursor_on();
2077 else
2078 cursor_off();
2079 }
2080}
2081
2082/*
2083 * Reverse engineer the RGB value into a cterm color index.
Bram Moolenaar46359e12017-11-29 22:33:38 +01002084 * First color is 1. Return 0 if no match found (default color).
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002085 */
2086 static int
2087color2index(VTermColor *color, int fg, int *boldp)
2088{
2089 int red = color->red;
2090 int blue = color->blue;
2091 int green = color->green;
2092
Bram Moolenaar46359e12017-11-29 22:33:38 +01002093 if (color->ansi_index != VTERM_ANSI_INDEX_NONE)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002094 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002095 /* First 16 colors and default: use the ANSI index, because these
2096 * colors can be redefined. */
2097 if (t_colors >= 16)
2098 return color->ansi_index;
2099 switch (color->ansi_index)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002100 {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002101 case 0: return 0;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01002102 case 1: return lookup_color( 0, fg, boldp) + 1; /* black */
Bram Moolenaar46359e12017-11-29 22:33:38 +01002103 case 2: return lookup_color( 4, fg, boldp) + 1; /* dark red */
2104 case 3: return lookup_color( 2, fg, boldp) + 1; /* dark green */
2105 case 4: return lookup_color( 6, fg, boldp) + 1; /* brown */
2106 case 5: return lookup_color( 1, fg, boldp) + 1; /* dark blue*/
2107 case 6: return lookup_color( 5, fg, boldp) + 1; /* dark magenta */
2108 case 7: return lookup_color( 3, fg, boldp) + 1; /* dark cyan */
2109 case 8: return lookup_color( 8, fg, boldp) + 1; /* light grey */
2110 case 9: return lookup_color(12, fg, boldp) + 1; /* dark grey */
2111 case 10: return lookup_color(20, fg, boldp) + 1; /* red */
2112 case 11: return lookup_color(16, fg, boldp) + 1; /* green */
2113 case 12: return lookup_color(24, fg, boldp) + 1; /* yellow */
2114 case 13: return lookup_color(14, fg, boldp) + 1; /* blue */
2115 case 14: return lookup_color(22, fg, boldp) + 1; /* magenta */
2116 case 15: return lookup_color(18, fg, boldp) + 1; /* cyan */
2117 case 16: return lookup_color(26, fg, boldp) + 1; /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002118 }
2119 }
Bram Moolenaar46359e12017-11-29 22:33:38 +01002120
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002121 if (t_colors >= 256)
2122 {
2123 if (red == blue && red == green)
2124 {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002125 /* 24-color greyscale plus white and black */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002126 static int cutoff[23] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002127 0x0D, 0x17, 0x21, 0x2B, 0x35, 0x3F, 0x49, 0x53, 0x5D, 0x67,
2128 0x71, 0x7B, 0x85, 0x8F, 0x99, 0xA3, 0xAD, 0xB7, 0xC1, 0xCB,
2129 0xD5, 0xDF, 0xE9};
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002130 int i;
2131
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002132 if (red < 5)
2133 return 17; /* 00/00/00 */
2134 if (red > 245) /* ff/ff/ff */
2135 return 232;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002136 for (i = 0; i < 23; ++i)
2137 if (red < cutoff[i])
2138 return i + 233;
2139 return 256;
2140 }
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002141 {
2142 static int cutoff[5] = {0x2F, 0x73, 0x9B, 0xC3, 0xEB};
2143 int ri, gi, bi;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002144
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002145 /* 216-color cube */
2146 for (ri = 0; ri < 5; ++ri)
2147 if (red < cutoff[ri])
2148 break;
2149 for (gi = 0; gi < 5; ++gi)
2150 if (green < cutoff[gi])
2151 break;
2152 for (bi = 0; bi < 5; ++bi)
2153 if (blue < cutoff[bi])
2154 break;
2155 return 17 + ri * 36 + gi * 6 + bi;
2156 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002157 }
2158 return 0;
2159}
2160
2161/*
Bram Moolenaard96ff162018-02-18 22:13:29 +01002162 * Convert Vterm attributes to highlight flags.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002163 */
2164 static int
Bram Moolenaard96ff162018-02-18 22:13:29 +01002165vtermAttr2hl(VTermScreenCellAttrs cellattrs)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002166{
2167 int attr = 0;
2168
2169 if (cellattrs.bold)
2170 attr |= HL_BOLD;
2171 if (cellattrs.underline)
2172 attr |= HL_UNDERLINE;
2173 if (cellattrs.italic)
2174 attr |= HL_ITALIC;
2175 if (cellattrs.strike)
2176 attr |= HL_STRIKETHROUGH;
2177 if (cellattrs.reverse)
2178 attr |= HL_INVERSE;
Bram Moolenaard96ff162018-02-18 22:13:29 +01002179 return attr;
2180}
2181
2182/*
2183 * Store Vterm attributes in "cell" from highlight flags.
2184 */
2185 static void
2186hl2vtermAttr(int attr, cellattr_T *cell)
2187{
2188 vim_memset(&cell->attrs, 0, sizeof(VTermScreenCellAttrs));
2189 if (attr & HL_BOLD)
2190 cell->attrs.bold = 1;
2191 if (attr & HL_UNDERLINE)
2192 cell->attrs.underline = 1;
2193 if (attr & HL_ITALIC)
2194 cell->attrs.italic = 1;
2195 if (attr & HL_STRIKETHROUGH)
2196 cell->attrs.strike = 1;
2197 if (attr & HL_INVERSE)
2198 cell->attrs.reverse = 1;
2199}
2200
2201/*
2202 * Convert the attributes of a vterm cell into an attribute index.
2203 */
2204 static int
2205cell2attr(VTermScreenCellAttrs cellattrs, VTermColor cellfg, VTermColor cellbg)
2206{
2207 int attr = vtermAttr2hl(cellattrs);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002208
2209#ifdef FEAT_GUI
2210 if (gui.in_use)
2211 {
2212 guicolor_T fg, bg;
2213
2214 fg = gui_mch_get_rgb_color(cellfg.red, cellfg.green, cellfg.blue);
2215 bg = gui_mch_get_rgb_color(cellbg.red, cellbg.green, cellbg.blue);
2216 return get_gui_attr_idx(attr, fg, bg);
2217 }
2218 else
2219#endif
2220#ifdef FEAT_TERMGUICOLORS
2221 if (p_tgc)
2222 {
2223 guicolor_T fg, bg;
2224
2225 fg = gui_get_rgb_color_cmn(cellfg.red, cellfg.green, cellfg.blue);
2226 bg = gui_get_rgb_color_cmn(cellbg.red, cellbg.green, cellbg.blue);
2227
2228 return get_tgc_attr_idx(attr, fg, bg);
2229 }
2230 else
2231#endif
2232 {
2233 int bold = MAYBE;
2234 int fg = color2index(&cellfg, TRUE, &bold);
2235 int bg = color2index(&cellbg, FALSE, &bold);
2236
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002237 /* Use the "Terminal" highlighting for the default colors. */
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002238 if ((fg == 0 || bg == 0) && t_colors >= 16)
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002239 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002240 if (fg == 0 && term_default_cterm_fg >= 0)
2241 fg = term_default_cterm_fg + 1;
2242 if (bg == 0 && term_default_cterm_bg >= 0)
2243 bg = term_default_cterm_bg + 1;
Bram Moolenaar76bb7192017-11-30 22:07:07 +01002244 }
2245
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002246 /* with 8 colors set the bold attribute to get a bright foreground */
2247 if (bold == TRUE)
2248 attr |= HL_BOLD;
2249 return get_cterm_attr_idx(attr, fg, bg);
2250 }
2251 return 0;
2252}
2253
2254 static int
2255handle_damage(VTermRect rect, void *user)
2256{
2257 term_T *term = (term_T *)user;
2258
2259 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, rect.start_row);
2260 term->tl_dirty_row_end = MAX(term->tl_dirty_row_end, rect.end_row);
2261 redraw_buf_later(term->tl_buffer, NOT_VALID);
2262 return 1;
2263}
2264
2265 static int
2266handle_moverect(VTermRect dest, VTermRect src, void *user)
2267{
2268 term_T *term = (term_T *)user;
2269
2270 /* Scrolling up is done much more efficiently by deleting lines instead of
2271 * redrawing the text. */
2272 if (dest.start_col == src.start_col
2273 && dest.end_col == src.end_col
2274 && dest.start_row < src.start_row)
2275 {
2276 win_T *wp;
2277 VTermColor fg, bg;
2278 VTermScreenCellAttrs attr;
2279 int clear_attr;
2280
2281 /* Set the color to clear lines with. */
2282 vterm_state_get_default_colors(vterm_obtain_state(term->tl_vterm),
2283 &fg, &bg);
2284 vim_memset(&attr, 0, sizeof(attr));
2285 clear_attr = cell2attr(attr, fg, bg);
2286
2287 FOR_ALL_WINDOWS(wp)
2288 {
2289 if (wp->w_buffer == term->tl_buffer)
2290 win_del_lines(wp, dest.start_row,
2291 src.start_row - dest.start_row, FALSE, FALSE,
2292 clear_attr);
2293 }
2294 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002295
2296 term->tl_dirty_row_start = MIN(term->tl_dirty_row_start, dest.start_row);
2297 term->tl_dirty_row_end = MIN(term->tl_dirty_row_end, dest.end_row);
2298
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002299 redraw_buf_later(term->tl_buffer, NOT_VALID);
2300 return 1;
2301}
2302
2303 static int
2304handle_movecursor(
2305 VTermPos pos,
2306 VTermPos oldpos UNUSED,
2307 int visible,
2308 void *user)
2309{
2310 term_T *term = (term_T *)user;
2311 win_T *wp;
2312
2313 term->tl_cursor_pos = pos;
2314 term->tl_cursor_visible = visible;
2315
2316 FOR_ALL_WINDOWS(wp)
2317 {
2318 if (wp->w_buffer == term->tl_buffer)
2319 position_cursor(wp, &pos);
2320 }
2321 if (term->tl_buffer == curbuf && !term->tl_normal_mode)
2322 {
2323 may_toggle_cursor(term);
2324 update_cursor(term, term->tl_cursor_visible);
2325 }
2326
2327 return 1;
2328}
2329
2330 static int
2331handle_settermprop(
2332 VTermProp prop,
2333 VTermValue *value,
2334 void *user)
2335{
2336 term_T *term = (term_T *)user;
2337
2338 switch (prop)
2339 {
2340 case VTERM_PROP_TITLE:
2341 vim_free(term->tl_title);
2342 /* a blank title isn't useful, make it empty, so that "running" is
2343 * displayed */
2344 if (*skipwhite((char_u *)value->string) == NUL)
2345 term->tl_title = NULL;
2346#ifdef WIN3264
2347 else if (!enc_utf8 && enc_codepage > 0)
2348 {
2349 WCHAR *ret = NULL;
2350 int length = 0;
2351
2352 MultiByteToWideChar_alloc(CP_UTF8, 0,
2353 (char*)value->string, (int)STRLEN(value->string),
2354 &ret, &length);
2355 if (ret != NULL)
2356 {
2357 WideCharToMultiByte_alloc(enc_codepage, 0,
2358 ret, length, (char**)&term->tl_title,
2359 &length, 0, 0);
2360 vim_free(ret);
2361 }
2362 }
2363#endif
2364 else
2365 term->tl_title = vim_strsave((char_u *)value->string);
Bram Moolenaard23a8232018-02-10 18:45:26 +01002366 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002367 if (term == curbuf->b_term)
2368 maketitle();
2369 break;
2370
2371 case VTERM_PROP_CURSORVISIBLE:
2372 term->tl_cursor_visible = value->boolean;
2373 may_toggle_cursor(term);
2374 out_flush();
2375 break;
2376
2377 case VTERM_PROP_CURSORBLINK:
2378 term->tl_cursor_blink = value->boolean;
2379 may_set_cursor_props(term);
2380 break;
2381
2382 case VTERM_PROP_CURSORSHAPE:
2383 term->tl_cursor_shape = value->number;
2384 may_set_cursor_props(term);
2385 break;
2386
2387 case VTERM_PROP_CURSORCOLOR:
Bram Moolenaard317b382018-02-08 22:33:31 +01002388 if (desired_cursor_color == term->tl_cursor_color)
2389 desired_cursor_color = (char_u *)"";
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002390 vim_free(term->tl_cursor_color);
2391 if (*value->string == NUL)
2392 term->tl_cursor_color = NULL;
2393 else
2394 term->tl_cursor_color = vim_strsave((char_u *)value->string);
2395 may_set_cursor_props(term);
2396 break;
2397
2398 case VTERM_PROP_ALTSCREEN:
2399 /* TODO: do anything else? */
2400 term->tl_using_altscreen = value->boolean;
2401 break;
2402
2403 default:
2404 break;
2405 }
2406 /* Always return 1, otherwise vterm doesn't store the value internally. */
2407 return 1;
2408}
2409
2410/*
2411 * The job running in the terminal resized the terminal.
2412 */
2413 static int
2414handle_resize(int rows, int cols, void *user)
2415{
2416 term_T *term = (term_T *)user;
2417 win_T *wp;
2418
2419 term->tl_rows = rows;
2420 term->tl_cols = cols;
2421 if (term->tl_vterm_size_changed)
2422 /* Size was set by vterm_set_size(), don't set the window size. */
2423 term->tl_vterm_size_changed = FALSE;
2424 else
2425 {
2426 FOR_ALL_WINDOWS(wp)
2427 {
2428 if (wp->w_buffer == term->tl_buffer)
2429 {
2430 win_setheight_win(rows, wp);
2431 win_setwidth_win(cols, wp);
2432 }
2433 }
2434 redraw_buf_later(term->tl_buffer, NOT_VALID);
2435 }
2436 return 1;
2437}
2438
2439/*
2440 * Handle a line that is pushed off the top of the screen.
2441 */
2442 static int
2443handle_pushline(int cols, const VTermScreenCell *cells, void *user)
2444{
2445 term_T *term = (term_T *)user;
2446
2447 /* TODO: Limit the number of lines that are stored. */
2448 if (ga_grow(&term->tl_scrollback, 1) == OK)
2449 {
2450 cellattr_T *p = NULL;
2451 int len = 0;
2452 int i;
2453 int c;
2454 int col;
2455 sb_line_T *line;
2456 garray_T ga;
2457 cellattr_T fill_attr = term->tl_default_color;
2458
2459 /* do not store empty cells at the end */
2460 for (i = 0; i < cols; ++i)
2461 if (cells[i].chars[0] != 0)
2462 len = i + 1;
2463 else
2464 cell2cellattr(&cells[i], &fill_attr);
2465
2466 ga_init2(&ga, 1, 100);
2467 if (len > 0)
2468 p = (cellattr_T *)alloc((int)sizeof(cellattr_T) * len);
2469 if (p != NULL)
2470 {
2471 for (col = 0; col < len; col += cells[col].width)
2472 {
2473 if (ga_grow(&ga, MB_MAXBYTES) == FAIL)
2474 {
2475 ga.ga_len = 0;
2476 break;
2477 }
2478 for (i = 0; (c = cells[col].chars[i]) > 0 || i == 0; ++i)
2479 ga.ga_len += utf_char2bytes(c == NUL ? ' ' : c,
2480 (char_u *)ga.ga_data + ga.ga_len);
2481 cell2cellattr(&cells[col], &p[col]);
2482 }
2483 }
2484 if (ga_grow(&ga, 1) == FAIL)
2485 add_scrollback_line_to_buffer(term, (char_u *)"", 0);
2486 else
2487 {
2488 *((char_u *)ga.ga_data + ga.ga_len) = NUL;
2489 add_scrollback_line_to_buffer(term, ga.ga_data, ga.ga_len);
2490 }
2491 ga_clear(&ga);
2492
2493 line = (sb_line_T *)term->tl_scrollback.ga_data
2494 + term->tl_scrollback.ga_len;
2495 line->sb_cols = len;
2496 line->sb_cells = p;
2497 line->sb_fill_attr = fill_attr;
2498 ++term->tl_scrollback.ga_len;
2499 ++term->tl_scrollback_scrolled;
2500 }
2501 return 0; /* ignored */
2502}
2503
2504static VTermScreenCallbacks screen_callbacks = {
2505 handle_damage, /* damage */
2506 handle_moverect, /* moverect */
2507 handle_movecursor, /* movecursor */
2508 handle_settermprop, /* settermprop */
2509 NULL, /* bell */
2510 handle_resize, /* resize */
2511 handle_pushline, /* sb_pushline */
2512 NULL /* sb_popline */
2513};
2514
2515/*
2516 * Called when a channel has been closed.
2517 * If this was a channel for a terminal window then finish it up.
2518 */
2519 void
2520term_channel_closed(channel_T *ch)
2521{
2522 term_T *term;
2523 int did_one = FALSE;
2524
2525 for (term = first_term; term != NULL; term = term->tl_next)
2526 if (term->tl_job == ch->ch_job)
2527 {
2528 term->tl_channel_closed = TRUE;
2529 did_one = TRUE;
2530
Bram Moolenaard23a8232018-02-10 18:45:26 +01002531 VIM_CLEAR(term->tl_title);
2532 VIM_CLEAR(term->tl_status_text);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002533
2534 /* Unless in Terminal-Normal mode: clear the vterm. */
2535 if (!term->tl_normal_mode)
2536 {
2537 int fnum = term->tl_buffer->b_fnum;
2538
2539 cleanup_vterm(term);
2540
2541 if (term->tl_finish == 'c')
2542 {
Bram Moolenaarff546792017-11-21 14:47:57 +01002543 aco_save_T aco;
2544
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002545 /* ++close or term_finish == "close" */
2546 ch_log(NULL, "terminal job finished, closing window");
Bram Moolenaarff546792017-11-21 14:47:57 +01002547 aucmd_prepbuf(&aco, term->tl_buffer);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002548 do_bufdel(DOBUF_WIPE, (char_u *)"", 1, fnum, fnum, FALSE);
Bram Moolenaarff546792017-11-21 14:47:57 +01002549 aucmd_restbuf(&aco);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002550 break;
2551 }
2552 if (term->tl_finish == 'o' && term->tl_buffer->b_nwindows == 0)
2553 {
2554 char buf[50];
2555
2556 /* TODO: use term_opencmd */
2557 ch_log(NULL, "terminal job finished, opening window");
2558 vim_snprintf(buf, sizeof(buf),
2559 term->tl_opencmd == NULL
2560 ? "botright sbuf %d"
2561 : (char *)term->tl_opencmd, fnum);
2562 do_cmdline_cmd((char_u *)buf);
2563 }
2564 else
2565 ch_log(NULL, "terminal job finished");
2566 }
2567
2568 redraw_buf_and_status_later(term->tl_buffer, NOT_VALID);
2569 }
2570 if (did_one)
2571 {
2572 redraw_statuslines();
2573
2574 /* Need to break out of vgetc(). */
2575 ins_char_typebuf(K_IGNORE);
2576 typebuf_was_filled = TRUE;
2577
2578 term = curbuf->b_term;
2579 if (term != NULL)
2580 {
2581 if (term->tl_job == ch->ch_job)
2582 maketitle();
2583 update_cursor(term, term->tl_cursor_visible);
2584 }
2585 }
2586}
2587
2588/*
2589 * Called to update a window that contains an active terminal.
2590 * Returns FAIL when there is no terminal running in this window or in
2591 * Terminal-Normal mode.
2592 */
2593 int
2594term_update_window(win_T *wp)
2595{
2596 term_T *term = wp->w_buffer->b_term;
2597 VTerm *vterm;
2598 VTermScreen *screen;
2599 VTermState *state;
2600 VTermPos pos;
2601
2602 if (term == NULL || term->tl_vterm == NULL || term->tl_normal_mode)
2603 return FAIL;
2604
2605 vterm = term->tl_vterm;
2606 screen = vterm_obtain_screen(vterm);
2607 state = vterm_obtain_state(vterm);
2608
Bram Moolenaar54e5dbf2017-10-07 17:35:09 +02002609 if (wp->w_redr_type >= SOME_VALID)
Bram Moolenaar19a3d682017-10-02 21:54:59 +02002610 {
2611 term->tl_dirty_row_start = 0;
2612 term->tl_dirty_row_end = MAX_ROW;
2613 }
2614
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002615 /*
2616 * If the window was resized a redraw will be triggered and we get here.
2617 * Adjust the size of the vterm unless 'termsize' specifies a fixed size.
2618 */
2619 if ((!term->tl_rows_fixed && term->tl_rows != wp->w_height)
2620 || (!term->tl_cols_fixed && term->tl_cols != wp->w_width))
2621 {
2622 int rows = term->tl_rows_fixed ? term->tl_rows : wp->w_height;
2623 int cols = term->tl_cols_fixed ? term->tl_cols : wp->w_width;
2624 win_T *twp;
2625
2626 FOR_ALL_WINDOWS(twp)
2627 {
2628 /* When more than one window shows the same terminal, use the
2629 * smallest size. */
2630 if (twp->w_buffer == term->tl_buffer)
2631 {
2632 if (!term->tl_rows_fixed && rows > twp->w_height)
2633 rows = twp->w_height;
2634 if (!term->tl_cols_fixed && cols > twp->w_width)
2635 cols = twp->w_width;
2636 }
2637 }
2638
2639 term->tl_vterm_size_changed = TRUE;
2640 vterm_set_size(vterm, rows, cols);
2641 ch_log(term->tl_job->jv_channel, "Resizing terminal to %d lines",
2642 rows);
2643 term_report_winsize(term, rows, cols);
2644 }
2645
2646 /* The cursor may have been moved when resizing. */
2647 vterm_state_get_cursorpos(state, &pos);
2648 position_cursor(wp, &pos);
2649
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002650 for (pos.row = term->tl_dirty_row_start; pos.row < term->tl_dirty_row_end
2651 && pos.row < wp->w_height; ++pos.row)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002652 {
2653 int off = screen_get_current_line_off();
2654 int max_col = MIN(wp->w_width, term->tl_cols);
2655
2656 if (pos.row < term->tl_rows)
2657 {
2658 for (pos.col = 0; pos.col < max_col; )
2659 {
2660 VTermScreenCell cell;
2661 int c;
2662
2663 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
2664 vim_memset(&cell, 0, sizeof(cell));
2665
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002666 c = cell.chars[0];
2667 if (c == NUL)
2668 {
2669 ScreenLines[off] = ' ';
2670 if (enc_utf8)
2671 ScreenLinesUC[off] = NUL;
2672 }
2673 else
2674 {
2675 if (enc_utf8)
2676 {
Bram Moolenaar6daeef12017-10-15 22:56:49 +02002677 int i;
2678
2679 /* composing chars */
2680 for (i = 0; i < Screen_mco
2681 && i + 1 < VTERM_MAX_CHARS_PER_CELL; ++i)
2682 {
2683 ScreenLinesC[i][off] = cell.chars[i + 1];
2684 if (cell.chars[i + 1] == 0)
2685 break;
2686 }
2687 if (c >= 0x80 || (Screen_mco > 0
2688 && ScreenLinesC[0][off] != 0))
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002689 {
2690 ScreenLines[off] = ' ';
2691 ScreenLinesUC[off] = c;
2692 }
2693 else
2694 {
2695 ScreenLines[off] = c;
2696 ScreenLinesUC[off] = NUL;
2697 }
2698 }
2699#ifdef WIN3264
2700 else if (has_mbyte && c >= 0x80)
2701 {
2702 char_u mb[MB_MAXBYTES+1];
2703 WCHAR wc = c;
2704
2705 if (WideCharToMultiByte(GetACP(), 0, &wc, 1,
2706 (char*)mb, 2, 0, 0) > 1)
2707 {
2708 ScreenLines[off] = mb[0];
2709 ScreenLines[off + 1] = mb[1];
2710 cell.width = mb_ptr2cells(mb);
2711 }
2712 else
2713 ScreenLines[off] = c;
2714 }
2715#endif
2716 else
2717 ScreenLines[off] = c;
2718 }
2719 ScreenAttrs[off] = cell2attr(cell.attrs, cell.fg, cell.bg);
2720
2721 ++pos.col;
2722 ++off;
2723 if (cell.width == 2)
2724 {
2725 if (enc_utf8)
2726 ScreenLinesUC[off] = NUL;
2727
2728 /* don't set the second byte to NUL for a DBCS encoding, it
2729 * has been set above */
2730 if (enc_utf8 || !has_mbyte)
2731 ScreenLines[off] = NUL;
2732
2733 ++pos.col;
2734 ++off;
2735 }
2736 }
2737 }
2738 else
2739 pos.col = 0;
2740
Bram Moolenaarf118d482018-03-13 13:14:00 +01002741 screen_line(wp->w_winrow + pos.row
2742#ifdef FEAT_MENU
2743 + winbar_height(wp)
2744#endif
2745 , wp->w_wincol, pos.col, wp->w_width, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002746 }
Bram Moolenaar3a497e12017-09-30 20:40:27 +02002747 term->tl_dirty_row_start = MAX_ROW;
2748 term->tl_dirty_row_end = 0;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002749
2750 return OK;
2751}
2752
2753/*
2754 * Return TRUE if "wp" is a terminal window where the job has finished.
2755 */
2756 int
2757term_is_finished(buf_T *buf)
2758{
2759 return buf->b_term != NULL && buf->b_term->tl_vterm == NULL;
2760}
2761
2762/*
2763 * Return TRUE if "wp" is a terminal window where the job has finished or we
2764 * are in Terminal-Normal mode, thus we show the buffer contents.
2765 */
2766 int
2767term_show_buffer(buf_T *buf)
2768{
2769 term_T *term = buf->b_term;
2770
2771 return term != NULL && (term->tl_vterm == NULL || term->tl_normal_mode);
2772}
2773
2774/*
2775 * The current buffer is going to be changed. If there is terminal
2776 * highlighting remove it now.
2777 */
2778 void
2779term_change_in_curbuf(void)
2780{
2781 term_T *term = curbuf->b_term;
2782
2783 if (term_is_finished(curbuf) && term->tl_scrollback.ga_len > 0)
2784 {
2785 free_scrollback(term);
2786 redraw_buf_later(term->tl_buffer, NOT_VALID);
2787
2788 /* The buffer is now like a normal buffer, it cannot be easily
2789 * abandoned when changed. */
2790 set_string_option_direct((char_u *)"buftype", -1,
2791 (char_u *)"", OPT_FREE|OPT_LOCAL, 0);
2792 }
2793}
2794
2795/*
2796 * Get the screen attribute for a position in the buffer.
2797 * Use a negative "col" to get the filler background color.
2798 */
2799 int
2800term_get_attr(buf_T *buf, linenr_T lnum, int col)
2801{
2802 term_T *term = buf->b_term;
2803 sb_line_T *line;
2804 cellattr_T *cellattr;
2805
2806 if (lnum > term->tl_scrollback.ga_len)
2807 cellattr = &term->tl_default_color;
2808 else
2809 {
2810 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum - 1;
2811 if (col < 0 || col >= line->sb_cols)
2812 cellattr = &line->sb_fill_attr;
2813 else
2814 cellattr = line->sb_cells + col;
2815 }
2816 return cell2attr(cellattr->attrs, cellattr->fg, cellattr->bg);
2817}
2818
2819static VTermColor ansi_table[16] = {
Bram Moolenaar46359e12017-11-29 22:33:38 +01002820 { 0, 0, 0, 1}, /* black */
2821 {224, 0, 0, 2}, /* dark red */
2822 { 0, 224, 0, 3}, /* dark green */
2823 {224, 224, 0, 4}, /* dark yellow / brown */
2824 { 0, 0, 224, 5}, /* dark blue */
2825 {224, 0, 224, 6}, /* dark magenta */
2826 { 0, 224, 224, 7}, /* dark cyan */
2827 {224, 224, 224, 8}, /* light grey */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002828
Bram Moolenaar46359e12017-11-29 22:33:38 +01002829 {128, 128, 128, 9}, /* dark grey */
2830 {255, 64, 64, 10}, /* light red */
2831 { 64, 255, 64, 11}, /* light green */
2832 {255, 255, 64, 12}, /* yellow */
2833 { 64, 64, 255, 13}, /* light blue */
2834 {255, 64, 255, 14}, /* light magenta */
2835 { 64, 255, 255, 15}, /* light cyan */
2836 {255, 255, 255, 16}, /* white */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002837};
2838
2839static int cube_value[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002840 0x00, 0x5F, 0x87, 0xAF, 0xD7, 0xFF
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002841};
2842
2843static int grey_ramp[] = {
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002844 0x08, 0x12, 0x1C, 0x26, 0x30, 0x3A, 0x44, 0x4E, 0x58, 0x62, 0x6C, 0x76,
2845 0x80, 0x8A, 0x94, 0x9E, 0xA8, 0xB2, 0xBC, 0xC6, 0xD0, 0xDA, 0xE4, 0xEE
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002846};
2847
2848/*
2849 * Convert a cterm color number 0 - 255 to RGB.
Bram Moolenaara8fc0d32017-09-26 13:59:47 +02002850 * This is compatible with xterm.
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002851 */
2852 static void
2853cterm_color2rgb(int nr, VTermColor *rgb)
2854{
2855 int idx;
2856
2857 if (nr < 16)
2858 {
2859 *rgb = ansi_table[nr];
2860 }
2861 else if (nr < 232)
2862 {
2863 /* 216 color cube */
2864 idx = nr - 16;
2865 rgb->blue = cube_value[idx % 6];
2866 rgb->green = cube_value[idx / 6 % 6];
2867 rgb->red = cube_value[idx / 36 % 6];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002868 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002869 }
2870 else if (nr < 256)
2871 {
2872 /* 24 grey scale ramp */
2873 idx = nr - 232;
2874 rgb->blue = grey_ramp[idx];
2875 rgb->green = grey_ramp[idx];
2876 rgb->red = grey_ramp[idx];
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002877 rgb->ansi_index = VTERM_ANSI_INDEX_NONE;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002878 }
2879}
2880
2881/*
2882 * Create a new vterm and initialize it.
2883 */
2884 static void
2885create_vterm(term_T *term, int rows, int cols)
2886{
2887 VTerm *vterm;
2888 VTermScreen *screen;
2889 VTermValue value;
2890 VTermColor *fg, *bg;
2891 int fgval, bgval;
2892 int id;
2893
2894 vterm = vterm_new(rows, cols);
2895 term->tl_vterm = vterm;
2896 screen = vterm_obtain_screen(vterm);
2897 vterm_screen_set_callbacks(screen, &screen_callbacks, term);
2898 /* TODO: depends on 'encoding'. */
2899 vterm_set_utf8(vterm, 1);
2900
2901 vim_memset(&term->tl_default_color.attrs, 0, sizeof(VTermScreenCellAttrs));
2902 term->tl_default_color.width = 1;
2903 fg = &term->tl_default_color.fg;
2904 bg = &term->tl_default_color.bg;
2905
2906 /* Vterm uses a default black background. Set it to white when
2907 * 'background' is "light". */
2908 if (*p_bg == 'l')
2909 {
2910 fgval = 0;
2911 bgval = 255;
2912 }
2913 else
2914 {
2915 fgval = 255;
2916 bgval = 0;
2917 }
2918 fg->red = fg->green = fg->blue = fgval;
2919 bg->red = bg->green = bg->blue = bgval;
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002920 fg->ansi_index = bg->ansi_index = VTERM_ANSI_INDEX_DEFAULT;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002921
2922 /* The "Terminal" highlight group overrules the defaults. */
2923 id = syn_name2id((char_u *)"Terminal");
2924
Bram Moolenaar46359e12017-11-29 22:33:38 +01002925 /* Use the actual color for the GUI and when 'termguicolors' is set. */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002926#if defined(FEAT_GUI) || defined(FEAT_TERMGUICOLORS)
2927 if (0
2928# ifdef FEAT_GUI
2929 || gui.in_use
2930# endif
2931# ifdef FEAT_TERMGUICOLORS
2932 || p_tgc
2933# endif
2934 )
2935 {
2936 guicolor_T fg_rgb = INVALCOLOR;
2937 guicolor_T bg_rgb = INVALCOLOR;
2938
2939 if (id != 0)
2940 syn_id2colors(id, &fg_rgb, &bg_rgb);
2941
2942# ifdef FEAT_GUI
2943 if (gui.in_use)
2944 {
2945 if (fg_rgb == INVALCOLOR)
2946 fg_rgb = gui.norm_pixel;
2947 if (bg_rgb == INVALCOLOR)
2948 bg_rgb = gui.back_pixel;
2949 }
2950# ifdef FEAT_TERMGUICOLORS
2951 else
2952# endif
2953# endif
2954# ifdef FEAT_TERMGUICOLORS
2955 {
2956 if (fg_rgb == INVALCOLOR)
2957 fg_rgb = cterm_normal_fg_gui_color;
2958 if (bg_rgb == INVALCOLOR)
2959 bg_rgb = cterm_normal_bg_gui_color;
2960 }
2961# endif
2962 if (fg_rgb != INVALCOLOR)
2963 {
2964 long_u rgb = GUI_MCH_GET_RGB(fg_rgb);
2965
2966 fg->red = (unsigned)(rgb >> 16);
2967 fg->green = (unsigned)(rgb >> 8) & 255;
2968 fg->blue = (unsigned)rgb & 255;
2969 }
2970 if (bg_rgb != INVALCOLOR)
2971 {
2972 long_u rgb = GUI_MCH_GET_RGB(bg_rgb);
2973
2974 bg->red = (unsigned)(rgb >> 16);
2975 bg->green = (unsigned)(rgb >> 8) & 255;
2976 bg->blue = (unsigned)rgb & 255;
2977 }
2978 }
2979 else
2980#endif
2981 if (id != 0 && t_colors >= 16)
2982 {
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01002983 if (term_default_cterm_fg >= 0)
2984 cterm_color2rgb(term_default_cterm_fg, fg);
2985 if (term_default_cterm_bg >= 0)
2986 cterm_color2rgb(term_default_cterm_bg, bg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002987 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002988 else
2989 {
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002990#if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002991 int tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002992#endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002993
2994 /* In an MS-Windows console we know the normal colors. */
2995 if (cterm_normal_fg_color > 0)
2996 {
2997 cterm_color2rgb(cterm_normal_fg_color - 1, fg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02002998# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02002999 tmp = fg->red;
3000 fg->red = fg->blue;
3001 fg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003002# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003003 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003004# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003005 else
3006 term_get_fg_color(&fg->red, &fg->green, &fg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003007# endif
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003008
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003009 if (cterm_normal_bg_color > 0)
3010 {
3011 cterm_color2rgb(cterm_normal_bg_color - 1, bg);
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003012# if defined(WIN3264) && !defined(FEAT_GUI_W32)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003013 tmp = bg->red;
3014 bg->red = bg->blue;
3015 bg->blue = tmp;
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003016# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003017 }
Bram Moolenaar9377df32017-10-15 13:22:01 +02003018# ifdef FEAT_TERMRESPONSE
Bram Moolenaar65e4c4f2017-10-14 23:24:25 +02003019 else
3020 term_get_bg_color(&bg->red, &bg->green, &bg->blue);
Bram Moolenaar9377df32017-10-15 13:22:01 +02003021# endif
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003022 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003023
3024 vterm_state_set_default_colors(vterm_obtain_state(vterm), fg, bg);
3025
3026 /* Required to initialize most things. */
3027 vterm_screen_reset(screen, 1 /* hard */);
3028
3029 /* Allow using alternate screen. */
3030 vterm_screen_enable_altscreen(screen, 1);
3031
3032 /* For unix do not use a blinking cursor. In an xterm this causes the
3033 * cursor to blink if it's blinking in the xterm.
3034 * For Windows we respect the system wide setting. */
3035#ifdef WIN3264
3036 if (GetCaretBlinkTime() == INFINITE)
3037 value.boolean = 0;
3038 else
3039 value.boolean = 1;
3040#else
3041 value.boolean = 0;
3042#endif
3043 vterm_state_set_termprop(vterm_obtain_state(vterm),
3044 VTERM_PROP_CURSORBLINK, &value);
3045}
3046
3047/*
3048 * Return the text to show for the buffer name and status.
3049 */
3050 char_u *
3051term_get_status_text(term_T *term)
3052{
3053 if (term->tl_status_text == NULL)
3054 {
3055 char_u *txt;
3056 size_t len;
3057
3058 if (term->tl_normal_mode)
3059 {
3060 if (term_job_running(term))
3061 txt = (char_u *)_("Terminal");
3062 else
3063 txt = (char_u *)_("Terminal-finished");
3064 }
3065 else if (term->tl_title != NULL)
3066 txt = term->tl_title;
3067 else if (term_none_open(term))
3068 txt = (char_u *)_("active");
3069 else if (term_job_running(term))
3070 txt = (char_u *)_("running");
3071 else
3072 txt = (char_u *)_("finished");
3073 len = 9 + STRLEN(term->tl_buffer->b_fname) + STRLEN(txt);
3074 term->tl_status_text = alloc((int)len);
3075 if (term->tl_status_text != NULL)
3076 vim_snprintf((char *)term->tl_status_text, len, "%s [%s]",
3077 term->tl_buffer->b_fname, txt);
3078 }
3079 return term->tl_status_text;
3080}
3081
3082/*
3083 * Mark references in jobs of terminals.
3084 */
3085 int
3086set_ref_in_term(int copyID)
3087{
3088 int abort = FALSE;
3089 term_T *term;
3090 typval_T tv;
3091
3092 for (term = first_term; term != NULL; term = term->tl_next)
3093 if (term->tl_job != NULL)
3094 {
3095 tv.v_type = VAR_JOB;
3096 tv.vval.v_job = term->tl_job;
3097 abort = abort || set_ref_in_item(&tv, copyID, NULL, NULL);
3098 }
3099 return abort;
3100}
3101
3102/*
Bram Moolenaara7c54cf2017-12-01 21:07:20 +01003103 * Cache "Terminal" highlight group colors.
3104 */
3105 void
3106set_terminal_default_colors(int cterm_fg, int cterm_bg)
3107{
3108 term_default_cterm_fg = cterm_fg - 1;
3109 term_default_cterm_bg = cterm_bg - 1;
3110}
3111
3112/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003113 * Get the buffer from the first argument in "argvars".
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003114 * Returns NULL when the buffer is not for a terminal window and logs a message
3115 * with "where".
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003116 */
3117 static buf_T *
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003118term_get_buf(typval_T *argvars, char *where)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003119{
3120 buf_T *buf;
3121
3122 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
3123 ++emsg_off;
3124 buf = get_buf_tv(&argvars[0], FALSE);
3125 --emsg_off;
3126 if (buf == NULL || buf->b_term == NULL)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003127 {
3128 ch_log(NULL, "%s: invalid buffer argument", where);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003129 return NULL;
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003130 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003131 return buf;
3132}
3133
Bram Moolenaard96ff162018-02-18 22:13:29 +01003134 static int
3135same_color(VTermColor *a, VTermColor *b)
3136{
3137 return a->red == b->red
3138 && a->green == b->green
3139 && a->blue == b->blue
3140 && a->ansi_index == b->ansi_index;
3141}
3142
3143 static void
3144dump_term_color(FILE *fd, VTermColor *color)
3145{
3146 fprintf(fd, "%02x%02x%02x%d",
3147 (int)color->red, (int)color->green, (int)color->blue,
3148 (int)color->ansi_index);
3149}
3150
3151/*
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003152 * "term_dumpwrite(buf, filename, options)" function
Bram Moolenaard96ff162018-02-18 22:13:29 +01003153 *
3154 * Each screen cell in full is:
3155 * |{characters}+{attributes}#{fg-color}{color-idx}#{bg-color}{color-idx}
3156 * {characters} is a space for an empty cell
3157 * For a double-width character "+" is changed to "*" and the next cell is
3158 * skipped.
3159 * {attributes} is the decimal value of HL_BOLD + HL_UNDERLINE, etc.
3160 * when "&" use the same as the previous cell.
3161 * {fg-color} is hex RGB, when "&" use the same as the previous cell.
3162 * {bg-color} is hex RGB, when "&" use the same as the previous cell.
3163 * {color-idx} is a number from 0 to 255
3164 *
3165 * Screen cell with same width, attributes and color as the previous one:
3166 * |{characters}
3167 *
3168 * To use the color of the previous cell, use "&" instead of {color}-{idx}.
3169 *
3170 * Repeating the previous screen cell:
3171 * @{count}
3172 */
3173 void
3174f_term_dumpwrite(typval_T *argvars, typval_T *rettv UNUSED)
3175{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003176 buf_T *buf = term_get_buf(argvars, "term_dumpwrite()");
Bram Moolenaard96ff162018-02-18 22:13:29 +01003177 term_T *term;
3178 char_u *fname;
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003179 int max_height = 0;
3180 int max_width = 0;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003181 stat_T st;
3182 FILE *fd;
3183 VTermPos pos;
3184 VTermScreen *screen;
3185 VTermScreenCell prev_cell;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003186 VTermState *state;
3187 VTermPos cursor_pos;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003188
3189 if (check_restricted() || check_secure())
3190 return;
3191 if (buf == NULL)
3192 return;
3193 term = buf->b_term;
3194
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003195 if (argvars[2].v_type != VAR_UNKNOWN)
3196 {
3197 dict_T *d;
3198
3199 if (argvars[2].v_type != VAR_DICT)
3200 {
3201 EMSG(_(e_dictreq));
3202 return;
3203 }
3204 d = argvars[2].vval.v_dict;
3205 if (d != NULL)
3206 {
3207 max_height = get_dict_number(d, (char_u *)"rows");
3208 max_width = get_dict_number(d, (char_u *)"columns");
3209 }
3210 }
3211
Bram Moolenaard96ff162018-02-18 22:13:29 +01003212 fname = get_tv_string_chk(&argvars[1]);
3213 if (fname == NULL)
3214 return;
3215 if (mch_stat((char *)fname, &st) >= 0)
3216 {
3217 EMSG2(_("E953: File exists: %s"), fname);
3218 return;
3219 }
3220
Bram Moolenaard96ff162018-02-18 22:13:29 +01003221 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
3222 {
3223 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
3224 return;
3225 }
3226
3227 vim_memset(&prev_cell, 0, sizeof(prev_cell));
3228
3229 screen = vterm_obtain_screen(term->tl_vterm);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003230 state = vterm_obtain_state(term->tl_vterm);
3231 vterm_state_get_cursorpos(state, &cursor_pos);
3232
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003233 for (pos.row = 0; (max_height == 0 || pos.row < max_height)
3234 && pos.row < term->tl_rows; ++pos.row)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003235 {
3236 int repeat = 0;
3237
Bram Moolenaar6bb2cdf2018-02-24 19:53:53 +01003238 for (pos.col = 0; (max_width == 0 || pos.col < max_width)
3239 && pos.col < term->tl_cols; ++pos.col)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003240 {
3241 VTermScreenCell cell;
3242 int same_attr;
3243 int same_chars = TRUE;
3244 int i;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003245 int is_cursor_pos = (pos.col == cursor_pos.col
3246 && pos.row == cursor_pos.row);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003247
3248 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
3249 vim_memset(&cell, 0, sizeof(cell));
3250
3251 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
3252 {
3253 if (cell.chars[i] != prev_cell.chars[i])
3254 same_chars = FALSE;
3255 if (cell.chars[i] == NUL || prev_cell.chars[i] == NUL)
3256 break;
3257 }
3258 same_attr = vtermAttr2hl(cell.attrs)
3259 == vtermAttr2hl(prev_cell.attrs)
3260 && same_color(&cell.fg, &prev_cell.fg)
3261 && same_color(&cell.bg, &prev_cell.bg);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003262 if (same_chars && cell.width == prev_cell.width && same_attr
3263 && !is_cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003264 {
3265 ++repeat;
3266 }
3267 else
3268 {
3269 if (repeat > 0)
3270 {
3271 fprintf(fd, "@%d", repeat);
3272 repeat = 0;
3273 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003274 fputs(is_cursor_pos ? ">" : "|", fd);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003275
3276 if (cell.chars[0] == NUL)
3277 fputs(" ", fd);
3278 else
3279 {
3280 char_u charbuf[10];
3281 int len;
3282
3283 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL
3284 && cell.chars[i] != NUL; ++i)
3285 {
3286 len = utf_char2bytes(cell.chars[0], charbuf);
3287 fwrite(charbuf, len, 1, fd);
3288 }
3289 }
3290
3291 /* When only the characters differ we don't write anything, the
3292 * following "|", "@" or NL will indicate using the same
3293 * attributes. */
3294 if (cell.width != prev_cell.width || !same_attr)
3295 {
3296 if (cell.width == 2)
3297 {
3298 fputs("*", fd);
3299 ++pos.col;
3300 }
3301 else
3302 fputs("+", fd);
3303
3304 if (same_attr)
3305 {
3306 fputs("&", fd);
3307 }
3308 else
3309 {
3310 fprintf(fd, "%d", vtermAttr2hl(cell.attrs));
3311 if (same_color(&cell.fg, &prev_cell.fg))
3312 fputs("&", fd);
3313 else
3314 {
3315 fputs("#", fd);
3316 dump_term_color(fd, &cell.fg);
3317 }
3318 if (same_color(&cell.bg, &prev_cell.bg))
3319 fputs("&", fd);
3320 else
3321 {
3322 fputs("#", fd);
3323 dump_term_color(fd, &cell.bg);
3324 }
3325 }
3326 }
3327
3328 prev_cell = cell;
3329 }
3330 }
3331 if (repeat > 0)
3332 fprintf(fd, "@%d", repeat);
3333 fputs("\n", fd);
3334 }
3335
3336 fclose(fd);
3337}
3338
3339/*
3340 * Called when a dump is corrupted. Put a breakpoint here when debugging.
3341 */
3342 static void
3343dump_is_corrupt(garray_T *gap)
3344{
3345 ga_concat(gap, (char_u *)"CORRUPT");
3346}
3347
3348 static void
3349append_cell(garray_T *gap, cellattr_T *cell)
3350{
3351 if (ga_grow(gap, 1) == OK)
3352 {
3353 *(((cellattr_T *)gap->ga_data) + gap->ga_len) = *cell;
3354 ++gap->ga_len;
3355 }
3356}
3357
3358/*
3359 * Read the dump file from "fd" and append lines to the current buffer.
3360 * Return the cell width of the longest line.
3361 */
3362 static int
Bram Moolenaar9271d052018-02-25 21:39:46 +01003363read_dump_file(FILE *fd, VTermPos *cursor_pos)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003364{
3365 int c;
3366 garray_T ga_text;
3367 garray_T ga_cell;
3368 char_u *prev_char = NULL;
3369 int attr = 0;
3370 cellattr_T cell;
3371 term_T *term = curbuf->b_term;
3372 int max_cells = 0;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003373 int start_row = term->tl_scrollback.ga_len;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003374
3375 ga_init2(&ga_text, 1, 90);
3376 ga_init2(&ga_cell, sizeof(cellattr_T), 90);
3377 vim_memset(&cell, 0, sizeof(cell));
Bram Moolenaar9271d052018-02-25 21:39:46 +01003378 cursor_pos->row = -1;
3379 cursor_pos->col = -1;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003380
3381 c = fgetc(fd);
3382 for (;;)
3383 {
3384 if (c == EOF)
3385 break;
3386 if (c == '\n')
3387 {
3388 /* End of a line: append it to the buffer. */
3389 if (ga_text.ga_data == NULL)
3390 dump_is_corrupt(&ga_text);
3391 if (ga_grow(&term->tl_scrollback, 1) == OK)
3392 {
3393 sb_line_T *line = (sb_line_T *)term->tl_scrollback.ga_data
3394 + term->tl_scrollback.ga_len;
3395
3396 if (max_cells < ga_cell.ga_len)
3397 max_cells = ga_cell.ga_len;
3398 line->sb_cols = ga_cell.ga_len;
3399 line->sb_cells = ga_cell.ga_data;
3400 line->sb_fill_attr = term->tl_default_color;
3401 ++term->tl_scrollback.ga_len;
3402 ga_init(&ga_cell);
3403
3404 ga_append(&ga_text, NUL);
3405 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3406 ga_text.ga_len, FALSE);
3407 }
3408 else
3409 ga_clear(&ga_cell);
3410 ga_text.ga_len = 0;
3411
3412 c = fgetc(fd);
3413 }
Bram Moolenaar9271d052018-02-25 21:39:46 +01003414 else if (c == '|' || c == '>')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003415 {
3416 int prev_len = ga_text.ga_len;
3417
Bram Moolenaar9271d052018-02-25 21:39:46 +01003418 if (c == '>')
3419 {
3420 if (cursor_pos->row != -1)
3421 dump_is_corrupt(&ga_text); /* duplicate cursor */
3422 cursor_pos->row = term->tl_scrollback.ga_len - start_row;
3423 cursor_pos->col = ga_cell.ga_len;
3424 }
3425
Bram Moolenaard96ff162018-02-18 22:13:29 +01003426 /* normal character(s) followed by "+", "*", "|", "@" or NL */
3427 c = fgetc(fd);
3428 if (c != EOF)
3429 ga_append(&ga_text, c);
3430 for (;;)
3431 {
3432 c = fgetc(fd);
Bram Moolenaar9271d052018-02-25 21:39:46 +01003433 if (c == '+' || c == '*' || c == '|' || c == '>' || c == '@'
Bram Moolenaard96ff162018-02-18 22:13:29 +01003434 || c == EOF || c == '\n')
3435 break;
3436 ga_append(&ga_text, c);
3437 }
3438
3439 /* save the character for repeating it */
3440 vim_free(prev_char);
3441 if (ga_text.ga_data != NULL)
3442 prev_char = vim_strnsave(((char_u *)ga_text.ga_data) + prev_len,
3443 ga_text.ga_len - prev_len);
3444
Bram Moolenaar9271d052018-02-25 21:39:46 +01003445 if (c == '@' || c == '|' || c == '>' || c == '\n')
Bram Moolenaard96ff162018-02-18 22:13:29 +01003446 {
3447 /* use all attributes from previous cell */
3448 }
3449 else if (c == '+' || c == '*')
3450 {
3451 int is_bg;
3452
3453 cell.width = c == '+' ? 1 : 2;
3454
3455 c = fgetc(fd);
3456 if (c == '&')
3457 {
3458 /* use same attr as previous cell */
3459 c = fgetc(fd);
3460 }
3461 else if (isdigit(c))
3462 {
3463 /* get the decimal attribute */
3464 attr = 0;
3465 while (isdigit(c))
3466 {
3467 attr = attr * 10 + (c - '0');
3468 c = fgetc(fd);
3469 }
3470 hl2vtermAttr(attr, &cell);
3471 }
3472 else
3473 dump_is_corrupt(&ga_text);
3474
3475 /* is_bg == 0: fg, is_bg == 1: bg */
3476 for (is_bg = 0; is_bg <= 1; ++is_bg)
3477 {
3478 if (c == '&')
3479 {
3480 /* use same color as previous cell */
3481 c = fgetc(fd);
3482 }
3483 else if (c == '#')
3484 {
3485 int red, green, blue, index = 0;
3486
3487 c = fgetc(fd);
3488 red = hex2nr(c);
3489 c = fgetc(fd);
3490 red = (red << 4) + hex2nr(c);
3491 c = fgetc(fd);
3492 green = hex2nr(c);
3493 c = fgetc(fd);
3494 green = (green << 4) + hex2nr(c);
3495 c = fgetc(fd);
3496 blue = hex2nr(c);
3497 c = fgetc(fd);
3498 blue = (blue << 4) + hex2nr(c);
3499 c = fgetc(fd);
3500 if (!isdigit(c))
3501 dump_is_corrupt(&ga_text);
3502 while (isdigit(c))
3503 {
3504 index = index * 10 + (c - '0');
3505 c = fgetc(fd);
3506 }
3507
3508 if (is_bg)
3509 {
3510 cell.bg.red = red;
3511 cell.bg.green = green;
3512 cell.bg.blue = blue;
3513 cell.bg.ansi_index = index;
3514 }
3515 else
3516 {
3517 cell.fg.red = red;
3518 cell.fg.green = green;
3519 cell.fg.blue = blue;
3520 cell.fg.ansi_index = index;
3521 }
3522 }
3523 else
3524 dump_is_corrupt(&ga_text);
3525 }
3526 }
3527 else
3528 dump_is_corrupt(&ga_text);
3529
3530 append_cell(&ga_cell, &cell);
3531 }
3532 else if (c == '@')
3533 {
3534 if (prev_char == NULL)
3535 dump_is_corrupt(&ga_text);
3536 else
3537 {
3538 int count = 0;
3539
3540 /* repeat previous character, get the count */
3541 for (;;)
3542 {
3543 c = fgetc(fd);
3544 if (!isdigit(c))
3545 break;
3546 count = count * 10 + (c - '0');
3547 }
3548
3549 while (count-- > 0)
3550 {
3551 ga_concat(&ga_text, prev_char);
3552 append_cell(&ga_cell, &cell);
3553 }
3554 }
3555 }
3556 else
3557 {
3558 dump_is_corrupt(&ga_text);
3559 c = fgetc(fd);
3560 }
3561 }
3562
3563 if (ga_text.ga_len > 0)
3564 {
3565 /* trailing characters after last NL */
3566 dump_is_corrupt(&ga_text);
3567 ga_append(&ga_text, NUL);
3568 ml_append(curbuf->b_ml.ml_line_count, ga_text.ga_data,
3569 ga_text.ga_len, FALSE);
3570 }
3571
3572 ga_clear(&ga_text);
3573 vim_free(prev_char);
3574
3575 return max_cells;
3576}
3577
3578/*
3579 * Common for "term_dumpdiff()" and "term_dumpload()".
3580 */
3581 static void
3582term_load_dump(typval_T *argvars, typval_T *rettv, int do_diff)
3583{
3584 jobopt_T opt;
3585 buf_T *buf;
3586 char_u buf1[NUMBUFLEN];
3587 char_u buf2[NUMBUFLEN];
3588 char_u *fname1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003589 char_u *fname2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003590 FILE *fd1;
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003591 FILE *fd2 = NULL;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003592 char_u *textline = NULL;
3593
3594 /* First open the files. If this fails bail out. */
3595 fname1 = get_tv_string_buf_chk(&argvars[0], buf1);
3596 if (do_diff)
3597 fname2 = get_tv_string_buf_chk(&argvars[1], buf2);
3598 if (fname1 == NULL || (do_diff && fname2 == NULL))
3599 {
3600 EMSG(_(e_invarg));
3601 return;
3602 }
3603 fd1 = mch_fopen((char *)fname1, READBIN);
3604 if (fd1 == NULL)
3605 {
3606 EMSG2(_(e_notread), fname1);
3607 return;
3608 }
3609 if (do_diff)
3610 {
3611 fd2 = mch_fopen((char *)fname2, READBIN);
3612 if (fd2 == NULL)
3613 {
3614 fclose(fd1);
3615 EMSG2(_(e_notread), fname2);
3616 return;
3617 }
3618 }
3619
3620 init_job_options(&opt);
3621 /* TODO: use the {options} argument */
3622
3623 /* TODO: use the file name arguments for the buffer name */
3624 opt.jo_term_name = (char_u *)"dump diff";
3625
3626 buf = term_start(&argvars[0], &opt, TRUE, FALSE);
3627 if (buf != NULL && buf->b_term != NULL)
3628 {
3629 int i;
3630 linenr_T bot_lnum;
3631 linenr_T lnum;
3632 term_T *term = buf->b_term;
3633 int width;
3634 int width2;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003635 VTermPos cursor_pos1;
3636 VTermPos cursor_pos2;
Bram Moolenaard96ff162018-02-18 22:13:29 +01003637
3638 rettv->vval.v_number = buf->b_fnum;
3639
3640 /* read the files, fill the buffer with the diff */
Bram Moolenaar9271d052018-02-25 21:39:46 +01003641 width = read_dump_file(fd1, &cursor_pos1);
3642
3643 /* position the cursor */
3644 if (cursor_pos1.row >= 0)
3645 {
3646 curwin->w_cursor.lnum = cursor_pos1.row + 1;
3647 coladvance(cursor_pos1.col);
3648 }
Bram Moolenaard96ff162018-02-18 22:13:29 +01003649
3650 /* Delete the empty line that was in the empty buffer. */
3651 ml_delete(1, FALSE);
3652
3653 /* For term_dumpload() we are done here. */
3654 if (!do_diff)
3655 goto theend;
3656
3657 term->tl_top_diff_rows = curbuf->b_ml.ml_line_count;
3658
3659 textline = alloc(width + 1);
3660 if (textline == NULL)
3661 goto theend;
3662 for (i = 0; i < width; ++i)
3663 textline[i] = '=';
3664 textline[width] = NUL;
3665 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3666 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3667 if (add_empty_scrollback(term, &term->tl_default_color, 0) == OK)
3668 ml_append(curbuf->b_ml.ml_line_count, textline, 0, FALSE);
3669
3670 bot_lnum = curbuf->b_ml.ml_line_count;
Bram Moolenaar9271d052018-02-25 21:39:46 +01003671 width2 = read_dump_file(fd2, &cursor_pos2);
Bram Moolenaard96ff162018-02-18 22:13:29 +01003672 if (width2 > width)
3673 {
3674 vim_free(textline);
3675 textline = alloc(width2 + 1);
3676 if (textline == NULL)
3677 goto theend;
3678 width = width2;
3679 textline[width] = NUL;
3680 }
3681 term->tl_bot_diff_rows = curbuf->b_ml.ml_line_count - bot_lnum;
3682
3683 for (lnum = 1; lnum <= term->tl_top_diff_rows; ++lnum)
3684 {
3685 if (lnum + bot_lnum > curbuf->b_ml.ml_line_count)
3686 {
3687 /* bottom part has fewer rows, fill with "-" */
3688 for (i = 0; i < width; ++i)
3689 textline[i] = '-';
3690 }
3691 else
3692 {
3693 char_u *line1;
3694 char_u *line2;
3695 char_u *p1;
3696 char_u *p2;
3697 int col;
3698 sb_line_T *sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3699 cellattr_T *cellattr1 = (sb_line + lnum - 1)->sb_cells;
3700 cellattr_T *cellattr2 = (sb_line + lnum + bot_lnum - 1)
3701 ->sb_cells;
3702
3703 /* Make a copy, getting the second line will invalidate it. */
3704 line1 = vim_strsave(ml_get(lnum));
3705 if (line1 == NULL)
3706 break;
3707 p1 = line1;
3708
3709 line2 = ml_get(lnum + bot_lnum);
3710 p2 = line2;
3711 for (col = 0; col < width && *p1 != NUL && *p2 != NUL; ++col)
3712 {
3713 int len1 = utfc_ptr2len(p1);
3714 int len2 = utfc_ptr2len(p2);
3715
3716 textline[col] = ' ';
3717 if (len1 != len2 || STRNCMP(p1, p2, len1) != 0)
Bram Moolenaar9271d052018-02-25 21:39:46 +01003718 /* text differs */
Bram Moolenaard96ff162018-02-18 22:13:29 +01003719 textline[col] = 'X';
Bram Moolenaar9271d052018-02-25 21:39:46 +01003720 else if (lnum == cursor_pos1.row + 1
3721 && col == cursor_pos1.col
3722 && (cursor_pos1.row != cursor_pos2.row
3723 || cursor_pos1.col != cursor_pos2.col))
3724 /* cursor in first but not in second */
3725 textline[col] = '>';
3726 else if (lnum == cursor_pos2.row + 1
3727 && col == cursor_pos2.col
3728 && (cursor_pos1.row != cursor_pos2.row
3729 || cursor_pos1.col != cursor_pos2.col))
3730 /* cursor in second but not in first */
3731 textline[col] = '<';
Bram Moolenaard96ff162018-02-18 22:13:29 +01003732 else if (cellattr1 != NULL && cellattr2 != NULL)
3733 {
3734 if ((cellattr1 + col)->width
3735 != (cellattr2 + col)->width)
3736 textline[col] = 'w';
3737 else if (!same_color(&(cellattr1 + col)->fg,
3738 &(cellattr2 + col)->fg))
3739 textline[col] = 'f';
3740 else if (!same_color(&(cellattr1 + col)->bg,
3741 &(cellattr2 + col)->bg))
3742 textline[col] = 'b';
3743 else if (vtermAttr2hl((cellattr1 + col)->attrs)
3744 != vtermAttr2hl(((cellattr2 + col)->attrs)))
3745 textline[col] = 'a';
3746 }
3747 p1 += len1;
3748 p2 += len2;
3749 /* TODO: handle different width */
3750 }
3751 vim_free(line1);
3752
3753 while (col < width)
3754 {
3755 if (*p1 == NUL && *p2 == NUL)
3756 textline[col] = '?';
3757 else if (*p1 == NUL)
3758 {
3759 textline[col] = '+';
3760 p2 += utfc_ptr2len(p2);
3761 }
3762 else
3763 {
3764 textline[col] = '-';
3765 p1 += utfc_ptr2len(p1);
3766 }
3767 ++col;
3768 }
3769 }
3770 if (add_empty_scrollback(term, &term->tl_default_color,
3771 term->tl_top_diff_rows) == OK)
3772 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3773 ++bot_lnum;
3774 }
3775
3776 while (lnum + bot_lnum <= curbuf->b_ml.ml_line_count)
3777 {
3778 /* bottom part has more rows, fill with "+" */
3779 for (i = 0; i < width; ++i)
3780 textline[i] = '+';
3781 if (add_empty_scrollback(term, &term->tl_default_color,
3782 term->tl_top_diff_rows) == OK)
3783 ml_append(term->tl_top_diff_rows + lnum, textline, 0, FALSE);
3784 ++lnum;
3785 ++bot_lnum;
3786 }
3787
3788 term->tl_cols = width;
3789 }
3790
3791theend:
3792 vim_free(textline);
3793 fclose(fd1);
Bram Moolenaar9c8816b2018-02-19 21:50:42 +01003794 if (fd2 != NULL)
Bram Moolenaard96ff162018-02-18 22:13:29 +01003795 fclose(fd2);
3796}
3797
3798/*
3799 * If the current buffer shows the output of term_dumpdiff(), swap the top and
3800 * bottom files.
3801 * Return FAIL when this is not possible.
3802 */
3803 int
3804term_swap_diff()
3805{
3806 term_T *term = curbuf->b_term;
3807 linenr_T line_count;
3808 linenr_T top_rows;
3809 linenr_T bot_rows;
3810 linenr_T bot_start;
3811 linenr_T lnum;
3812 char_u *p;
3813 sb_line_T *sb_line;
3814
3815 if (term == NULL
3816 || !term_is_finished(curbuf)
3817 || term->tl_top_diff_rows == 0
3818 || term->tl_scrollback.ga_len == 0)
3819 return FAIL;
3820
3821 line_count = curbuf->b_ml.ml_line_count;
3822 top_rows = term->tl_top_diff_rows;
3823 bot_rows = term->tl_bot_diff_rows;
3824 bot_start = line_count - bot_rows;
3825 sb_line = (sb_line_T *)term->tl_scrollback.ga_data;
3826
3827 /* move lines from top to above the bottom part */
3828 for (lnum = 1; lnum <= top_rows; ++lnum)
3829 {
3830 p = vim_strsave(ml_get(1));
3831 if (p == NULL)
3832 return OK;
3833 ml_append(bot_start, p, 0, FALSE);
3834 ml_delete(1, FALSE);
3835 vim_free(p);
3836 }
3837
3838 /* move lines from bottom to the top */
3839 for (lnum = 1; lnum <= bot_rows; ++lnum)
3840 {
3841 p = vim_strsave(ml_get(bot_start + lnum));
3842 if (p == NULL)
3843 return OK;
3844 ml_delete(bot_start + lnum, FALSE);
3845 ml_append(lnum - 1, p, 0, FALSE);
3846 vim_free(p);
3847 }
3848
3849 if (top_rows == bot_rows)
3850 {
3851 /* rows counts are equal, can swap cell properties */
3852 for (lnum = 0; lnum < top_rows; ++lnum)
3853 {
3854 sb_line_T temp;
3855
3856 temp = *(sb_line + lnum);
3857 *(sb_line + lnum) = *(sb_line + bot_start + lnum);
3858 *(sb_line + bot_start + lnum) = temp;
3859 }
3860 }
3861 else
3862 {
3863 size_t size = sizeof(sb_line_T) * term->tl_scrollback.ga_len;
3864 sb_line_T *temp = (sb_line_T *)alloc((int)size);
3865
3866 /* need to copy cell properties into temp memory */
3867 if (temp != NULL)
3868 {
3869 mch_memmove(temp, term->tl_scrollback.ga_data, size);
3870 mch_memmove(term->tl_scrollback.ga_data,
3871 temp + bot_start,
3872 sizeof(sb_line_T) * bot_rows);
3873 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data + bot_rows,
3874 temp + top_rows,
3875 sizeof(sb_line_T) * (line_count - top_rows - bot_rows));
3876 mch_memmove((sb_line_T *)term->tl_scrollback.ga_data
3877 + line_count - top_rows,
3878 temp,
3879 sizeof(sb_line_T) * top_rows);
3880 vim_free(temp);
3881 }
3882 }
3883
3884 term->tl_top_diff_rows = bot_rows;
3885 term->tl_bot_diff_rows = top_rows;
3886
3887 update_screen(NOT_VALID);
3888 return OK;
3889}
3890
3891/*
3892 * "term_dumpdiff(filename, filename, options)" function
3893 */
3894 void
3895f_term_dumpdiff(typval_T *argvars, typval_T *rettv)
3896{
3897 term_load_dump(argvars, rettv, TRUE);
3898}
3899
3900/*
3901 * "term_dumpload(filename, options)" function
3902 */
3903 void
3904f_term_dumpload(typval_T *argvars, typval_T *rettv)
3905{
3906 term_load_dump(argvars, rettv, FALSE);
3907}
3908
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003909/*
3910 * "term_getaltscreen(buf)" function
3911 */
3912 void
3913f_term_getaltscreen(typval_T *argvars, typval_T *rettv)
3914{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003915 buf_T *buf = term_get_buf(argvars, "term_getaltscreen()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003916
3917 if (buf == NULL)
3918 return;
3919 rettv->vval.v_number = buf->b_term->tl_using_altscreen;
3920}
3921
3922/*
3923 * "term_getattr(attr, name)" function
3924 */
3925 void
3926f_term_getattr(typval_T *argvars, typval_T *rettv)
3927{
3928 int attr;
3929 size_t i;
3930 char_u *name;
3931
3932 static struct {
3933 char *name;
3934 int attr;
3935 } attrs[] = {
3936 {"bold", HL_BOLD},
3937 {"italic", HL_ITALIC},
3938 {"underline", HL_UNDERLINE},
3939 {"strike", HL_STRIKETHROUGH},
3940 {"reverse", HL_INVERSE},
3941 };
3942
3943 attr = get_tv_number(&argvars[0]);
3944 name = get_tv_string_chk(&argvars[1]);
3945 if (name == NULL)
3946 return;
3947
3948 for (i = 0; i < sizeof(attrs)/sizeof(attrs[0]); ++i)
3949 if (STRCMP(name, attrs[i].name) == 0)
3950 {
3951 rettv->vval.v_number = (attr & attrs[i].attr) != 0 ? 1 : 0;
3952 break;
3953 }
3954}
3955
3956/*
3957 * "term_getcursor(buf)" function
3958 */
3959 void
3960f_term_getcursor(typval_T *argvars, typval_T *rettv)
3961{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003962 buf_T *buf = term_get_buf(argvars, "term_getcursor()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003963 term_T *term;
3964 list_T *l;
3965 dict_T *d;
3966
3967 if (rettv_list_alloc(rettv) == FAIL)
3968 return;
3969 if (buf == NULL)
3970 return;
3971 term = buf->b_term;
3972
3973 l = rettv->vval.v_list;
3974 list_append_number(l, term->tl_cursor_pos.row + 1);
3975 list_append_number(l, term->tl_cursor_pos.col + 1);
3976
3977 d = dict_alloc();
3978 if (d != NULL)
3979 {
3980 dict_add_nr_str(d, "visible", term->tl_cursor_visible, NULL);
3981 dict_add_nr_str(d, "blink", blink_state_is_inverted()
3982 ? !term->tl_cursor_blink : term->tl_cursor_blink, NULL);
3983 dict_add_nr_str(d, "shape", term->tl_cursor_shape, NULL);
3984 dict_add_nr_str(d, "color", 0L, term->tl_cursor_color == NULL
3985 ? (char_u *)"" : term->tl_cursor_color);
3986 list_append_dict(l, d);
3987 }
3988}
3989
3990/*
3991 * "term_getjob(buf)" function
3992 */
3993 void
3994f_term_getjob(typval_T *argvars, typval_T *rettv)
3995{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01003996 buf_T *buf = term_get_buf(argvars, "term_getjob()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02003997
3998 rettv->v_type = VAR_JOB;
3999 rettv->vval.v_job = NULL;
4000 if (buf == NULL)
4001 return;
4002
4003 rettv->vval.v_job = buf->b_term->tl_job;
4004 if (rettv->vval.v_job != NULL)
4005 ++rettv->vval.v_job->jv_refcount;
4006}
4007
4008 static int
4009get_row_number(typval_T *tv, term_T *term)
4010{
4011 if (tv->v_type == VAR_STRING
4012 && tv->vval.v_string != NULL
4013 && STRCMP(tv->vval.v_string, ".") == 0)
4014 return term->tl_cursor_pos.row;
4015 return (int)get_tv_number(tv) - 1;
4016}
4017
4018/*
4019 * "term_getline(buf, row)" function
4020 */
4021 void
4022f_term_getline(typval_T *argvars, typval_T *rettv)
4023{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004024 buf_T *buf = term_get_buf(argvars, "term_getline()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004025 term_T *term;
4026 int row;
4027
4028 rettv->v_type = VAR_STRING;
4029 if (buf == NULL)
4030 return;
4031 term = buf->b_term;
4032 row = get_row_number(&argvars[1], term);
4033
4034 if (term->tl_vterm == NULL)
4035 {
4036 linenr_T lnum = row + term->tl_scrollback_scrolled + 1;
4037
4038 /* vterm is finished, get the text from the buffer */
4039 if (lnum > 0 && lnum <= buf->b_ml.ml_line_count)
4040 rettv->vval.v_string = vim_strsave(ml_get_buf(buf, lnum, FALSE));
4041 }
4042 else
4043 {
4044 VTermScreen *screen = vterm_obtain_screen(term->tl_vterm);
4045 VTermRect rect;
4046 int len;
4047 char_u *p;
4048
4049 if (row < 0 || row >= term->tl_rows)
4050 return;
4051 len = term->tl_cols * MB_MAXBYTES + 1;
4052 p = alloc(len);
4053 if (p == NULL)
4054 return;
4055 rettv->vval.v_string = p;
4056
4057 rect.start_col = 0;
4058 rect.end_col = term->tl_cols;
4059 rect.start_row = row;
4060 rect.end_row = row + 1;
4061 p[vterm_screen_get_text(screen, (char *)p, len, rect)] = NUL;
4062 }
4063}
4064
4065/*
4066 * "term_getscrolled(buf)" function
4067 */
4068 void
4069f_term_getscrolled(typval_T *argvars, typval_T *rettv)
4070{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004071 buf_T *buf = term_get_buf(argvars, "term_getscrolled()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004072
4073 if (buf == NULL)
4074 return;
4075 rettv->vval.v_number = buf->b_term->tl_scrollback_scrolled;
4076}
4077
4078/*
4079 * "term_getsize(buf)" function
4080 */
4081 void
4082f_term_getsize(typval_T *argvars, typval_T *rettv)
4083{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004084 buf_T *buf = term_get_buf(argvars, "term_getsize()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004085 list_T *l;
4086
4087 if (rettv_list_alloc(rettv) == FAIL)
4088 return;
4089 if (buf == NULL)
4090 return;
4091
4092 l = rettv->vval.v_list;
4093 list_append_number(l, buf->b_term->tl_rows);
4094 list_append_number(l, buf->b_term->tl_cols);
4095}
4096
4097/*
4098 * "term_getstatus(buf)" function
4099 */
4100 void
4101f_term_getstatus(typval_T *argvars, typval_T *rettv)
4102{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004103 buf_T *buf = term_get_buf(argvars, "term_getstatus()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004104 term_T *term;
4105 char_u val[100];
4106
4107 rettv->v_type = VAR_STRING;
4108 if (buf == NULL)
4109 return;
4110 term = buf->b_term;
4111
4112 if (term_job_running(term))
4113 STRCPY(val, "running");
4114 else
4115 STRCPY(val, "finished");
4116 if (term->tl_normal_mode)
4117 STRCAT(val, ",normal");
4118 rettv->vval.v_string = vim_strsave(val);
4119}
4120
4121/*
4122 * "term_gettitle(buf)" function
4123 */
4124 void
4125f_term_gettitle(typval_T *argvars, typval_T *rettv)
4126{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004127 buf_T *buf = term_get_buf(argvars, "term_gettitle()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004128
4129 rettv->v_type = VAR_STRING;
4130 if (buf == NULL)
4131 return;
4132
4133 if (buf->b_term->tl_title != NULL)
4134 rettv->vval.v_string = vim_strsave(buf->b_term->tl_title);
4135}
4136
4137/*
4138 * "term_gettty(buf)" function
4139 */
4140 void
4141f_term_gettty(typval_T *argvars, typval_T *rettv)
4142{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004143 buf_T *buf = term_get_buf(argvars, "term_gettty()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004144 char_u *p;
4145 int num = 0;
4146
4147 rettv->v_type = VAR_STRING;
4148 if (buf == NULL)
4149 return;
4150 if (argvars[1].v_type != VAR_UNKNOWN)
4151 num = get_tv_number(&argvars[1]);
4152
4153 switch (num)
4154 {
4155 case 0:
4156 if (buf->b_term->tl_job != NULL)
4157 p = buf->b_term->tl_job->jv_tty_out;
4158 else
4159 p = buf->b_term->tl_tty_out;
4160 break;
4161 case 1:
4162 if (buf->b_term->tl_job != NULL)
4163 p = buf->b_term->tl_job->jv_tty_in;
4164 else
4165 p = buf->b_term->tl_tty_in;
4166 break;
4167 default:
4168 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
4169 return;
4170 }
4171 if (p != NULL)
4172 rettv->vval.v_string = vim_strsave(p);
4173}
4174
4175/*
4176 * "term_list()" function
4177 */
4178 void
4179f_term_list(typval_T *argvars UNUSED, typval_T *rettv)
4180{
4181 term_T *tp;
4182 list_T *l;
4183
4184 if (rettv_list_alloc(rettv) == FAIL || first_term == NULL)
4185 return;
4186
4187 l = rettv->vval.v_list;
4188 for (tp = first_term; tp != NULL; tp = tp->tl_next)
4189 if (tp != NULL && tp->tl_buffer != NULL)
4190 if (list_append_number(l,
4191 (varnumber_T)tp->tl_buffer->b_fnum) == FAIL)
4192 return;
4193}
4194
4195/*
4196 * "term_scrape(buf, row)" function
4197 */
4198 void
4199f_term_scrape(typval_T *argvars, typval_T *rettv)
4200{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004201 buf_T *buf = term_get_buf(argvars, "term_scrape()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004202 VTermScreen *screen = NULL;
4203 VTermPos pos;
4204 list_T *l;
4205 term_T *term;
4206 char_u *p;
4207 sb_line_T *line;
4208
4209 if (rettv_list_alloc(rettv) == FAIL)
4210 return;
4211 if (buf == NULL)
4212 return;
4213 term = buf->b_term;
4214
4215 l = rettv->vval.v_list;
4216 pos.row = get_row_number(&argvars[1], term);
4217
4218 if (term->tl_vterm != NULL)
4219 {
4220 screen = vterm_obtain_screen(term->tl_vterm);
4221 p = NULL;
4222 line = NULL;
4223 }
4224 else
4225 {
4226 linenr_T lnum = pos.row + term->tl_scrollback_scrolled;
4227
4228 if (lnum < 0 || lnum >= term->tl_scrollback.ga_len)
4229 return;
4230 p = ml_get_buf(buf, lnum + 1, FALSE);
4231 line = (sb_line_T *)term->tl_scrollback.ga_data + lnum;
4232 }
4233
4234 for (pos.col = 0; pos.col < term->tl_cols; )
4235 {
4236 dict_T *dcell;
4237 int width;
4238 VTermScreenCellAttrs attrs;
4239 VTermColor fg, bg;
4240 char_u rgb[8];
4241 char_u mbs[MB_MAXBYTES * VTERM_MAX_CHARS_PER_CELL + 1];
4242 int off = 0;
4243 int i;
4244
4245 if (screen == NULL)
4246 {
4247 cellattr_T *cellattr;
4248 int len;
4249
4250 /* vterm has finished, get the cell from scrollback */
4251 if (pos.col >= line->sb_cols)
4252 break;
4253 cellattr = line->sb_cells + pos.col;
4254 width = cellattr->width;
4255 attrs = cellattr->attrs;
4256 fg = cellattr->fg;
4257 bg = cellattr->bg;
4258 len = MB_PTR2LEN(p);
4259 mch_memmove(mbs, p, len);
4260 mbs[len] = NUL;
4261 p += len;
4262 }
4263 else
4264 {
4265 VTermScreenCell cell;
4266 if (vterm_screen_get_cell(screen, pos, &cell) == 0)
4267 break;
4268 for (i = 0; i < VTERM_MAX_CHARS_PER_CELL; ++i)
4269 {
4270 if (cell.chars[i] == 0)
4271 break;
4272 off += (*utf_char2bytes)((int)cell.chars[i], mbs + off);
4273 }
4274 mbs[off] = NUL;
4275 width = cell.width;
4276 attrs = cell.attrs;
4277 fg = cell.fg;
4278 bg = cell.bg;
4279 }
4280 dcell = dict_alloc();
Bram Moolenaar4b7e7be2018-02-11 14:53:30 +01004281 if (dcell == NULL)
4282 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004283 list_append_dict(l, dcell);
4284
4285 dict_add_nr_str(dcell, "chars", 0, mbs);
4286
4287 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4288 fg.red, fg.green, fg.blue);
4289 dict_add_nr_str(dcell, "fg", 0, rgb);
4290 vim_snprintf((char *)rgb, 8, "#%02x%02x%02x",
4291 bg.red, bg.green, bg.blue);
4292 dict_add_nr_str(dcell, "bg", 0, rgb);
4293
4294 dict_add_nr_str(dcell, "attr",
4295 cell2attr(attrs, fg, bg), NULL);
4296 dict_add_nr_str(dcell, "width", width, NULL);
4297
4298 ++pos.col;
4299 if (width == 2)
4300 ++pos.col;
4301 }
4302}
4303
4304/*
4305 * "term_sendkeys(buf, keys)" function
4306 */
4307 void
4308f_term_sendkeys(typval_T *argvars, typval_T *rettv)
4309{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004310 buf_T *buf = term_get_buf(argvars, "term_sendkeys()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004311 char_u *msg;
4312 term_T *term;
4313
4314 rettv->v_type = VAR_UNKNOWN;
4315 if (buf == NULL)
4316 return;
4317
4318 msg = get_tv_string_chk(&argvars[1]);
4319 if (msg == NULL)
4320 return;
4321 term = buf->b_term;
4322 if (term->tl_vterm == NULL)
4323 return;
4324
4325 while (*msg != NUL)
4326 {
4327 send_keys_to_term(term, PTR2CHAR(msg), FALSE);
Bram Moolenaar6daeef12017-10-15 22:56:49 +02004328 msg += MB_CPTR2LEN(msg);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004329 }
4330}
4331
4332/*
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004333 * "term_setrestore(buf, command)" function
4334 */
4335 void
4336f_term_setrestore(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4337{
4338#if defined(FEAT_SESSION)
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004339 buf_T *buf = term_get_buf(argvars, "term_setrestore()");
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004340 term_T *term;
4341 char_u *cmd;
4342
4343 if (buf == NULL)
4344 return;
4345 term = buf->b_term;
4346 vim_free(term->tl_command);
4347 cmd = get_tv_string_chk(&argvars[1]);
4348 if (cmd != NULL)
4349 term->tl_command = vim_strsave(cmd);
4350 else
4351 term->tl_command = NULL;
4352#endif
4353}
4354
4355/*
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004356 * "term_setkill(buf, how)" function
4357 */
4358 void
4359f_term_setkill(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
4360{
4361 buf_T *buf = term_get_buf(argvars, "term_setkill()");
4362 term_T *term;
4363 char_u *how;
4364
4365 if (buf == NULL)
4366 return;
4367 term = buf->b_term;
4368 vim_free(term->tl_kill);
4369 how = get_tv_string_chk(&argvars[1]);
4370 if (how != NULL)
4371 term->tl_kill = vim_strsave(how);
4372 else
4373 term->tl_kill = NULL;
4374}
4375
4376/*
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004377 * "term_start(command, options)" function
4378 */
4379 void
4380f_term_start(typval_T *argvars, typval_T *rettv)
4381{
4382 jobopt_T opt;
4383 buf_T *buf;
4384
4385 init_job_options(&opt);
4386 if (argvars[1].v_type != VAR_UNKNOWN
4387 && get_job_options(&argvars[1], &opt,
4388 JO_TIMEOUT_ALL + JO_STOPONEXIT
4389 + JO_CALLBACK + JO_OUT_CALLBACK + JO_ERR_CALLBACK
4390 + JO_EXIT_CB + JO_CLOSE_CALLBACK + JO_OUT_IO,
4391 JO2_TERM_NAME + JO2_TERM_FINISH + JO2_HIDDEN + JO2_TERM_OPENCMD
4392 + JO2_TERM_COLS + JO2_TERM_ROWS + JO2_VERTICAL + JO2_CURWIN
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004393 + JO2_CWD + JO2_ENV + JO2_EOF_CHARS
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004394 + JO2_NORESTORE + JO2_TERM_KILL) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004395 return;
4396
4397 if (opt.jo_vertical)
4398 cmdmod.split = WSP_VERT;
Bram Moolenaard96ff162018-02-18 22:13:29 +01004399 buf = term_start(&argvars[0], &opt, FALSE, FALSE);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004400
4401 if (buf != NULL && buf->b_term != NULL)
4402 rettv->vval.v_number = buf->b_fnum;
4403}
4404
4405/*
4406 * "term_wait" function
4407 */
4408 void
4409f_term_wait(typval_T *argvars, typval_T *rettv UNUSED)
4410{
Bram Moolenaar25cdd9c2018-03-10 20:28:12 +01004411 buf_T *buf = term_get_buf(argvars, "term_wait()");
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004412
4413 if (buf == NULL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004414 return;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004415 if (buf->b_term->tl_job == NULL)
4416 {
4417 ch_log(NULL, "term_wait(): no job to wait for");
4418 return;
4419 }
4420 if (buf->b_term->tl_job->jv_channel == NULL)
4421 /* channel is closed, nothing to do */
4422 return;
4423
4424 /* Get the job status, this will detect a job that finished. */
Bram Moolenaara15ef452018-02-09 16:46:00 +01004425 if (!buf->b_term->tl_job->jv_channel->ch_keep_open
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004426 && STRCMP(job_status(buf->b_term->tl_job), "dead") == 0)
4427 {
4428 /* The job is dead, keep reading channel I/O until the channel is
4429 * closed. buf->b_term may become NULL if the terminal was closed while
4430 * waiting. */
4431 ch_log(NULL, "term_wait(): waiting for channel to close");
4432 while (buf->b_term != NULL && !buf->b_term->tl_channel_closed)
4433 {
4434 mch_check_messages();
4435 parse_queued_messages();
Bram Moolenaare5182262017-11-19 15:05:44 +01004436 if (!buf_valid(buf))
4437 /* If the terminal is closed when the channel is closed the
4438 * buffer disappears. */
4439 break;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004440 ui_delay(10L, FALSE);
4441 }
4442 mch_check_messages();
4443 parse_queued_messages();
4444 }
4445 else
4446 {
4447 long wait = 10L;
4448
4449 mch_check_messages();
4450 parse_queued_messages();
4451
4452 /* Wait for some time for any channel I/O. */
4453 if (argvars[1].v_type != VAR_UNKNOWN)
4454 wait = get_tv_number(&argvars[1]);
4455 ui_delay(wait, TRUE);
4456 mch_check_messages();
4457
4458 /* Flushing messages on channels is hopefully sufficient.
4459 * TODO: is there a better way? */
4460 parse_queued_messages();
4461 }
4462}
4463
4464/*
4465 * Called when a channel has sent all the lines to a terminal.
4466 * Send a CTRL-D to mark the end of the text.
4467 */
4468 void
4469term_send_eof(channel_T *ch)
4470{
4471 term_T *term;
4472
4473 for (term = first_term; term != NULL; term = term->tl_next)
4474 if (term->tl_job == ch->ch_job)
4475 {
4476 if (term->tl_eof_chars != NULL)
4477 {
4478 channel_send(ch, PART_IN, term->tl_eof_chars,
4479 (int)STRLEN(term->tl_eof_chars), NULL);
4480 channel_send(ch, PART_IN, (char_u *)"\r", 1, NULL);
4481 }
4482# ifdef WIN3264
4483 else
4484 /* Default: CTRL-D */
4485 channel_send(ch, PART_IN, (char_u *)"\004\r", 2, NULL);
4486# endif
4487 }
4488}
4489
4490# if defined(WIN3264) || defined(PROTO)
4491
4492/**************************************
4493 * 2. MS-Windows implementation.
4494 */
4495
4496# ifndef PROTO
4497
4498#define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ul
4499#define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull
Bram Moolenaard317b382018-02-08 22:33:31 +01004500#define WINPTY_MOUSE_MODE_FORCE 2
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004501
4502void* (*winpty_config_new)(UINT64, void*);
4503void* (*winpty_open)(void*, void*);
4504void* (*winpty_spawn_config_new)(UINT64, void*, LPCWSTR, void*, void*, void*);
4505BOOL (*winpty_spawn)(void*, void*, HANDLE*, HANDLE*, DWORD*, void*);
4506void (*winpty_config_set_mouse_mode)(void*, int);
4507void (*winpty_config_set_initial_size)(void*, int, int);
4508LPCWSTR (*winpty_conin_name)(void*);
4509LPCWSTR (*winpty_conout_name)(void*);
4510LPCWSTR (*winpty_conerr_name)(void*);
4511void (*winpty_free)(void*);
4512void (*winpty_config_free)(void*);
4513void (*winpty_spawn_config_free)(void*);
4514void (*winpty_error_free)(void*);
4515LPCWSTR (*winpty_error_msg)(void*);
4516BOOL (*winpty_set_size)(void*, int, int, void*);
4517HANDLE (*winpty_agent_process)(void*);
4518
4519#define WINPTY_DLL "winpty.dll"
4520
4521static HINSTANCE hWinPtyDLL = NULL;
4522# endif
4523
4524 static int
4525dyn_winpty_init(int verbose)
4526{
4527 int i;
4528 static struct
4529 {
4530 char *name;
4531 FARPROC *ptr;
4532 } winpty_entry[] =
4533 {
4534 {"winpty_conerr_name", (FARPROC*)&winpty_conerr_name},
4535 {"winpty_config_free", (FARPROC*)&winpty_config_free},
4536 {"winpty_config_new", (FARPROC*)&winpty_config_new},
4537 {"winpty_config_set_mouse_mode",
4538 (FARPROC*)&winpty_config_set_mouse_mode},
4539 {"winpty_config_set_initial_size",
4540 (FARPROC*)&winpty_config_set_initial_size},
4541 {"winpty_conin_name", (FARPROC*)&winpty_conin_name},
4542 {"winpty_conout_name", (FARPROC*)&winpty_conout_name},
4543 {"winpty_error_free", (FARPROC*)&winpty_error_free},
4544 {"winpty_free", (FARPROC*)&winpty_free},
4545 {"winpty_open", (FARPROC*)&winpty_open},
4546 {"winpty_spawn", (FARPROC*)&winpty_spawn},
4547 {"winpty_spawn_config_free", (FARPROC*)&winpty_spawn_config_free},
4548 {"winpty_spawn_config_new", (FARPROC*)&winpty_spawn_config_new},
4549 {"winpty_error_msg", (FARPROC*)&winpty_error_msg},
4550 {"winpty_set_size", (FARPROC*)&winpty_set_size},
4551 {"winpty_agent_process", (FARPROC*)&winpty_agent_process},
4552 {NULL, NULL}
4553 };
4554
4555 /* No need to initialize twice. */
4556 if (hWinPtyDLL)
4557 return OK;
4558 /* Load winpty.dll, prefer using the 'winptydll' option, fall back to just
4559 * winpty.dll. */
4560 if (*p_winptydll != NUL)
4561 hWinPtyDLL = vimLoadLib((char *)p_winptydll);
4562 if (!hWinPtyDLL)
4563 hWinPtyDLL = vimLoadLib(WINPTY_DLL);
4564 if (!hWinPtyDLL)
4565 {
4566 if (verbose)
4567 EMSG2(_(e_loadlib), *p_winptydll != NUL ? p_winptydll
4568 : (char_u *)WINPTY_DLL);
4569 return FAIL;
4570 }
4571 for (i = 0; winpty_entry[i].name != NULL
4572 && winpty_entry[i].ptr != NULL; ++i)
4573 {
4574 if ((*winpty_entry[i].ptr = (FARPROC)GetProcAddress(hWinPtyDLL,
4575 winpty_entry[i].name)) == NULL)
4576 {
4577 if (verbose)
4578 EMSG2(_(e_loadfunc), winpty_entry[i].name);
4579 return FAIL;
4580 }
4581 }
4582
4583 return OK;
4584}
4585
4586/*
4587 * Create a new terminal of "rows" by "cols" cells.
4588 * Store a reference in "term".
4589 * Return OK or FAIL.
4590 */
4591 static int
4592term_and_job_init(
4593 term_T *term,
4594 typval_T *argvar,
4595 jobopt_T *opt)
4596{
4597 WCHAR *cmd_wchar = NULL;
4598 WCHAR *cwd_wchar = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004599 WCHAR *env_wchar = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004600 channel_T *channel = NULL;
4601 job_T *job = NULL;
4602 DWORD error;
4603 HANDLE jo = NULL;
4604 HANDLE child_process_handle;
4605 HANDLE child_thread_handle;
Bram Moolenaar4aad53c2018-01-26 21:11:03 +01004606 void *winpty_err = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004607 void *spawn_config = NULL;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004608 garray_T ga_cmd, ga_env;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004609 char_u *cmd = NULL;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004610
4611 if (dyn_winpty_init(TRUE) == FAIL)
4612 return FAIL;
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004613 ga_init2(&ga_cmd, (int)sizeof(char*), 20);
4614 ga_init2(&ga_env, (int)sizeof(char*), 20);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004615
4616 if (argvar->v_type == VAR_STRING)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004617 {
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004618 cmd = argvar->vval.v_string;
4619 }
4620 else if (argvar->v_type == VAR_LIST)
4621 {
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004622 if (win32_build_cmd(argvar->vval.v_list, &ga_cmd) == FAIL)
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004623 goto failed;
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004624 cmd = ga_cmd.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004625 }
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004626 if (cmd == NULL || *cmd == NUL)
4627 {
4628 EMSG(_(e_invarg));
4629 goto failed;
4630 }
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004631
4632 cmd_wchar = enc_to_utf16(cmd, NULL);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004633 ga_clear(&ga_cmd);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004634 if (cmd_wchar == NULL)
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004635 goto failed;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004636 if (opt->jo_cwd != NULL)
4637 cwd_wchar = enc_to_utf16(opt->jo_cwd, NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004638
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004639 win32_build_env(opt->jo_env, &ga_env, TRUE);
4640 env_wchar = ga_env.ga_data;
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004641
4642 job = job_alloc();
4643 if (job == NULL)
4644 goto failed;
4645
4646 channel = add_channel();
4647 if (channel == NULL)
4648 goto failed;
4649
4650 term->tl_winpty_config = winpty_config_new(0, &winpty_err);
4651 if (term->tl_winpty_config == NULL)
4652 goto failed;
4653
4654 winpty_config_set_mouse_mode(term->tl_winpty_config,
4655 WINPTY_MOUSE_MODE_FORCE);
4656 winpty_config_set_initial_size(term->tl_winpty_config,
4657 term->tl_cols, term->tl_rows);
4658 term->tl_winpty = winpty_open(term->tl_winpty_config, &winpty_err);
4659 if (term->tl_winpty == NULL)
4660 goto failed;
4661
4662 spawn_config = winpty_spawn_config_new(
4663 WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN |
4664 WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN,
4665 NULL,
4666 cmd_wchar,
4667 cwd_wchar,
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004668 env_wchar,
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004669 &winpty_err);
4670 if (spawn_config == NULL)
4671 goto failed;
4672
4673 channel = add_channel();
4674 if (channel == NULL)
4675 goto failed;
4676
4677 job = job_alloc();
4678 if (job == NULL)
4679 goto failed;
4680
4681 if (opt->jo_set & JO_IN_BUF)
4682 job->jv_in_buf = buflist_findnr(opt->jo_io_buf[PART_IN]);
4683
4684 if (!winpty_spawn(term->tl_winpty, spawn_config, &child_process_handle,
4685 &child_thread_handle, &error, &winpty_err))
4686 goto failed;
4687
4688 channel_set_pipes(channel,
4689 (sock_T)CreateFileW(
4690 winpty_conin_name(term->tl_winpty),
4691 GENERIC_WRITE, 0, NULL,
4692 OPEN_EXISTING, 0, NULL),
4693 (sock_T)CreateFileW(
4694 winpty_conout_name(term->tl_winpty),
4695 GENERIC_READ, 0, NULL,
4696 OPEN_EXISTING, 0, NULL),
4697 (sock_T)CreateFileW(
4698 winpty_conerr_name(term->tl_winpty),
4699 GENERIC_READ, 0, NULL,
4700 OPEN_EXISTING, 0, NULL));
4701
4702 /* Write lines with CR instead of NL. */
4703 channel->ch_write_text_mode = TRUE;
4704
4705 jo = CreateJobObject(NULL, NULL);
4706 if (jo == NULL)
4707 goto failed;
4708
4709 if (!AssignProcessToJobObject(jo, child_process_handle))
4710 {
4711 /* Failed, switch the way to terminate process with TerminateProcess. */
4712 CloseHandle(jo);
4713 jo = NULL;
4714 }
4715
4716 winpty_spawn_config_free(spawn_config);
4717 vim_free(cmd_wchar);
4718 vim_free(cwd_wchar);
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004719 vim_free(env_wchar);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004720
4721 create_vterm(term, term->tl_rows, term->tl_cols);
4722
4723 channel_set_job(channel, job, opt);
4724 job_set_options(job, opt);
4725
4726 job->jv_channel = channel;
4727 job->jv_proc_info.hProcess = child_process_handle;
4728 job->jv_proc_info.dwProcessId = GetProcessId(child_process_handle);
4729 job->jv_job_object = jo;
4730 job->jv_status = JOB_STARTED;
4731 job->jv_tty_in = utf16_to_enc(
4732 (short_u*)winpty_conin_name(term->tl_winpty), NULL);
4733 job->jv_tty_out = utf16_to_enc(
4734 (short_u*)winpty_conout_name(term->tl_winpty), NULL);
4735 ++job->jv_refcount;
4736 term->tl_job = job;
4737
4738 return OK;
4739
4740failed:
Bram Moolenaarede35bb2018-01-26 20:05:18 +01004741 ga_clear(&ga_cmd);
4742 ga_clear(&ga_env);
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004743 vim_free(cmd_wchar);
4744 vim_free(cwd_wchar);
4745 if (spawn_config != NULL)
4746 winpty_spawn_config_free(spawn_config);
4747 if (channel != NULL)
4748 channel_clear(channel);
4749 if (job != NULL)
4750 {
4751 job->jv_channel = NULL;
4752 job_cleanup(job);
4753 }
4754 term->tl_job = NULL;
4755 if (jo != NULL)
4756 CloseHandle(jo);
4757 if (term->tl_winpty != NULL)
4758 winpty_free(term->tl_winpty);
4759 term->tl_winpty = NULL;
4760 if (term->tl_winpty_config != NULL)
4761 winpty_config_free(term->tl_winpty_config);
4762 term->tl_winpty_config = NULL;
4763 if (winpty_err != NULL)
4764 {
4765 char_u *msg = utf16_to_enc(
4766 (short_u *)winpty_error_msg(winpty_err), NULL);
4767
4768 EMSG(msg);
4769 winpty_error_free(winpty_err);
4770 }
4771 return FAIL;
4772}
4773
4774 static int
4775create_pty_only(term_T *term, jobopt_T *options)
4776{
4777 HANDLE hPipeIn = INVALID_HANDLE_VALUE;
4778 HANDLE hPipeOut = INVALID_HANDLE_VALUE;
4779 char in_name[80], out_name[80];
4780 channel_T *channel = NULL;
4781
4782 create_vterm(term, term->tl_rows, term->tl_cols);
4783
4784 vim_snprintf(in_name, sizeof(in_name), "\\\\.\\pipe\\vim-%d-in-%d",
4785 GetCurrentProcessId(),
4786 curbuf->b_fnum);
4787 hPipeIn = CreateNamedPipe(in_name, PIPE_ACCESS_OUTBOUND,
4788 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4789 PIPE_UNLIMITED_INSTANCES,
4790 0, 0, NMPWAIT_NOWAIT, NULL);
4791 if (hPipeIn == INVALID_HANDLE_VALUE)
4792 goto failed;
4793
4794 vim_snprintf(out_name, sizeof(out_name), "\\\\.\\pipe\\vim-%d-out-%d",
4795 GetCurrentProcessId(),
4796 curbuf->b_fnum);
4797 hPipeOut = CreateNamedPipe(out_name, PIPE_ACCESS_INBOUND,
4798 PIPE_TYPE_MESSAGE | PIPE_NOWAIT,
4799 PIPE_UNLIMITED_INSTANCES,
4800 0, 0, 0, NULL);
4801 if (hPipeOut == INVALID_HANDLE_VALUE)
4802 goto failed;
4803
4804 ConnectNamedPipe(hPipeIn, NULL);
4805 ConnectNamedPipe(hPipeOut, NULL);
4806
4807 term->tl_job = job_alloc();
4808 if (term->tl_job == NULL)
4809 goto failed;
4810 ++term->tl_job->jv_refcount;
4811
4812 /* behave like the job is already finished */
4813 term->tl_job->jv_status = JOB_FINISHED;
4814
4815 channel = add_channel();
4816 if (channel == NULL)
4817 goto failed;
4818 term->tl_job->jv_channel = channel;
4819 channel->ch_keep_open = TRUE;
4820 channel->ch_named_pipe = TRUE;
4821
4822 channel_set_pipes(channel,
4823 (sock_T)hPipeIn,
4824 (sock_T)hPipeOut,
4825 (sock_T)hPipeOut);
4826 channel_set_job(channel, term->tl_job, options);
4827 term->tl_job->jv_tty_in = vim_strsave((char_u*)in_name);
4828 term->tl_job->jv_tty_out = vim_strsave((char_u*)out_name);
4829
4830 return OK;
4831
4832failed:
4833 if (hPipeIn != NULL)
4834 CloseHandle(hPipeIn);
4835 if (hPipeOut != NULL)
4836 CloseHandle(hPipeOut);
4837 return FAIL;
4838}
4839
4840/*
4841 * Free the terminal emulator part of "term".
4842 */
4843 static void
4844term_free_vterm(term_T *term)
4845{
4846 if (term->tl_winpty != NULL)
4847 winpty_free(term->tl_winpty);
4848 term->tl_winpty = NULL;
4849 if (term->tl_winpty_config != NULL)
4850 winpty_config_free(term->tl_winpty_config);
4851 term->tl_winpty_config = NULL;
4852 if (term->tl_vterm != NULL)
4853 vterm_free(term->tl_vterm);
4854 term->tl_vterm = NULL;
4855}
4856
4857/*
4858 * Request size to terminal.
4859 */
4860 static void
4861term_report_winsize(term_T *term, int rows, int cols)
4862{
4863 if (term->tl_winpty)
4864 winpty_set_size(term->tl_winpty, cols, rows, NULL);
4865}
4866
4867 int
4868terminal_enabled(void)
4869{
4870 return dyn_winpty_init(FALSE) == OK;
4871}
4872
4873# else
4874
4875/**************************************
4876 * 3. Unix-like implementation.
4877 */
4878
4879/*
4880 * Create a new terminal of "rows" by "cols" cells.
4881 * Start job for "cmd".
4882 * Store the pointers in "term".
4883 * Return OK or FAIL.
4884 */
4885 static int
4886term_and_job_init(
4887 term_T *term,
4888 typval_T *argvar,
4889 jobopt_T *opt)
4890{
4891 create_vterm(term, term->tl_rows, term->tl_cols);
4892
Bram Moolenaar4d8bac82018-03-09 21:33:34 +01004893 /* This will change a string in "argvar". */
Bram Moolenaar2e6ab182017-09-20 10:03:07 +02004894 term->tl_job = job_start(argvar, opt);
4895 if (term->tl_job != NULL)
4896 ++term->tl_job->jv_refcount;
4897
4898 return term->tl_job != NULL
4899 && term->tl_job->jv_channel != NULL
4900 && term->tl_job->jv_status != JOB_FAILED ? OK : FAIL;
4901}
4902
4903 static int
4904create_pty_only(term_T *term, jobopt_T *opt)
4905{
4906 create_vterm(term, term->tl_rows, term->tl_cols);
4907
4908 term->tl_job = job_alloc();
4909 if (term->tl_job == NULL)
4910 return FAIL;
4911 ++term->tl_job->jv_refcount;
4912
4913 /* behave like the job is already finished */
4914 term->tl_job->jv_status = JOB_FINISHED;
4915
4916 return mch_create_pty_channel(term->tl_job, opt);
4917}
4918
4919/*
4920 * Free the terminal emulator part of "term".
4921 */
4922 static void
4923term_free_vterm(term_T *term)
4924{
4925 if (term->tl_vterm != NULL)
4926 vterm_free(term->tl_vterm);
4927 term->tl_vterm = NULL;
4928}
4929
4930/*
4931 * Request size to terminal.
4932 */
4933 static void
4934term_report_winsize(term_T *term, int rows, int cols)
4935{
4936 /* Use an ioctl() to report the new window size to the job. */
4937 if (term->tl_job != NULL && term->tl_job->jv_channel != NULL)
4938 {
4939 int fd = -1;
4940 int part;
4941
4942 for (part = PART_OUT; part < PART_COUNT; ++part)
4943 {
4944 fd = term->tl_job->jv_channel->ch_part[part].ch_fd;
4945 if (isatty(fd))
4946 break;
4947 }
4948 if (part < PART_COUNT && mch_report_winsize(fd, rows, cols) == OK)
4949 mch_signal_job(term->tl_job, (char_u *)"winch");
4950 }
4951}
4952
4953# endif
4954
4955#endif /* FEAT_TERMINAL */