xref: /netbsd-src/external/bsd/tmux/dist/status.c (revision 8450a7c42673d65e3b1f6560d3b6ecd317a6cbe8)
1 /* $OpenBSD$ */
2 
3 /*
4  * Copyright (c) 2007 Nicholas Marriott <nicholas.marriott@gmail.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15  * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/types.h>
20 #include <sys/time.h>
21 
22 #include <errno.h>
23 #include <limits.h>
24 #include <stdarg.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <time.h>
28 #include <unistd.h>
29 
30 #include "tmux.h"
31 
32 char   *status_redraw_get_left(struct client *, time_t, struct grid_cell *,
33 	    size_t *);
34 char   *status_redraw_get_right(struct client *, time_t, struct grid_cell *,
35 	    size_t *);
36 char   *status_print(struct client *, struct winlink *, time_t,
37 	    struct grid_cell *);
38 char   *status_replace(struct client *, struct winlink *, const char *, time_t);
39 void	status_message_callback(int, short, void *);
40 void	status_timer_callback(int, short, void *);
41 
42 const char *status_prompt_up_history(u_int *);
43 const char *status_prompt_down_history(u_int *);
44 void	status_prompt_add_history(const char *);
45 
46 const char **status_prompt_complete_list(u_int *, const char *);
47 char   *status_prompt_complete_prefix(const char **, u_int);
48 char   *status_prompt_complete(struct session *, const char *);
49 
50 char   *status_prompt_find_history_file(void);
51 
52 /* Status prompt history. */
53 #define PROMPT_HISTORY 100
54 char	**status_prompt_hlist;
55 u_int	  status_prompt_hsize;
56 
57 /* Find the history file to load/save from/to. */
58 char *
59 status_prompt_find_history_file(void)
60 {
61 	const char	*home, *history_file;
62 	char		*path;
63 
64 	history_file = options_get_string(global_options, "history-file");
65 	if (*history_file == '\0')
66 		return (NULL);
67 	if (*history_file == '/')
68 		return (xstrdup(history_file));
69 
70 	if (history_file[0] != '~' || history_file[1] != '/')
71 		return (NULL);
72 	if ((home = find_home()) == NULL)
73 		return (NULL);
74 	xasprintf(&path, "%s%s", home, history_file + 1);
75 	return (path);
76 }
77 
78 /* Load status prompt history from file. */
79 void
80 status_prompt_load_history(void)
81 {
82 	FILE	*f;
83 	char	*history_file, *line, *tmp;
84 	size_t	 length;
85 
86 	if ((history_file = status_prompt_find_history_file()) == NULL)
87 		return;
88 	log_debug("loading history from %s", history_file);
89 
90 	f = fopen(history_file, "r");
91 	if (f == NULL) {
92 		log_debug("%s: %s", history_file, strerror(errno));
93 		free(history_file);
94 		return;
95 	}
96 	free(history_file);
97 
98 	for (;;) {
99 		if ((line = fgetln(f, &length)) == NULL)
100 			break;
101 
102 		if (length > 0) {
103 			if (line[length - 1] == '\n') {
104 				line[length - 1] = '\0';
105 				status_prompt_add_history(line);
106 			} else {
107 				tmp = xmalloc(length + 1);
108 				memcpy(tmp, line, length);
109 				tmp[length] = '\0';
110 				status_prompt_add_history(tmp);
111 				free(tmp);
112 			}
113 		}
114 	}
115 	fclose(f);
116 }
117 
118 /* Save status prompt history to file. */
119 void
120 status_prompt_save_history(void)
121 {
122 	FILE	*f;
123 	u_int	 i;
124 	char	*history_file;
125 
126 	if ((history_file = status_prompt_find_history_file()) == NULL)
127 		return;
128 	log_debug("saving history to %s", history_file);
129 
130 	f = fopen(history_file, "w");
131 	if (f == NULL) {
132 		log_debug("%s: %s", history_file, strerror(errno));
133 		free(history_file);
134 		return;
135 	}
136 	free(history_file);
137 
138 	for (i = 0; i < status_prompt_hsize; i++) {
139 		fputs(status_prompt_hlist[i], f);
140 		fputc('\n', f);
141 	}
142 	fclose(f);
143 
144 }
145 
146 /* Status timer callback. */
147 void
148 status_timer_callback(__unused int fd, __unused short events, void *arg)
149 {
150 	struct client	*c = arg;
151 	struct session	*s = c->session;
152 	struct timeval	 tv;
153 
154 	evtimer_del(&c->status_timer);
155 
156 	if (s == NULL)
157 		return;
158 
159 	if (c->message_string == NULL && c->prompt_string == NULL)
160 		c->flags |= CLIENT_STATUS;
161 
162 	timerclear(&tv);
163 	tv.tv_sec = options_get_number(s->options, "status-interval");
164 
165 	if (tv.tv_sec != 0)
166 		evtimer_add(&c->status_timer, &tv);
167 	log_debug("client %p, status interval %d", c, (int)tv.tv_sec);
168 }
169 
170 /* Start status timer for client. */
171 void
172 status_timer_start(struct client *c)
173 {
174 	struct session	*s = c->session;
175 
176 	if (event_initialized(&c->status_timer))
177 		evtimer_del(&c->status_timer);
178 	else
179 		evtimer_set(&c->status_timer, status_timer_callback, c);
180 
181 	if (s != NULL && options_get_number(s->options, "status"))
182 		status_timer_callback(-1, 0, c);
183 }
184 
185 /* Start status timer for all clients. */
186 void
187 status_timer_start_all(void)
188 {
189 	struct client	*c;
190 
191 	TAILQ_FOREACH(c, &clients, entry)
192 		status_timer_start(c);
193 }
194 
195 /* Get screen line of status line. -1 means off. */
196 int
197 status_at_line(struct client *c)
198 {
199 	struct session	*s = c->session;
200 
201 	if (!options_get_number(s->options, "status"))
202 		return (-1);
203 
204 	if (options_get_number(s->options, "status-position") == 0)
205 		return (0);
206 	return (c->tty.sy - 1);
207 }
208 
209 /* Retrieve options for left string. */
210 char *
211 status_redraw_get_left(struct client *c, time_t t, struct grid_cell *gc,
212     size_t *size)
213 {
214 	struct session	*s = c->session;
215 	const char	*template;
216 	char		*left;
217 	size_t		 leftlen;
218 
219 	style_apply_update(gc, s->options, "status-left-style");
220 
221 	template = options_get_string(s->options, "status-left");
222 	left = status_replace(c, NULL, template, t);
223 
224 	*size = options_get_number(s->options, "status-left-length");
225 	leftlen = screen_write_cstrlen("%s", left);
226 	if (leftlen < *size)
227 		*size = leftlen;
228 	return (left);
229 }
230 
231 /* Retrieve options for right string. */
232 char *
233 status_redraw_get_right(struct client *c, time_t t, struct grid_cell *gc,
234     size_t *size)
235 {
236 	struct session	*s = c->session;
237 	const char	*template;
238 	char		*right;
239 	size_t		 rightlen;
240 
241 	style_apply_update(gc, s->options, "status-right-style");
242 
243 	template = options_get_string(s->options, "status-right");
244 	right = status_replace(c, NULL, template, t);
245 
246 	*size = options_get_number(s->options, "status-right-length");
247 	rightlen = screen_write_cstrlen("%s", right);
248 	if (rightlen < *size)
249 		*size = rightlen;
250 	return (right);
251 }
252 
253 /* Get window at window list position. */
254 struct window *
255 status_get_window_at(struct client *c, u_int x)
256 {
257 	struct session	*s = c->session;
258 	struct winlink	*wl;
259 	struct options	*oo;
260 	size_t		 len;
261 
262 	x += c->wlmouse;
263 	RB_FOREACH(wl, winlinks, &s->windows) {
264 		oo = wl->window->options;
265 		len = strlen(options_get_string(oo, "window-status-separator"));
266 
267 		if (x < wl->status_width)
268 			return (wl->window);
269 		x -= wl->status_width + len;
270 	}
271 	return (NULL);
272 }
273 
274 /* Draw status for client on the last lines of given context. */
275 int
276 status_redraw(struct client *c)
277 {
278 	struct screen_write_ctx	ctx;
279 	struct session	       *s = c->session;
280 	struct winlink	       *wl;
281 	struct screen		old_status, window_list;
282 	struct grid_cell	stdgc, lgc, rgc, gc;
283 	struct options	       *oo;
284 	time_t			t;
285 	char		       *left, *right, *sep;
286 	u_int			offset, needed;
287 	u_int			wlstart, wlwidth, wlavailable, wloffset, wlsize;
288 	size_t			llen, rlen, seplen;
289 	int			larrow, rarrow;
290 
291 	/* No status line? */
292 	if (c->tty.sy == 0 || !options_get_number(s->options, "status"))
293 		return (1);
294 	left = right = NULL;
295 	larrow = rarrow = 0;
296 
297 	/* Store current time. */
298 	t = time(NULL);
299 
300 	/* Set up default colour. */
301 	style_apply(&stdgc, s->options, "status-style");
302 
303 	/* Create the target screen. */
304 	memcpy(&old_status, &c->status, sizeof old_status);
305 	screen_init(&c->status, c->tty.sx, 1, 0);
306 	screen_write_start(&ctx, NULL, &c->status);
307 	for (offset = 0; offset < c->tty.sx; offset++)
308 		screen_write_putc(&ctx, &stdgc, ' ');
309 	screen_write_stop(&ctx);
310 
311 	/* If the height is one line, blank status line. */
312 	if (c->tty.sy <= 1)
313 		goto out;
314 
315 	/* Work out left and right strings. */
316 	memcpy(&lgc, &stdgc, sizeof lgc);
317 	left = status_redraw_get_left(c, t, &lgc, &llen);
318 	memcpy(&rgc, &stdgc, sizeof rgc);
319 	right = status_redraw_get_right(c, t, &rgc, &rlen);
320 
321 	/*
322 	 * Figure out how much space we have for the window list. If there
323 	 * isn't enough space, just show a blank status line.
324 	 */
325 	needed = 0;
326 	if (llen != 0)
327 		needed += llen;
328 	if (rlen != 0)
329 		needed += rlen;
330 	if (c->tty.sx == 0 || c->tty.sx <= needed)
331 		goto out;
332 	wlavailable = c->tty.sx - needed;
333 
334 	/* Calculate the total size needed for the window list. */
335 	wlstart = wloffset = wlwidth = 0;
336 	RB_FOREACH(wl, winlinks, &s->windows) {
337 		free(wl->status_text);
338 		memcpy(&wl->status_cell, &stdgc, sizeof wl->status_cell);
339 		wl->status_text = status_print(c, wl, t, &wl->status_cell);
340 		wl->status_width = screen_write_cstrlen("%s", wl->status_text);
341 
342 		if (wl == s->curw)
343 			wloffset = wlwidth;
344 
345 		oo = wl->window->options;
346 		sep = options_get_string(oo, "window-status-separator");
347 		seplen = screen_write_strlen("%s", sep);
348 		wlwidth += wl->status_width + seplen;
349 	}
350 
351 	/* Create a new screen for the window list. */
352 	screen_init(&window_list, wlwidth, 1, 0);
353 
354 	/* And draw the window list into it. */
355 	screen_write_start(&ctx, NULL, &window_list);
356 	RB_FOREACH(wl, winlinks, &s->windows) {
357 		screen_write_cnputs(&ctx, -1, &wl->status_cell, "%s",
358 		    wl->status_text);
359 
360 		oo = wl->window->options;
361 		sep = options_get_string(oo, "window-status-separator");
362 		screen_write_nputs(&ctx, -1, &stdgc, "%s", sep);
363 	}
364 	screen_write_stop(&ctx);
365 
366 	/* If there is enough space for the total width, skip to draw now. */
367 	if (wlwidth <= wlavailable)
368 		goto draw;
369 
370 	/* Find size of current window text. */
371 	wlsize = s->curw->status_width;
372 
373 	/*
374 	 * If the current window is already on screen, good to draw from the
375 	 * start and just leave off the end.
376 	 */
377 	if (wloffset + wlsize < wlavailable) {
378 		if (wlavailable > 0) {
379 			rarrow = 1;
380 			wlavailable--;
381 		}
382 		wlwidth = wlavailable;
383 	} else {
384 		/*
385 		 * Work out how many characters we need to omit from the
386 		 * start. There are wlavailable characters to fill, and
387 		 * wloffset + wlsize must be the last. So, the start character
388 		 * is wloffset + wlsize - wlavailable.
389 		 */
390 		if (wlavailable > 0) {
391 			larrow = 1;
392 			wlavailable--;
393 		}
394 
395 		wlstart = wloffset + wlsize - wlavailable;
396 		if (wlavailable > 0 && wlwidth > wlstart + wlavailable + 1) {
397 			rarrow = 1;
398 			wlstart++;
399 			wlavailable--;
400 		}
401 		wlwidth = wlavailable;
402 	}
403 
404 	/* Bail if anything is now too small too. */
405 	if (wlwidth == 0 || wlavailable == 0) {
406 		screen_free(&window_list);
407 		goto out;
408 	}
409 
410 	/*
411 	 * Now the start position is known, work out the state of the left and
412 	 * right arrows.
413 	 */
414 	offset = 0;
415 	RB_FOREACH(wl, winlinks, &s->windows) {
416 		if (wl->flags & WINLINK_ALERTFLAGS &&
417 		    larrow == 1 && offset < wlstart)
418 			larrow = -1;
419 
420 		offset += wl->status_width;
421 
422 		if (wl->flags & WINLINK_ALERTFLAGS &&
423 		    rarrow == 1 && offset > wlstart + wlwidth)
424 			rarrow = -1;
425 	}
426 
427 draw:
428 	/* Begin drawing. */
429 	screen_write_start(&ctx, NULL, &c->status);
430 
431 	/* Draw the left string and arrow. */
432 	screen_write_cursormove(&ctx, 0, 0);
433 	if (llen != 0)
434 		screen_write_cnputs(&ctx, llen, &lgc, "%s", left);
435 	if (larrow != 0) {
436 		memcpy(&gc, &stdgc, sizeof gc);
437 		if (larrow == -1)
438 			gc.attr ^= GRID_ATTR_REVERSE;
439 		screen_write_putc(&ctx, &gc, '<');
440 	}
441 
442 	/* Draw the right string and arrow. */
443 	if (rarrow != 0) {
444 		screen_write_cursormove(&ctx, c->tty.sx - rlen - 1, 0);
445 		memcpy(&gc, &stdgc, sizeof gc);
446 		if (rarrow == -1)
447 			gc.attr ^= GRID_ATTR_REVERSE;
448 		screen_write_putc(&ctx, &gc, '>');
449 	} else
450 		screen_write_cursormove(&ctx, c->tty.sx - rlen, 0);
451 	if (rlen != 0)
452 		screen_write_cnputs(&ctx, rlen, &rgc, "%s", right);
453 
454 	/* Figure out the offset for the window list. */
455 	if (llen != 0)
456 		wloffset = llen;
457 	else
458 		wloffset = 0;
459 	if (wlwidth < wlavailable) {
460 		switch (options_get_number(s->options, "status-justify")) {
461 		case 1:	/* centred */
462 			wloffset += (wlavailable - wlwidth) / 2;
463 			break;
464 		case 2:	/* right */
465 			wloffset += (wlavailable - wlwidth);
466 			break;
467 		}
468 	}
469 	if (larrow != 0)
470 		wloffset++;
471 
472 	/* Copy the window list. */
473 	c->wlmouse = -wloffset + wlstart;
474 	screen_write_cursormove(&ctx, wloffset, 0);
475 	screen_write_copy(&ctx, &window_list, wlstart, 0, wlwidth, 1);
476 	screen_free(&window_list);
477 
478 	screen_write_stop(&ctx);
479 
480 out:
481 	free(left);
482 	free(right);
483 
484 	if (grid_compare(c->status.grid, old_status.grid) == 0) {
485 		screen_free(&old_status);
486 		return (0);
487 	}
488 	screen_free(&old_status);
489 	return (1);
490 }
491 
492 /* Replace special sequences in fmt. */
493 char *
494 status_replace(struct client *c, struct winlink *wl, const char *fmt, time_t t)
495 {
496 	struct format_tree	*ft;
497 	char			*expanded;
498 
499 	if (fmt == NULL)
500 		return (xstrdup(""));
501 
502 	if (c->flags & CLIENT_STATUSFORCE)
503 		ft = format_create(NULL, FORMAT_STATUS|FORMAT_FORCE);
504 	else
505 		ft = format_create(NULL, FORMAT_STATUS);
506 	format_defaults(ft, c, NULL, wl, NULL);
507 
508 	expanded = format_expand_time(ft, fmt, t);
509 
510 	format_free(ft);
511 	return (expanded);
512 }
513 
514 /* Return winlink status line entry and adjust gc as necessary. */
515 char *
516 status_print(struct client *c, struct winlink *wl, time_t t,
517     struct grid_cell *gc)
518 {
519 	struct options	*oo = wl->window->options;
520 	struct session	*s = c->session;
521 	const char	*fmt;
522 	char   		*text;
523 
524 	style_apply_update(gc, oo, "window-status-style");
525 	fmt = options_get_string(oo, "window-status-format");
526 	if (wl == s->curw) {
527 		style_apply_update(gc, oo, "window-status-current-style");
528 		fmt = options_get_string(oo, "window-status-current-format");
529 	}
530 	if (wl == TAILQ_FIRST(&s->lastw))
531 		style_apply_update(gc, oo, "window-status-last-style");
532 
533 	if (wl->flags & WINLINK_BELL)
534 		style_apply_update(gc, oo, "window-status-bell-style");
535 	else if (wl->flags & (WINLINK_ACTIVITY|WINLINK_SILENCE))
536 		style_apply_update(gc, oo, "window-status-activity-style");
537 
538 	text = status_replace(c, wl, fmt, t);
539 	return (text);
540 }
541 
542 /* Set a status line message. */
543 void
544 status_message_set(struct client *c, const char *fmt, ...)
545 {
546 	struct timeval		 tv;
547 	struct message_entry	*msg, *msg1;
548 	va_list			 ap;
549 	int			 delay;
550 	u_int			 limit;
551 
552 	limit = options_get_number(global_options, "message-limit");
553 
554 	status_prompt_clear(c);
555 	status_message_clear(c);
556 
557 	va_start(ap, fmt);
558 	xvasprintf(&c->message_string, fmt, ap);
559 	va_end(ap);
560 
561 	msg = xcalloc(1, sizeof *msg);
562 	msg->msg_time = time(NULL);
563 	msg->msg_num = c->message_next++;
564 	msg->msg = xstrdup(c->message_string);
565 	TAILQ_INSERT_TAIL(&c->message_log, msg, entry);
566 
567 	TAILQ_FOREACH_SAFE(msg, &c->message_log, entry, msg1) {
568 		if (msg->msg_num + limit >= c->message_next)
569 			break;
570 		free(msg->msg);
571 		TAILQ_REMOVE(&c->message_log, msg, entry);
572 		free(msg);
573 	}
574 
575 	delay = options_get_number(c->session->options, "display-time");
576 	if (delay > 0) {
577 		tv.tv_sec = delay / 1000;
578 		tv.tv_usec = (delay % 1000) * 1000L;
579 
580 		if (event_initialized(&c->message_timer))
581 			evtimer_del(&c->message_timer);
582 		evtimer_set(&c->message_timer, status_message_callback, c);
583 		evtimer_add(&c->message_timer, &tv);
584 	}
585 
586 	c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
587 	c->flags |= CLIENT_STATUS;
588 }
589 
590 /* Clear status line message. */
591 void
592 status_message_clear(struct client *c)
593 {
594 	if (c->message_string == NULL)
595 		return;
596 
597 	free(c->message_string);
598 	c->message_string = NULL;
599 
600 	c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
601 	c->flags |= CLIENT_REDRAW; /* screen was frozen and may have changed */
602 
603 	screen_reinit(&c->status);
604 }
605 
606 /* Clear status line message after timer expires. */
607 void
608 status_message_callback(__unused int fd, __unused short event, void *data)
609 {
610 	struct client	*c = data;
611 
612 	status_message_clear(c);
613 }
614 
615 /* Draw client message on status line of present else on last line. */
616 int
617 status_message_redraw(struct client *c)
618 {
619 	struct screen_write_ctx		ctx;
620 	struct session		       *s = c->session;
621 	struct screen		        old_status;
622 	size_t			        len;
623 	struct grid_cell		gc;
624 
625 	if (c->tty.sx == 0 || c->tty.sy == 0)
626 		return (0);
627 	memcpy(&old_status, &c->status, sizeof old_status);
628 	screen_init(&c->status, c->tty.sx, 1, 0);
629 
630 	len = screen_write_strlen("%s", c->message_string);
631 	if (len > c->tty.sx)
632 		len = c->tty.sx;
633 
634 	style_apply(&gc, s->options, "message-style");
635 
636 	screen_write_start(&ctx, NULL, &c->status);
637 
638 	screen_write_cursormove(&ctx, 0, 0);
639 	screen_write_nputs(&ctx, len, &gc, "%s", c->message_string);
640 	for (; len < c->tty.sx; len++)
641 		screen_write_putc(&ctx, &gc, ' ');
642 
643 	screen_write_stop(&ctx);
644 
645 	if (grid_compare(c->status.grid, old_status.grid) == 0) {
646 		screen_free(&old_status);
647 		return (0);
648 	}
649 	screen_free(&old_status);
650 	return (1);
651 }
652 
653 /* Enable status line prompt. */
654 void
655 status_prompt_set(struct client *c, const char *msg, const char *input,
656     int (*callbackfn)(void *, const char *), void (*freefn)(void *),
657     void *data, int flags)
658 {
659 	struct format_tree	*ft;
660 	int			 keys;
661 	time_t			 t;
662 
663 	ft = format_create(NULL, 0);
664 	format_defaults(ft, c, NULL, NULL, NULL);
665 	t = time(NULL);
666 
667 	status_message_clear(c);
668 	status_prompt_clear(c);
669 
670 	c->prompt_string = format_expand_time(ft, msg, t);
671 
672 	c->prompt_buffer = format_expand_time(ft, input, t);
673 	c->prompt_index = strlen(c->prompt_buffer);
674 
675 	c->prompt_callbackfn = callbackfn;
676 	c->prompt_freefn = freefn;
677 	c->prompt_data = data;
678 
679 	c->prompt_hindex = 0;
680 
681 	c->prompt_flags = flags;
682 
683 	keys = options_get_number(c->session->options, "status-keys");
684 	if (keys == MODEKEY_EMACS)
685 		mode_key_init(&c->prompt_mdata, &mode_key_tree_emacs_edit);
686 	else
687 		mode_key_init(&c->prompt_mdata, &mode_key_tree_vi_edit);
688 
689 	c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
690 	c->flags |= CLIENT_STATUS;
691 
692 	format_free(ft);
693 }
694 
695 /* Remove status line prompt. */
696 void
697 status_prompt_clear(struct client *c)
698 {
699 	if (c->prompt_string == NULL)
700 		return;
701 
702 	if (c->prompt_freefn != NULL && c->prompt_data != NULL)
703 		c->prompt_freefn(c->prompt_data);
704 
705 	free(c->prompt_string);
706 	c->prompt_string = NULL;
707 
708 	free(c->prompt_buffer);
709 	c->prompt_buffer = NULL;
710 
711 	c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
712 	c->flags |= CLIENT_REDRAW; /* screen was frozen and may have changed */
713 
714 	screen_reinit(&c->status);
715 }
716 
717 /* Update status line prompt with a new prompt string. */
718 void
719 status_prompt_update(struct client *c, const char *msg, const char *input)
720 {
721 	struct format_tree	*ft;
722 	time_t			 t;
723 
724 	ft = format_create(NULL, 0);
725 	format_defaults(ft, c, NULL, NULL, NULL);
726 	t = time(NULL);
727 
728 	free(c->prompt_string);
729 	c->prompt_string = format_expand_time(ft, msg, t);
730 
731 	free(c->prompt_buffer);
732 	c->prompt_buffer = format_expand_time(ft, input, t);
733 	c->prompt_index = strlen(c->prompt_buffer);
734 
735 	c->prompt_hindex = 0;
736 
737 	c->flags |= CLIENT_STATUS;
738 
739 	format_free(ft);
740 }
741 
742 /* Draw client prompt on status line of present else on last line. */
743 int
744 status_prompt_redraw(struct client *c)
745 {
746 	struct screen_write_ctx		ctx;
747 	struct session		       *s = c->session;
748 	struct screen		        old_status;
749 	size_t			        i, size, left, len, off;
750 	struct grid_cell		gc;
751 
752 	if (c->tty.sx == 0 || c->tty.sy == 0)
753 		return (0);
754 	memcpy(&old_status, &c->status, sizeof old_status);
755 	screen_init(&c->status, c->tty.sx, 1, 0);
756 
757 	len = screen_write_strlen("%s", c->prompt_string);
758 	if (len > c->tty.sx)
759 		len = c->tty.sx;
760 	off = 0;
761 
762 	/* Change colours for command mode. */
763 	if (c->prompt_mdata.mode == 1)
764 		style_apply(&gc, s->options, "message-command-style");
765 	else
766 		style_apply(&gc, s->options, "message-style");
767 
768 	screen_write_start(&ctx, NULL, &c->status);
769 
770 	screen_write_cursormove(&ctx, 0, 0);
771 	screen_write_nputs(&ctx, len, &gc, "%s", c->prompt_string);
772 
773 	left = c->tty.sx - len;
774 	if (left != 0) {
775 		size = screen_write_strlen("%s", c->prompt_buffer);
776 		if (c->prompt_index >= left) {
777 			off = c->prompt_index - left + 1;
778 			if (c->prompt_index == size)
779 				left--;
780 			size = left;
781 		}
782 		screen_write_nputs(&ctx, left, &gc, "%s", c->prompt_buffer +
783 		    off);
784 
785 		for (i = len + size; i < c->tty.sx; i++)
786 			screen_write_putc(&ctx, &gc, ' ');
787 	}
788 
789 	screen_write_stop(&ctx);
790 
791 	/* Apply fake cursor. */
792 	off = len + c->prompt_index - off;
793 	grid_view_get_cell(c->status.grid, off, 0, &gc);
794 	gc.attr ^= GRID_ATTR_REVERSE;
795 	grid_view_set_cell(c->status.grid, off, 0, &gc);
796 
797 	if (grid_compare(c->status.grid, old_status.grid) == 0) {
798 		screen_free(&old_status);
799 		return (0);
800 	}
801 	screen_free(&old_status);
802 	return (1);
803 }
804 
805 /* Handle keys in prompt. */
806 void
807 status_prompt_key(struct client *c, key_code key)
808 {
809 	struct session		*sess = c->session;
810 	struct options		*oo = sess->options;
811 	struct paste_buffer	*pb;
812 	char			*s, *first, *last, word[64], swapc;
813 	const char		*histstr, *bufdata, *wsep = NULL;
814 	u_char			 ch;
815 	size_t			 size, n, off, idx, bufsize;
816 
817 	size = strlen(c->prompt_buffer);
818 	switch (mode_key_lookup(&c->prompt_mdata, key, NULL)) {
819 	case MODEKEYEDIT_CURSORLEFT:
820 		if (c->prompt_index > 0) {
821 			c->prompt_index--;
822 			c->flags |= CLIENT_STATUS;
823 		}
824 		break;
825 	case MODEKEYEDIT_SWITCHMODE:
826 		c->flags |= CLIENT_STATUS;
827 		break;
828 	case MODEKEYEDIT_SWITCHMODEAPPEND:
829 		c->flags |= CLIENT_STATUS;
830 		/* FALLTHROUGH */
831 	case MODEKEYEDIT_CURSORRIGHT:
832 		if (c->prompt_index < size) {
833 			c->prompt_index++;
834 			c->flags |= CLIENT_STATUS;
835 		}
836 		break;
837 	case MODEKEYEDIT_SWITCHMODEBEGINLINE:
838 		c->flags |= CLIENT_STATUS;
839 		/* FALLTHROUGH */
840 	case MODEKEYEDIT_STARTOFLINE:
841 		if (c->prompt_index != 0) {
842 			c->prompt_index = 0;
843 			c->flags |= CLIENT_STATUS;
844 		}
845 		break;
846 	case MODEKEYEDIT_SWITCHMODEAPPENDLINE:
847 		c->flags |= CLIENT_STATUS;
848 		/* FALLTHROUGH */
849 	case MODEKEYEDIT_ENDOFLINE:
850 		if (c->prompt_index != size) {
851 			c->prompt_index = size;
852 			c->flags |= CLIENT_STATUS;
853 		}
854 		break;
855 	case MODEKEYEDIT_COMPLETE:
856 		if (*c->prompt_buffer == '\0')
857 			break;
858 
859 		idx = c->prompt_index;
860 		if (idx != 0)
861 			idx--;
862 
863 		/* Find the word we are in. */
864 		first = c->prompt_buffer + idx;
865 		while (first > c->prompt_buffer && *first != ' ')
866 			first--;
867 		while (*first == ' ')
868 			first++;
869 		last = c->prompt_buffer + idx;
870 		while (*last != '\0' && *last != ' ')
871 			last++;
872 		while (*last == ' ')
873 			last--;
874 		if (*last != '\0')
875 			last++;
876 		if (last <= first ||
877 		    ((size_t) (last - first)) > (sizeof word) - 1)
878 			break;
879 		memcpy(word, first, last - first);
880 		word[last - first] = '\0';
881 
882 		/* And try to complete it. */
883 		if ((s = status_prompt_complete(sess, word)) == NULL)
884 			break;
885 
886 		/* Trim out word. */
887 		n = size - (last - c->prompt_buffer) + 1; /* with \0 */
888 		memmove(first, last, n);
889 		size -= last - first;
890 
891 		/* Insert the new word. */
892 		size += strlen(s);
893 		off = first - c->prompt_buffer;
894 		c->prompt_buffer = xrealloc(c->prompt_buffer, size + 1);
895 		first = c->prompt_buffer + off;
896 		memmove(first + strlen(s), first, n);
897 		memcpy(first, s, strlen(s));
898 
899 		c->prompt_index = (first - c->prompt_buffer) + strlen(s);
900 		free(s);
901 
902 		c->flags |= CLIENT_STATUS;
903 		break;
904 	case MODEKEYEDIT_BACKSPACE:
905 		if (c->prompt_index != 0) {
906 			if (c->prompt_index == size)
907 				c->prompt_buffer[--c->prompt_index] = '\0';
908 			else {
909 				memmove(c->prompt_buffer + c->prompt_index - 1,
910 				    c->prompt_buffer + c->prompt_index,
911 				    size + 1 - c->prompt_index);
912 				c->prompt_index--;
913 			}
914 			c->flags |= CLIENT_STATUS;
915 		}
916 		break;
917 	case MODEKEYEDIT_DELETE:
918 	case MODEKEYEDIT_SWITCHMODESUBSTITUTE:
919 		if (c->prompt_index != size) {
920 			memmove(c->prompt_buffer + c->prompt_index,
921 			    c->prompt_buffer + c->prompt_index + 1,
922 			    size + 1 - c->prompt_index);
923 			c->flags |= CLIENT_STATUS;
924 		}
925 		break;
926 	case MODEKEYEDIT_DELETELINE:
927 	case MODEKEYEDIT_SWITCHMODESUBSTITUTELINE:
928 		*c->prompt_buffer = '\0';
929 		c->prompt_index = 0;
930 		c->flags |= CLIENT_STATUS;
931 		break;
932 	case MODEKEYEDIT_DELETETOENDOFLINE:
933 	case MODEKEYEDIT_SWITCHMODECHANGELINE:
934 		if (c->prompt_index < size) {
935 			c->prompt_buffer[c->prompt_index] = '\0';
936 			c->flags |= CLIENT_STATUS;
937 		}
938 		break;
939 	case MODEKEYEDIT_DELETEWORD:
940 		wsep = options_get_string(oo, "word-separators");
941 		idx = c->prompt_index;
942 
943 		/* Find a non-separator. */
944 		while (idx != 0) {
945 			idx--;
946 			if (!strchr(wsep, c->prompt_buffer[idx]))
947 				break;
948 		}
949 
950 		/* Find the separator at the beginning of the word. */
951 		while (idx != 0) {
952 			idx--;
953 			if (strchr(wsep, c->prompt_buffer[idx])) {
954 				/* Go back to the word. */
955 				idx++;
956 				break;
957 			}
958 		}
959 
960 		memmove(c->prompt_buffer + idx,
961 		    c->prompt_buffer + c->prompt_index,
962 		    size + 1 - c->prompt_index);
963 		memset(c->prompt_buffer + size - (c->prompt_index - idx),
964 		    '\0', c->prompt_index - idx);
965 		c->prompt_index = idx;
966 		c->flags |= CLIENT_STATUS;
967 		break;
968 	case MODEKEYEDIT_NEXTSPACE:
969 		wsep = " ";
970 		/* FALLTHROUGH */
971 	case MODEKEYEDIT_NEXTWORD:
972 		if (wsep == NULL)
973 			wsep = options_get_string(oo, "word-separators");
974 
975 		/* Find a separator. */
976 		while (c->prompt_index != size) {
977 			c->prompt_index++;
978 			if (strchr(wsep, c->prompt_buffer[c->prompt_index]))
979 				break;
980 		}
981 
982 		/* Find the word right after the separation. */
983 		while (c->prompt_index != size) {
984 			c->prompt_index++;
985 			if (!strchr(wsep, c->prompt_buffer[c->prompt_index]))
986 				break;
987 		}
988 
989 		c->flags |= CLIENT_STATUS;
990 		break;
991 	case MODEKEYEDIT_NEXTSPACEEND:
992 		wsep = " ";
993 		/* FALLTHROUGH */
994 	case MODEKEYEDIT_NEXTWORDEND:
995 		if (wsep == NULL)
996 			wsep = options_get_string(oo, "word-separators");
997 
998 		/* Find a word. */
999 		while (c->prompt_index != size) {
1000 			c->prompt_index++;
1001 			if (!strchr(wsep, c->prompt_buffer[c->prompt_index]))
1002 				break;
1003 		}
1004 
1005 		/* Find the separator at the end of the word. */
1006 		while (c->prompt_index != size) {
1007 			c->prompt_index++;
1008 			if (strchr(wsep, c->prompt_buffer[c->prompt_index]))
1009 				break;
1010 		}
1011 
1012 		/* Back up to the end-of-word like vi. */
1013 		if (options_get_number(oo, "status-keys") == MODEKEY_VI &&
1014 		    c->prompt_index != 0)
1015 			c->prompt_index--;
1016 
1017 		c->flags |= CLIENT_STATUS;
1018 		break;
1019 	case MODEKEYEDIT_PREVIOUSSPACE:
1020 		wsep = " ";
1021 		/* FALLTHROUGH */
1022 	case MODEKEYEDIT_PREVIOUSWORD:
1023 		if (wsep == NULL)
1024 			wsep = options_get_string(oo, "word-separators");
1025 
1026 		/* Find a non-separator. */
1027 		while (c->prompt_index != 0) {
1028 			c->prompt_index--;
1029 			if (!strchr(wsep, c->prompt_buffer[c->prompt_index]))
1030 				break;
1031 		}
1032 
1033 		/* Find the separator at the beginning of the word. */
1034 		while (c->prompt_index != 0) {
1035 			c->prompt_index--;
1036 			if (strchr(wsep, c->prompt_buffer[c->prompt_index])) {
1037 				/* Go back to the word. */
1038 				c->prompt_index++;
1039 				break;
1040 			}
1041 		}
1042 
1043 		c->flags |= CLIENT_STATUS;
1044 		break;
1045 	case MODEKEYEDIT_HISTORYUP:
1046 		histstr = status_prompt_up_history(&c->prompt_hindex);
1047 		if (histstr == NULL)
1048 			break;
1049 		free(c->prompt_buffer);
1050 		c->prompt_buffer = xstrdup(histstr);
1051 		c->prompt_index = strlen(c->prompt_buffer);
1052 		c->flags |= CLIENT_STATUS;
1053 		break;
1054 	case MODEKEYEDIT_HISTORYDOWN:
1055 		histstr = status_prompt_down_history(&c->prompt_hindex);
1056 		if (histstr == NULL)
1057 			break;
1058 		free(c->prompt_buffer);
1059 		c->prompt_buffer = xstrdup(histstr);
1060 		c->prompt_index = strlen(c->prompt_buffer);
1061 		c->flags |= CLIENT_STATUS;
1062 		break;
1063 	case MODEKEYEDIT_PASTE:
1064 		if ((pb = paste_get_top(NULL)) == NULL)
1065 			break;
1066 		bufdata = paste_buffer_data(pb, &bufsize);
1067 		for (n = 0; n < bufsize; n++) {
1068 			ch = (u_char)bufdata[n];
1069 			if (ch < 32 || ch == 127)
1070 				break;
1071 		}
1072 
1073 		c->prompt_buffer = xrealloc(c->prompt_buffer, size + n + 1);
1074 		if (c->prompt_index == size) {
1075 			memcpy(c->prompt_buffer + c->prompt_index, bufdata, n);
1076 			c->prompt_index += n;
1077 			c->prompt_buffer[c->prompt_index] = '\0';
1078 		} else {
1079 			memmove(c->prompt_buffer + c->prompt_index + n,
1080 			    c->prompt_buffer + c->prompt_index,
1081 			    size + 1 - c->prompt_index);
1082 			memcpy(c->prompt_buffer + c->prompt_index, bufdata, n);
1083 			c->prompt_index += n;
1084 		}
1085 
1086 		c->flags |= CLIENT_STATUS;
1087 		break;
1088 	case MODEKEYEDIT_TRANSPOSECHARS:
1089 		idx = c->prompt_index;
1090 		if (idx < size)
1091 			idx++;
1092 		if (idx >= 2) {
1093 			swapc = c->prompt_buffer[idx - 2];
1094 			c->prompt_buffer[idx - 2] = c->prompt_buffer[idx - 1];
1095 			c->prompt_buffer[idx - 1] = swapc;
1096 			c->prompt_index = idx;
1097 			c->flags |= CLIENT_STATUS;
1098 		}
1099 		break;
1100 	case MODEKEYEDIT_ENTER:
1101 		if (*c->prompt_buffer != '\0')
1102 			status_prompt_add_history(c->prompt_buffer);
1103 		if (c->prompt_callbackfn(c->prompt_data, c->prompt_buffer) == 0)
1104 			status_prompt_clear(c);
1105 		break;
1106 	case MODEKEYEDIT_CANCEL:
1107 		if (c->prompt_callbackfn(c->prompt_data, NULL) == 0)
1108 			status_prompt_clear(c);
1109 		break;
1110 	case MODEKEY_OTHER:
1111 		if (key <= 0x1f || key >= 0x7f)
1112 			break;
1113 		c->prompt_buffer = xrealloc(c->prompt_buffer, size + 2);
1114 
1115 		if (c->prompt_index == size) {
1116 			c->prompt_buffer[c->prompt_index++] = key;
1117 			c->prompt_buffer[c->prompt_index] = '\0';
1118 		} else {
1119 			memmove(c->prompt_buffer + c->prompt_index + 1,
1120 			    c->prompt_buffer + c->prompt_index,
1121 			    size + 1 - c->prompt_index);
1122 			c->prompt_buffer[c->prompt_index++] = key;
1123 		}
1124 
1125 		if (c->prompt_flags & PROMPT_SINGLE) {
1126 			if (c->prompt_callbackfn(c->prompt_data,
1127 			    c->prompt_buffer) == 0)
1128 				status_prompt_clear(c);
1129 		}
1130 
1131 		c->flags |= CLIENT_STATUS;
1132 		break;
1133 	default:
1134 		break;
1135 	}
1136 }
1137 
1138 /* Get previous line from the history. */
1139 const char *
1140 status_prompt_up_history(u_int *idx)
1141 {
1142 	/*
1143 	 * History runs from 0 to size - 1. Index is from 0 to size. Zero is
1144 	 * empty.
1145 	 */
1146 
1147 	if (status_prompt_hsize == 0 || *idx == status_prompt_hsize)
1148 		return (NULL);
1149 	(*idx)++;
1150 	return (status_prompt_hlist[status_prompt_hsize - *idx]);
1151 }
1152 
1153 /* Get next line from the history. */
1154 const char *
1155 status_prompt_down_history(u_int *idx)
1156 {
1157 	if (status_prompt_hsize == 0 || *idx == 0)
1158 		return ("");
1159 	(*idx)--;
1160 	if (*idx == 0)
1161 		return ("");
1162 	return (status_prompt_hlist[status_prompt_hsize - *idx]);
1163 }
1164 
1165 /* Add line to the history. */
1166 void
1167 status_prompt_add_history(const char *line)
1168 {
1169 	size_t	size;
1170 
1171 	if (status_prompt_hsize > 0 &&
1172 	    strcmp(status_prompt_hlist[status_prompt_hsize - 1], line) == 0)
1173 		return;
1174 
1175 	if (status_prompt_hsize == PROMPT_HISTORY) {
1176 		free(status_prompt_hlist[0]);
1177 
1178 		size = (PROMPT_HISTORY - 1) * sizeof *status_prompt_hlist;
1179 		memmove(&status_prompt_hlist[0], &status_prompt_hlist[1], size);
1180 
1181 		status_prompt_hlist[status_prompt_hsize - 1] = xstrdup(line);
1182 		return;
1183 	}
1184 
1185 	status_prompt_hlist = xreallocarray(status_prompt_hlist,
1186 	    status_prompt_hsize + 1, sizeof *status_prompt_hlist);
1187 	status_prompt_hlist[status_prompt_hsize++] = xstrdup(line);
1188 }
1189 
1190 /* Build completion list. */
1191 const char **
1192 status_prompt_complete_list(u_int *size, const char *s)
1193 {
1194 	const char				**list = NULL, **layout;
1195 	const struct cmd_entry			**cmdent;
1196 	const struct options_table_entry	 *oe;
1197 	const char				 *layouts[] = {
1198 		"even-horizontal", "even-vertical", "main-horizontal",
1199 		"main-vertical", "tiled", NULL
1200 	};
1201 
1202 	*size = 0;
1203 	for (cmdent = cmd_table; *cmdent != NULL; cmdent++) {
1204 		if (strncmp((*cmdent)->name, s, strlen(s)) == 0) {
1205 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1206 			list[(*size)++] = (*cmdent)->name;
1207 		}
1208 	}
1209 	for (oe = options_table; oe->name != NULL; oe++) {
1210 		if (strncmp(oe->name, s, strlen(s)) == 0) {
1211 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1212 			list[(*size)++] = oe->name;
1213 		}
1214 	}
1215 	for (layout = layouts; *layout != NULL; layout++) {
1216 		if (strncmp(*layout, s, strlen(s)) == 0) {
1217 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1218 			list[(*size)++] = *layout;
1219 		}
1220 	}
1221 	return (list);
1222 }
1223 
1224 /* Find longest prefix. */
1225 char *
1226 status_prompt_complete_prefix(const char **list, u_int size)
1227 {
1228 	char	 *out;
1229 	u_int	  i;
1230 	size_t	  j;
1231 
1232 	out = xstrdup(list[0]);
1233 	for (i = 1; i < size; i++) {
1234 		j = strlen(list[i]);
1235 		if (j > strlen(out))
1236 			j = strlen(out);
1237 		for (; j > 0; j--) {
1238 			if (out[j - 1] != list[i][j - 1])
1239 				out[j - 1] = '\0';
1240 		}
1241 	}
1242 	return (out);
1243 }
1244 
1245 /* Complete word. */
1246 char *
1247 status_prompt_complete(struct session *sess, const char *s)
1248 {
1249 	const char	**list = NULL, *colon;
1250 	u_int		  size = 0, i;
1251 	struct session	 *s_loop;
1252 	struct winlink	 *wl;
1253 	struct window	 *w;
1254 	char		 *copy, *out, *tmp;
1255 
1256 	if (*s == '\0')
1257 		return (NULL);
1258 	out = NULL;
1259 
1260 	if (strncmp(s, "-t", 2) != 0 && strncmp(s, "-s", 2) != 0) {
1261 		list = status_prompt_complete_list(&size, s);
1262 		if (size == 0)
1263 			out = NULL;
1264 		else if (size == 1)
1265 			xasprintf(&out, "%s ", list[0]);
1266 		else
1267 			out = status_prompt_complete_prefix(list, size);
1268 		free(list);
1269 		return (out);
1270 	}
1271 	copy = xstrdup(s);
1272 
1273 	colon = ":";
1274 	if (copy[strlen(copy) - 1] == ':')
1275 		copy[strlen(copy) - 1] = '\0';
1276 	else
1277 		colon = "";
1278 	s = copy + 2;
1279 
1280 	RB_FOREACH(s_loop, sessions, &sessions) {
1281 		if (strncmp(s_loop->name, s, strlen(s)) == 0) {
1282 			list = xreallocarray(list, size + 2, sizeof *list);
1283 			list[size++] = s_loop->name;
1284 		}
1285 	}
1286 	if (size == 1) {
1287 		out = xstrdup(list[0]);
1288 		if (session_find(list[0]) != NULL)
1289 			colon = ":";
1290 	} else if (size != 0)
1291 		out = status_prompt_complete_prefix(list, size);
1292 	if (out != NULL) {
1293 		xasprintf(&tmp, "-%c%s%s", copy[1], out, colon);
1294 		out = tmp;
1295 		goto found;
1296 	}
1297 
1298 	colon = "";
1299 	if (*s == ':') {
1300 		RB_FOREACH(wl, winlinks, &sess->windows) {
1301 			xasprintf(&tmp, ":%s", wl->window->name);
1302 			if (strncmp(tmp, s, strlen(s)) == 0){
1303 				list = xreallocarray(list, size + 1,
1304 				    sizeof *list);
1305 				list[size++] = tmp;
1306 				continue;
1307 			}
1308 			free(tmp);
1309 
1310 			xasprintf(&tmp, ":%d", wl->idx);
1311 			if (strncmp(tmp, s, strlen(s)) == 0) {
1312 				list = xreallocarray(list, size + 1,
1313 				    sizeof *list);
1314 				list[size++] = tmp;
1315 				continue;
1316 			}
1317 			free(tmp);
1318 		}
1319 	} else {
1320 		RB_FOREACH(s_loop, sessions, &sessions) {
1321 			RB_FOREACH(wl, winlinks, &s_loop->windows) {
1322 				w = wl->window;
1323 
1324 				xasprintf(&tmp, "%s:%s", s_loop->name, w->name);
1325 				if (strncmp(tmp, s, strlen(s)) == 0) {
1326 					list = xreallocarray(list, size + 1,
1327 					    sizeof *list);
1328 					list[size++] = tmp;
1329 					continue;
1330 				}
1331 				free(tmp);
1332 
1333 				xasprintf(&tmp, "%s:%d", s_loop->name, wl->idx);
1334 				if (strncmp(tmp, s, strlen(s)) == 0) {
1335 					list = xreallocarray(list, size + 1,
1336 					    sizeof *list);
1337 					list[size++] = tmp;
1338 					continue;
1339 				}
1340 				free(tmp);
1341 			}
1342 		}
1343 	}
1344 	if (size == 1) {
1345 		out = xstrdup(list[0]);
1346 		colon = " ";
1347 	} else if (size != 0)
1348 		out = status_prompt_complete_prefix(list, size);
1349 	if (out != NULL) {
1350 		xasprintf(&tmp, "-%c%s%s", copy[1], out, colon);
1351 		out = tmp;
1352 	}
1353 
1354 	for (i = 0; i < size; i++)
1355 		free(__UNCONST(list[i]));
1356 
1357 found:
1358 	free(copy);
1359 	free(list);
1360 	return (out);
1361 }
1362