xref: /openbsd/usr.bin/tmux/status.c (revision 5a38ef86)
1 /* $OpenBSD: status.c,v 1.231 2021/11/15 10:58:13 nicm Exp $ */
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 static void	 status_message_callback(int, short, void *);
33 static void	 status_timer_callback(int, short, void *);
34 
35 static char	*status_prompt_find_history_file(void);
36 static const char *status_prompt_up_history(u_int *, u_int);
37 static const char *status_prompt_down_history(u_int *, u_int);
38 static void	 status_prompt_add_history(const char *, u_int);
39 
40 static char	*status_prompt_complete(struct client *, const char *, u_int);
41 static char	*status_prompt_complete_window_menu(struct client *,
42 		     struct session *, const char *, u_int, char);
43 
44 struct status_prompt_menu {
45 	struct client	 *c;
46 	u_int		  start;
47 	u_int		  size;
48 	char		**list;
49 	char		  flag;
50 };
51 
52 static const char	*prompt_type_strings[] = {
53 	"command",
54 	"search",
55 	"target",
56 	"window-target"
57 };
58 
59 /* Status prompt history. */
60 char		**status_prompt_hlist[PROMPT_NTYPES];
61 u_int		  status_prompt_hsize[PROMPT_NTYPES];
62 
63 /* Find the history file to load/save from/to. */
64 static char *
65 status_prompt_find_history_file(void)
66 {
67 	const char	*home, *history_file;
68 	char		*path;
69 
70 	history_file = options_get_string(global_options, "history-file");
71 	if (*history_file == '\0')
72 		return (NULL);
73 	if (*history_file == '/')
74 		return (xstrdup(history_file));
75 
76 	if (history_file[0] != '~' || history_file[1] != '/')
77 		return (NULL);
78 	if ((home = find_home()) == NULL)
79 		return (NULL);
80 	xasprintf(&path, "%s%s", home, history_file + 1);
81 	return (path);
82 }
83 
84 /* Add loaded history item to the appropriate list. */
85 static void
86 status_prompt_add_typed_history(char *line)
87 {
88 	char			*typestr;
89 	enum prompt_type	 type = PROMPT_TYPE_INVALID;
90 
91 	typestr = strsep(&line, ":");
92 	if (line != NULL)
93 		type = status_prompt_type(typestr);
94 	if (type == PROMPT_TYPE_INVALID) {
95 		/*
96 		 * Invalid types are not expected, but this provides backward
97 		 * compatibility with old history files.
98 		 */
99 		if (line != NULL)
100 			*(--line) = ':';
101 		status_prompt_add_history(typestr, PROMPT_TYPE_COMMAND);
102 	} else
103 		status_prompt_add_history(line, type);
104 }
105 
106 /* Load status prompt history from file. */
107 void
108 status_prompt_load_history(void)
109 {
110 	FILE	*f;
111 	char	*history_file, *line, *tmp;
112 	size_t	 length;
113 
114 	if ((history_file = status_prompt_find_history_file()) == NULL)
115 		return;
116 	log_debug("loading history from %s", history_file);
117 
118 	f = fopen(history_file, "r");
119 	if (f == NULL) {
120 		log_debug("%s: %s", history_file, strerror(errno));
121 		free(history_file);
122 		return;
123 	}
124 	free(history_file);
125 
126 	for (;;) {
127 		if ((line = fgetln(f, &length)) == NULL)
128 			break;
129 
130 		if (length > 0) {
131 			if (line[length - 1] == '\n') {
132 				line[length - 1] = '\0';
133 				status_prompt_add_typed_history(line);
134 			} else {
135 				tmp = xmalloc(length + 1);
136 				memcpy(tmp, line, length);
137 				tmp[length] = '\0';
138 				status_prompt_add_typed_history(tmp);
139 				free(tmp);
140 			}
141 		}
142 	}
143 	fclose(f);
144 }
145 
146 /* Save status prompt history to file. */
147 void
148 status_prompt_save_history(void)
149 {
150 	FILE	*f;
151 	u_int	 i, type;
152 	char	*history_file;
153 
154 	if ((history_file = status_prompt_find_history_file()) == NULL)
155 		return;
156 	log_debug("saving history to %s", history_file);
157 
158 	f = fopen(history_file, "w");
159 	if (f == NULL) {
160 		log_debug("%s: %s", history_file, strerror(errno));
161 		free(history_file);
162 		return;
163 	}
164 	free(history_file);
165 
166 	for (type = 0; type < PROMPT_NTYPES; type++) {
167 		for (i = 0; i < status_prompt_hsize[type]; i++) {
168 			fputs(prompt_type_strings[type], f);
169 			fputc(':', f);
170 			fputs(status_prompt_hlist[type][i], f);
171 			fputc('\n', f);
172 		}
173 	}
174 	fclose(f);
175 
176 }
177 
178 /* Status timer callback. */
179 static void
180 status_timer_callback(__unused int fd, __unused short events, void *arg)
181 {
182 	struct client	*c = arg;
183 	struct session	*s = c->session;
184 	struct timeval	 tv;
185 
186 	evtimer_del(&c->status.timer);
187 
188 	if (s == NULL)
189 		return;
190 
191 	if (c->message_string == NULL && c->prompt_string == NULL)
192 		c->flags |= CLIENT_REDRAWSTATUS;
193 
194 	timerclear(&tv);
195 	tv.tv_sec = options_get_number(s->options, "status-interval");
196 
197 	if (tv.tv_sec != 0)
198 		evtimer_add(&c->status.timer, &tv);
199 	log_debug("client %p, status interval %d", c, (int)tv.tv_sec);
200 }
201 
202 /* Start status timer for client. */
203 void
204 status_timer_start(struct client *c)
205 {
206 	struct session	*s = c->session;
207 
208 	if (event_initialized(&c->status.timer))
209 		evtimer_del(&c->status.timer);
210 	else
211 		evtimer_set(&c->status.timer, status_timer_callback, c);
212 
213 	if (s != NULL && options_get_number(s->options, "status"))
214 		status_timer_callback(-1, 0, c);
215 }
216 
217 /* Start status timer for all clients. */
218 void
219 status_timer_start_all(void)
220 {
221 	struct client	*c;
222 
223 	TAILQ_FOREACH(c, &clients, entry)
224 		status_timer_start(c);
225 }
226 
227 /* Update status cache. */
228 void
229 status_update_cache(struct session *s)
230 {
231 	s->statuslines = options_get_number(s->options, "status");
232 	if (s->statuslines == 0)
233 		s->statusat = -1;
234 	else if (options_get_number(s->options, "status-position") == 0)
235 		s->statusat = 0;
236 	else
237 		s->statusat = 1;
238 }
239 
240 /* Get screen line of status line. -1 means off. */
241 int
242 status_at_line(struct client *c)
243 {
244 	struct session	*s = c->session;
245 
246 	if (c->flags & (CLIENT_STATUSOFF|CLIENT_CONTROL))
247 		return (-1);
248 	if (s->statusat != 1)
249 		return (s->statusat);
250 	return (c->tty.sy - status_line_size(c));
251 }
252 
253 /* Get size of status line for client's session. 0 means off. */
254 u_int
255 status_line_size(struct client *c)
256 {
257 	struct session	*s = c->session;
258 
259 	if (c->flags & (CLIENT_STATUSOFF|CLIENT_CONTROL))
260 		return (0);
261 	if (s == NULL)
262 		return (options_get_number(global_s_options, "status"));
263 	return (s->statuslines);
264 }
265 
266 /* Get window at window list position. */
267 struct style_range *
268 status_get_range(struct client *c, u_int x, u_int y)
269 {
270 	struct status_line	*sl = &c->status;
271 	struct style_range	*sr;
272 
273 	if (y >= nitems(sl->entries))
274 		return (NULL);
275 	TAILQ_FOREACH(sr, &sl->entries[y].ranges, entry) {
276 		if (x >= sr->start && x < sr->end)
277 			return (sr);
278 	}
279 	return (NULL);
280 }
281 
282 /* Free all ranges. */
283 static void
284 status_free_ranges(struct style_ranges *srs)
285 {
286 	struct style_range	*sr, *sr1;
287 
288 	TAILQ_FOREACH_SAFE(sr, srs, entry, sr1) {
289 		TAILQ_REMOVE(srs, sr, entry);
290 		free(sr);
291 	}
292 }
293 
294 /* Save old status line. */
295 static void
296 status_push_screen(struct client *c)
297 {
298 	struct status_line *sl = &c->status;
299 
300 	if (sl->active == &sl->screen) {
301 		sl->active = xmalloc(sizeof *sl->active);
302 		screen_init(sl->active, c->tty.sx, status_line_size(c), 0);
303 	}
304 	sl->references++;
305 }
306 
307 /* Restore old status line. */
308 static void
309 status_pop_screen(struct client *c)
310 {
311 	struct status_line *sl = &c->status;
312 
313 	if (--sl->references == 0) {
314 		screen_free(sl->active);
315 		free(sl->active);
316 		sl->active = &sl->screen;
317 	}
318 }
319 
320 /* Initialize status line. */
321 void
322 status_init(struct client *c)
323 {
324 	struct status_line	*sl = &c->status;
325 	u_int			 i;
326 
327 	for (i = 0; i < nitems(sl->entries); i++)
328 		TAILQ_INIT(&sl->entries[i].ranges);
329 
330 	screen_init(&sl->screen, c->tty.sx, 1, 0);
331 	sl->active = &sl->screen;
332 }
333 
334 /* Free status line. */
335 void
336 status_free(struct client *c)
337 {
338 	struct status_line	*sl = &c->status;
339 	u_int			 i;
340 
341 	for (i = 0; i < nitems(sl->entries); i++) {
342 		status_free_ranges(&sl->entries[i].ranges);
343 		free((void *)sl->entries[i].expanded);
344 	}
345 
346 	if (event_initialized(&sl->timer))
347 		evtimer_del(&sl->timer);
348 
349 	if (sl->active != &sl->screen) {
350 		screen_free(sl->active);
351 		free(sl->active);
352 	}
353 	screen_free(&sl->screen);
354 }
355 
356 /* Draw status line for client. */
357 int
358 status_redraw(struct client *c)
359 {
360 	struct status_line		*sl = &c->status;
361 	struct status_line_entry	*sle;
362 	struct session			*s = c->session;
363 	struct screen_write_ctx		 ctx;
364 	struct grid_cell		 gc;
365 	u_int				 lines, i, n, width = c->tty.sx;
366 	int				 flags, force = 0, changed = 0, fg, bg;
367 	struct options_entry		*o;
368 	union options_value		*ov;
369 	struct format_tree		*ft;
370 	char				*expanded;
371 
372 	log_debug("%s enter", __func__);
373 
374 	/* Shouldn't get here if not the active screen. */
375 	if (sl->active != &sl->screen)
376 		fatalx("not the active screen");
377 
378 	/* No status line? */
379 	lines = status_line_size(c);
380 	if (c->tty.sy == 0 || lines == 0)
381 		return (1);
382 
383 	/* Create format tree. */
384 	flags = FORMAT_STATUS;
385 	if (c->flags & CLIENT_STATUSFORCE)
386 		flags |= FORMAT_FORCE;
387 	ft = format_create(c, NULL, FORMAT_NONE, flags);
388 	format_defaults(ft, c, NULL, NULL, NULL);
389 
390 	/* Set up default colour. */
391 	style_apply(&gc, s->options, "status-style", ft);
392 	fg = options_get_number(s->options, "status-fg");
393 	if (!COLOUR_DEFAULT(fg))
394 		gc.fg = fg;
395 	bg = options_get_number(s->options, "status-bg");
396 	if (!COLOUR_DEFAULT(bg))
397 		gc.bg = bg;
398 	if (!grid_cells_equal(&gc, &sl->style)) {
399 		force = 1;
400 		memcpy(&sl->style, &gc, sizeof sl->style);
401 	}
402 
403 	/* Resize the target screen. */
404 	if (screen_size_x(&sl->screen) != width ||
405 	    screen_size_y(&sl->screen) != lines) {
406 		screen_resize(&sl->screen, width, lines, 0);
407 		changed = force = 1;
408 	}
409 	screen_write_start(&ctx, &sl->screen);
410 
411 	/* Write the status lines. */
412 	o = options_get(s->options, "status-format");
413 	if (o == NULL) {
414 		for (n = 0; n < width * lines; n++)
415 			screen_write_putc(&ctx, &gc, ' ');
416 	} else {
417 		for (i = 0; i < lines; i++) {
418 			screen_write_cursormove(&ctx, 0, i, 0);
419 
420 			ov = options_array_get(o, i);
421 			if (ov == NULL) {
422 				for (n = 0; n < width; n++)
423 					screen_write_putc(&ctx, &gc, ' ');
424 				continue;
425 			}
426 			sle = &sl->entries[i];
427 
428 			expanded = format_expand_time(ft, ov->string);
429 			if (!force &&
430 			    sle->expanded != NULL &&
431 			    strcmp(expanded, sle->expanded) == 0) {
432 				free(expanded);
433 				continue;
434 			}
435 			changed = 1;
436 
437 			for (n = 0; n < width; n++)
438 				screen_write_putc(&ctx, &gc, ' ');
439 			screen_write_cursormove(&ctx, 0, i, 0);
440 
441 			status_free_ranges(&sle->ranges);
442 			format_draw(&ctx, &gc, width, expanded, &sle->ranges,
443 			    0);
444 
445 			free(sle->expanded);
446 			sle->expanded = expanded;
447 		}
448 	}
449 	screen_write_stop(&ctx);
450 
451 	/* Free the format tree. */
452 	format_free(ft);
453 
454 	/* Return if the status line has changed. */
455 	log_debug("%s exit: force=%d, changed=%d", __func__, force, changed);
456 	return (force || changed);
457 }
458 
459 /* Set a status line message. */
460 void
461 status_message_set(struct client *c, int delay, int ignore_styles,
462     int ignore_keys, const char *fmt, ...)
463 {
464 	struct timeval	tv;
465 	va_list		ap;
466 
467 	status_message_clear(c);
468 	status_push_screen(c);
469 
470 	va_start(ap, fmt);
471 	xvasprintf(&c->message_string, fmt, ap);
472 	va_end(ap);
473 
474 	server_add_message("%s message: %s", c->name, c->message_string);
475 
476 	/*
477 	 * With delay -1, the display-time option is used; zero means wait for
478 	 * key press; more than zero is the actual delay time in milliseconds.
479 	 */
480 	if (delay == -1)
481 		delay = options_get_number(c->session->options, "display-time");
482 	if (delay > 0) {
483 		tv.tv_sec = delay / 1000;
484 		tv.tv_usec = (delay % 1000) * 1000L;
485 
486 		if (event_initialized(&c->message_timer))
487 			evtimer_del(&c->message_timer);
488 		evtimer_set(&c->message_timer, status_message_callback, c);
489 
490 		evtimer_add(&c->message_timer, &tv);
491 	}
492 
493 	if (delay != 0)
494 		c->message_ignore_keys = ignore_keys;
495 	c->message_ignore_styles = ignore_styles;
496 
497 	c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
498 	c->flags |= CLIENT_REDRAWSTATUS;
499 }
500 
501 /* Clear status line message. */
502 void
503 status_message_clear(struct client *c)
504 {
505 	if (c->message_string == NULL)
506 		return;
507 
508 	free(c->message_string);
509 	c->message_string = NULL;
510 
511 	if (c->prompt_string == NULL)
512 		c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
513 	c->flags |= CLIENT_ALLREDRAWFLAGS; /* was frozen and may have changed */
514 
515 	status_pop_screen(c);
516 }
517 
518 /* Clear status line message after timer expires. */
519 static void
520 status_message_callback(__unused int fd, __unused short event, void *data)
521 {
522 	struct client	*c = data;
523 
524 	status_message_clear(c);
525 }
526 
527 /* Draw client message on status line of present else on last line. */
528 int
529 status_message_redraw(struct client *c)
530 {
531 	struct status_line	*sl = &c->status;
532 	struct screen_write_ctx	 ctx;
533 	struct session		*s = c->session;
534 	struct screen		 old_screen;
535 	size_t			 len;
536 	u_int			 lines, offset;
537 	struct grid_cell	 gc;
538 	struct format_tree	*ft;
539 
540 	if (c->tty.sx == 0 || c->tty.sy == 0)
541 		return (0);
542 	memcpy(&old_screen, sl->active, sizeof old_screen);
543 
544 	lines = status_line_size(c);
545 	if (lines <= 1)
546 		lines = 1;
547 	screen_init(sl->active, c->tty.sx, lines, 0);
548 
549 	len = screen_write_strlen("%s", c->message_string);
550 	if (len > c->tty.sx)
551 		len = c->tty.sx;
552 
553 	ft = format_create_defaults(NULL, c, NULL, NULL, NULL);
554 	style_apply(&gc, s->options, "message-style", ft);
555 	format_free(ft);
556 
557 	screen_write_start(&ctx, sl->active);
558 	screen_write_fast_copy(&ctx, &sl->screen, 0, 0, c->tty.sx, lines - 1);
559 	screen_write_cursormove(&ctx, 0, lines - 1, 0);
560 	for (offset = 0; offset < c->tty.sx; offset++)
561 		screen_write_putc(&ctx, &gc, ' ');
562 	screen_write_cursormove(&ctx, 0, lines - 1, 0);
563 	if (c->message_ignore_styles)
564 		screen_write_nputs(&ctx, len, &gc, "%s", c->message_string);
565 	else
566 		format_draw(&ctx, &gc, c->tty.sx, c->message_string, NULL, 0);
567 	screen_write_stop(&ctx);
568 
569 	if (grid_compare(sl->active->grid, old_screen.grid) == 0) {
570 		screen_free(&old_screen);
571 		return (0);
572 	}
573 	screen_free(&old_screen);
574 	return (1);
575 }
576 
577 /* Enable status line prompt. */
578 void
579 status_prompt_set(struct client *c, struct cmd_find_state *fs,
580     const char *msg, const char *input, prompt_input_cb inputcb,
581     prompt_free_cb freecb, void *data, int flags, enum prompt_type prompt_type)
582 {
583 	struct format_tree	*ft;
584 	char			*tmp;
585 
586 	if (fs != NULL)
587 		ft = format_create_from_state(NULL, c, fs);
588 	else
589 		ft = format_create_defaults(NULL, c, NULL, NULL, NULL);
590 
591 	if (input == NULL)
592 		input = "";
593 	if (flags & PROMPT_NOFORMAT)
594 		tmp = xstrdup(input);
595 	else
596 		tmp = format_expand_time(ft, input);
597 
598 	status_message_clear(c);
599 	status_prompt_clear(c);
600 	status_push_screen(c);
601 
602 	c->prompt_string = format_expand_time(ft, msg);
603 
604 	if (flags & PROMPT_INCREMENTAL) {
605 		c->prompt_last = xstrdup(tmp);
606 		c->prompt_buffer = utf8_fromcstr("");
607 	} else {
608 		c->prompt_last = NULL;
609 		c->prompt_buffer = utf8_fromcstr(tmp);
610 	}
611 	c->prompt_index = utf8_strlen(c->prompt_buffer);
612 
613 	c->prompt_inputcb = inputcb;
614 	c->prompt_freecb = freecb;
615 	c->prompt_data = data;
616 
617 	memset(c->prompt_hindex, 0, sizeof c->prompt_hindex);
618 
619 	c->prompt_flags = flags;
620 	c->prompt_type = prompt_type;
621 	c->prompt_mode = PROMPT_ENTRY;
622 
623 	if (~flags & PROMPT_INCREMENTAL)
624 		c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
625 	c->flags |= CLIENT_REDRAWSTATUS;
626 
627 	if (flags & PROMPT_INCREMENTAL)
628 		c->prompt_inputcb(c, c->prompt_data, "=", 0);
629 
630 	free(tmp);
631 	format_free(ft);
632 }
633 
634 /* Remove status line prompt. */
635 void
636 status_prompt_clear(struct client *c)
637 {
638 	if (c->prompt_string == NULL)
639 		return;
640 
641 	if (c->prompt_freecb != NULL && c->prompt_data != NULL)
642 		c->prompt_freecb(c->prompt_data);
643 
644 	free(c->prompt_last);
645 	c->prompt_last = NULL;
646 
647 	free(c->prompt_string);
648 	c->prompt_string = NULL;
649 
650 	free(c->prompt_buffer);
651 	c->prompt_buffer = NULL;
652 
653 	free(c->prompt_saved);
654 	c->prompt_saved = NULL;
655 
656 	c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
657 	c->flags |= CLIENT_ALLREDRAWFLAGS; /* was frozen and may have changed */
658 
659 	status_pop_screen(c);
660 }
661 
662 /* Update status line prompt with a new prompt string. */
663 void
664 status_prompt_update(struct client *c, const char *msg, const char *input)
665 {
666 	struct format_tree	*ft;
667 	char			*tmp;
668 
669 	ft = format_create(c, NULL, FORMAT_NONE, 0);
670 	format_defaults(ft, c, NULL, NULL, NULL);
671 
672 	tmp = format_expand_time(ft, input);
673 
674 	free(c->prompt_string);
675 	c->prompt_string = format_expand_time(ft, msg);
676 
677 	free(c->prompt_buffer);
678 	c->prompt_buffer = utf8_fromcstr(tmp);
679 	c->prompt_index = utf8_strlen(c->prompt_buffer);
680 
681 	memset(c->prompt_hindex, 0, sizeof c->prompt_hindex);
682 
683 	c->flags |= CLIENT_REDRAWSTATUS;
684 
685 	free(tmp);
686 	format_free(ft);
687 }
688 
689 /* Draw client prompt on status line of present else on last line. */
690 int
691 status_prompt_redraw(struct client *c)
692 {
693 	struct status_line	*sl = &c->status;
694 	struct screen_write_ctx	 ctx;
695 	struct session		*s = c->session;
696 	struct screen		 old_screen;
697 	u_int			 i, lines, offset, left, start, width;
698 	u_int			 pcursor, pwidth;
699 	struct grid_cell	 gc, cursorgc;
700 	struct format_tree	*ft;
701 
702 	if (c->tty.sx == 0 || c->tty.sy == 0)
703 		return (0);
704 	memcpy(&old_screen, sl->active, sizeof old_screen);
705 
706 	lines = status_line_size(c);
707 	if (lines <= 1)
708 		lines = 1;
709 	screen_init(sl->active, c->tty.sx, lines, 0);
710 
711 	ft = format_create_defaults(NULL, c, NULL, NULL, NULL);
712 	if (c->prompt_mode == PROMPT_COMMAND)
713 		style_apply(&gc, s->options, "message-command-style", ft);
714 	else
715 		style_apply(&gc, s->options, "message-style", ft);
716 	format_free(ft);
717 
718 	memcpy(&cursorgc, &gc, sizeof cursorgc);
719 	cursorgc.attr ^= GRID_ATTR_REVERSE;
720 
721 	start = screen_write_strlen("%s", c->prompt_string);
722 	if (start > c->tty.sx)
723 		start = c->tty.sx;
724 
725 	screen_write_start(&ctx, sl->active);
726 	screen_write_fast_copy(&ctx, &sl->screen, 0, 0, c->tty.sx, lines - 1);
727 	screen_write_cursormove(&ctx, 0, lines - 1, 0);
728 	for (offset = 0; offset < c->tty.sx; offset++)
729 		screen_write_putc(&ctx, &gc, ' ');
730 	screen_write_cursormove(&ctx, 0, lines - 1, 0);
731 	screen_write_nputs(&ctx, start, &gc, "%s", c->prompt_string);
732 	screen_write_cursormove(&ctx, start, lines - 1, 0);
733 
734 	left = c->tty.sx - start;
735 	if (left == 0)
736 		goto finished;
737 
738 	pcursor = utf8_strwidth(c->prompt_buffer, c->prompt_index);
739 	pwidth = utf8_strwidth(c->prompt_buffer, -1);
740 	if (pcursor >= left) {
741 		/*
742 		 * The cursor would be outside the screen so start drawing
743 		 * with it on the right.
744 		 */
745 		offset = (pcursor - left) + 1;
746 		pwidth = left;
747 	} else
748 		offset = 0;
749 	if (pwidth > left)
750 		pwidth = left;
751 	c->prompt_cursor = start + c->prompt_index - offset;
752 
753 	width = 0;
754 	for (i = 0; c->prompt_buffer[i].size != 0; i++) {
755 		if (width < offset) {
756 			width += c->prompt_buffer[i].width;
757 			continue;
758 		}
759 		if (width >= offset + pwidth)
760 			break;
761 		width += c->prompt_buffer[i].width;
762 		if (width > offset + pwidth)
763 			break;
764 
765 		if (i != c->prompt_index) {
766 			utf8_copy(&gc.data, &c->prompt_buffer[i]);
767 			screen_write_cell(&ctx, &gc);
768 		} else {
769 			utf8_copy(&cursorgc.data, &c->prompt_buffer[i]);
770 			screen_write_cell(&ctx, &cursorgc);
771 		}
772 	}
773 	if (sl->active->cx < screen_size_x(sl->active) && c->prompt_index >= i)
774 		screen_write_putc(&ctx, &cursorgc, ' ');
775 
776 finished:
777 	screen_write_stop(&ctx);
778 
779 	if (grid_compare(sl->active->grid, old_screen.grid) == 0) {
780 		screen_free(&old_screen);
781 		return (0);
782 	}
783 	screen_free(&old_screen);
784 	return (1);
785 }
786 
787 /* Is this a separator? */
788 static int
789 status_prompt_in_list(const char *ws, const struct utf8_data *ud)
790 {
791 	if (ud->size != 1 || ud->width != 1)
792 		return (0);
793 	return (strchr(ws, *ud->data) != NULL);
794 }
795 
796 /* Is this a space? */
797 static int
798 status_prompt_space(const struct utf8_data *ud)
799 {
800 	if (ud->size != 1 || ud->width != 1)
801 		return (0);
802 	return (*ud->data == ' ');
803 }
804 
805 /*
806  * Translate key from vi to emacs. Return 0 to drop key, 1 to process the key
807  * as an emacs key; return 2 to append to the buffer.
808  */
809 static int
810 status_prompt_translate_key(struct client *c, key_code key, key_code *new_key)
811 {
812 	if (c->prompt_mode == PROMPT_ENTRY) {
813 		switch (key) {
814 		case '\001': /* C-a */
815 		case '\003': /* C-c */
816 		case '\005': /* C-e */
817 		case '\007': /* C-g */
818 		case '\010': /* C-h */
819 		case '\011': /* Tab */
820 		case '\013': /* C-k */
821 		case '\016': /* C-n */
822 		case '\020': /* C-p */
823 		case '\024': /* C-t */
824 		case '\025': /* C-u */
825 		case '\027': /* C-w */
826 		case '\031': /* C-y */
827 		case '\n':
828 		case '\r':
829 		case KEYC_LEFT|KEYC_CTRL:
830 		case KEYC_RIGHT|KEYC_CTRL:
831 		case KEYC_BSPACE:
832 		case KEYC_DC:
833 		case KEYC_DOWN:
834 		case KEYC_END:
835 		case KEYC_HOME:
836 		case KEYC_LEFT:
837 		case KEYC_RIGHT:
838 		case KEYC_UP:
839 			*new_key = key;
840 			return (1);
841 		case '\033': /* Escape */
842 			c->prompt_mode = PROMPT_COMMAND;
843 			c->flags |= CLIENT_REDRAWSTATUS;
844 			return (0);
845 		}
846 		*new_key = key;
847 		return (2);
848 	}
849 
850 	switch (key) {
851 	case KEYC_BSPACE:
852 		*new_key = KEYC_LEFT;
853 		return (1);
854 	case 'A':
855 	case 'I':
856 	case 'C':
857 	case 's':
858 	case 'a':
859 		c->prompt_mode = PROMPT_ENTRY;
860 		c->flags |= CLIENT_REDRAWSTATUS;
861 		break; /* switch mode and... */
862 	case 'S':
863 		c->prompt_mode = PROMPT_ENTRY;
864 		c->flags |= CLIENT_REDRAWSTATUS;
865 		*new_key = '\025'; /* C-u */
866 		return (1);
867 	case 'i':
868 	case '\033': /* Escape */
869 		c->prompt_mode = PROMPT_ENTRY;
870 		c->flags |= CLIENT_REDRAWSTATUS;
871 		return (0);
872 	}
873 
874 	switch (key) {
875 	case 'A':
876 	case '$':
877 		*new_key = KEYC_END;
878 		return (1);
879 	case 'I':
880 	case '0':
881 	case '^':
882 		*new_key = KEYC_HOME;
883 		return (1);
884 	case 'C':
885 	case 'D':
886 		*new_key = '\013'; /* C-k */
887 		return (1);
888 	case KEYC_BSPACE:
889 	case 'X':
890 		*new_key = KEYC_BSPACE;
891 		return (1);
892 	case 'b':
893 		*new_key = 'b'|KEYC_META;
894 		return (1);
895 	case 'B':
896 		*new_key = 'B'|KEYC_VI;
897 		return (1);
898 	case 'd':
899 		*new_key = '\025'; /* C-u */
900 		return (1);
901 	case 'e':
902 		*new_key = 'e'|KEYC_VI;
903 		return (1);
904 	case 'E':
905 		*new_key = 'E'|KEYC_VI;
906 		return (1);
907 	case 'w':
908 		*new_key = 'w'|KEYC_VI;
909 		return (1);
910 	case 'W':
911 		*new_key = 'W'|KEYC_VI;
912 		return (1);
913 	case 'p':
914 		*new_key = '\031'; /* C-y */
915 		return (1);
916 	case 'q':
917 		*new_key = '\003'; /* C-c */
918 		return (1);
919 	case 's':
920 	case KEYC_DC:
921 	case 'x':
922 		*new_key = KEYC_DC;
923 		return (1);
924 	case KEYC_DOWN:
925 	case 'j':
926 		*new_key = KEYC_DOWN;
927 		return (1);
928 	case KEYC_LEFT:
929 	case 'h':
930 		*new_key = KEYC_LEFT;
931 		return (1);
932 	case 'a':
933 	case KEYC_RIGHT:
934 	case 'l':
935 		*new_key = KEYC_RIGHT;
936 		return (1);
937 	case KEYC_UP:
938 	case 'k':
939 		*new_key = KEYC_UP;
940 		return (1);
941 	case '\010' /* C-h */:
942 	case '\003' /* C-c */:
943 	case '\n':
944 	case '\r':
945 		return (1);
946 	}
947 	return (0);
948 }
949 
950 /* Paste into prompt. */
951 static int
952 status_prompt_paste(struct client *c)
953 {
954 	struct paste_buffer	*pb;
955 	const char		*bufdata;
956 	size_t			 size, n, bufsize;
957 	u_int			 i;
958 	struct utf8_data	*ud, *udp;
959 	enum utf8_state		 more;
960 
961 	size = utf8_strlen(c->prompt_buffer);
962 	if (c->prompt_saved != NULL) {
963 		ud = c->prompt_saved;
964 		n = utf8_strlen(c->prompt_saved);
965 	} else {
966 		if ((pb = paste_get_top(NULL)) == NULL)
967 			return (0);
968 		bufdata = paste_buffer_data(pb, &bufsize);
969 		ud = xreallocarray(NULL, bufsize + 1, sizeof *ud);
970 		udp = ud;
971 		for (i = 0; i != bufsize; /* nothing */) {
972 			more = utf8_open(udp, bufdata[i]);
973 			if (more == UTF8_MORE) {
974 				while (++i != bufsize && more == UTF8_MORE)
975 					more = utf8_append(udp, bufdata[i]);
976 				if (more == UTF8_DONE) {
977 					udp++;
978 					continue;
979 				}
980 				i -= udp->have;
981 			}
982 			if (bufdata[i] <= 31 || bufdata[i] >= 127)
983 				break;
984 			utf8_set(udp, bufdata[i]);
985 			udp++;
986 			i++;
987 		}
988 		udp->size = 0;
989 		n = udp - ud;
990 	}
991 	if (n == 0)
992 		return (0);
993 
994 	c->prompt_buffer = xreallocarray(c->prompt_buffer, size + n + 1,
995 	    sizeof *c->prompt_buffer);
996 	if (c->prompt_index == size) {
997 		memcpy(c->prompt_buffer + c->prompt_index, ud,
998 		    n * sizeof *c->prompt_buffer);
999 		c->prompt_index += n;
1000 		c->prompt_buffer[c->prompt_index].size = 0;
1001 	} else {
1002 		memmove(c->prompt_buffer + c->prompt_index + n,
1003 		    c->prompt_buffer + c->prompt_index,
1004 		    (size + 1 - c->prompt_index) * sizeof *c->prompt_buffer);
1005 		memcpy(c->prompt_buffer + c->prompt_index, ud,
1006 		    n * sizeof *c->prompt_buffer);
1007 		c->prompt_index += n;
1008 	}
1009 
1010 	if (ud != c->prompt_saved)
1011 		free(ud);
1012 	return (1);
1013 }
1014 
1015 /* Finish completion. */
1016 static int
1017 status_prompt_replace_complete(struct client *c, const char *s)
1018 {
1019 	char			 word[64], *allocated = NULL;
1020 	size_t			 size, n, off, idx, used;
1021 	struct utf8_data	*first, *last, *ud;
1022 
1023 	/* Work out where the cursor currently is. */
1024 	idx = c->prompt_index;
1025 	if (idx != 0)
1026 		idx--;
1027 	size = utf8_strlen(c->prompt_buffer);
1028 
1029 	/* Find the word we are in. */
1030 	first = &c->prompt_buffer[idx];
1031 	while (first > c->prompt_buffer && !status_prompt_space(first))
1032 		first--;
1033 	while (first->size != 0 && status_prompt_space(first))
1034 		first++;
1035 	last = &c->prompt_buffer[idx];
1036 	while (last->size != 0 && !status_prompt_space(last))
1037 		last++;
1038 	while (last > c->prompt_buffer && status_prompt_space(last))
1039 		last--;
1040 	if (last->size != 0)
1041 		last++;
1042 	if (last < first)
1043 		return (0);
1044 	if (s == NULL) {
1045 		used = 0;
1046 		for (ud = first; ud < last; ud++) {
1047 			if (used + ud->size >= sizeof word)
1048 				break;
1049 			memcpy(word + used, ud->data, ud->size);
1050 			used += ud->size;
1051 		}
1052 		if (ud != last)
1053 			return (0);
1054 		word[used] = '\0';
1055 	}
1056 
1057 	/* Try to complete it. */
1058 	if (s == NULL) {
1059 		allocated = status_prompt_complete(c, word,
1060 		    first - c->prompt_buffer);
1061 		if (allocated == NULL)
1062 			return (0);
1063 		s = allocated;
1064 	}
1065 
1066 	/* Trim out word. */
1067 	n = size - (last - c->prompt_buffer) + 1; /* with \0 */
1068 	memmove(first, last, n * sizeof *c->prompt_buffer);
1069 	size -= last - first;
1070 
1071 	/* Insert the new word. */
1072 	size += strlen(s);
1073 	off = first - c->prompt_buffer;
1074 	c->prompt_buffer = xreallocarray(c->prompt_buffer, size + 1,
1075 	    sizeof *c->prompt_buffer);
1076 	first = c->prompt_buffer + off;
1077 	memmove(first + strlen(s), first, n * sizeof *c->prompt_buffer);
1078 	for (idx = 0; idx < strlen(s); idx++)
1079 		utf8_set(&first[idx], s[idx]);
1080 	c->prompt_index = (first - c->prompt_buffer) + strlen(s);
1081 
1082 	free(allocated);
1083 	return (1);
1084 }
1085 
1086 /* Prompt forward to the next beginning of a word. */
1087 static void
1088 status_prompt_forward_word(struct client *c, size_t size, int vi,
1089     const char *separators)
1090 {
1091 	size_t		 idx = c->prompt_index;
1092 	int		 word_is_separators;
1093 
1094 	/* In emacs mode, skip until the first non-whitespace character. */
1095 	if (!vi)
1096 		while (idx != size &&
1097 		    status_prompt_space(&c->prompt_buffer[idx]))
1098 			idx++;
1099 
1100 	/* Can't move forward if we're already at the end. */
1101 	if (idx == size) {
1102 		c->prompt_index = idx;
1103 		return;
1104 	}
1105 
1106 	/* Determine the current character class (separators or not). */
1107 	word_is_separators = status_prompt_in_list(separators,
1108 	    &c->prompt_buffer[idx]) &&
1109 	    !status_prompt_space(&c->prompt_buffer[idx]);
1110 
1111 	/* Skip ahead until the first space or opposite character class. */
1112 	do {
1113 		idx++;
1114 		if (status_prompt_space(&c->prompt_buffer[idx])) {
1115 			/* In vi mode, go to the start of the next word. */
1116 			if (vi)
1117 				while (idx != size &&
1118 				    status_prompt_space(&c->prompt_buffer[idx]))
1119 					idx++;
1120 			break;
1121 		}
1122 	} while (idx != size && word_is_separators == status_prompt_in_list(
1123 	    separators, &c->prompt_buffer[idx]));
1124 
1125 	c->prompt_index = idx;
1126 }
1127 
1128 /* Prompt forward to the next end of a word. */
1129 static void
1130 status_prompt_end_word(struct client *c, size_t size, const char *separators)
1131 {
1132 	size_t		 idx = c->prompt_index;
1133 	int		 word_is_separators;
1134 
1135 	/* Can't move forward if we're already at the end. */
1136 	if (idx == size)
1137 		return;
1138 
1139 	/* Find the next word. */
1140 	do {
1141 		idx++;
1142 		if (idx == size) {
1143 			c->prompt_index = idx;
1144 			return;
1145 		}
1146 	} while (status_prompt_space(&c->prompt_buffer[idx]));
1147 
1148 	/* Determine the character class (separators or not). */
1149 	word_is_separators = status_prompt_in_list(separators,
1150 	    &c->prompt_buffer[idx]);
1151 
1152 	/* Skip ahead until the next space or opposite character class. */
1153 	do {
1154 		idx++;
1155 		if (idx == size)
1156 			break;
1157 	} while (!status_prompt_space(&c->prompt_buffer[idx]) &&
1158 	    word_is_separators == status_prompt_in_list(separators,
1159 	    &c->prompt_buffer[idx]));
1160 
1161 	/* Back up to the previous character to stop at the end of the word. */
1162 	c->prompt_index = idx - 1;
1163 }
1164 
1165 /* Prompt backward to the previous beginning of a word. */
1166 static void
1167 status_prompt_backward_word(struct client *c, const char *separators)
1168 {
1169 	size_t	idx = c->prompt_index;
1170 	int	word_is_separators;
1171 
1172 	/* Find non-whitespace. */
1173 	while (idx != 0) {
1174 		--idx;
1175 		if (!status_prompt_space(&c->prompt_buffer[idx]))
1176 			break;
1177 	}
1178 	word_is_separators = status_prompt_in_list(separators,
1179 	    &c->prompt_buffer[idx]);
1180 
1181 	/* Find the character before the beginning of the word. */
1182 	while (idx != 0) {
1183 		--idx;
1184 		if (status_prompt_space(&c->prompt_buffer[idx]) ||
1185 		    word_is_separators != status_prompt_in_list(separators,
1186 		    &c->prompt_buffer[idx])) {
1187 			/* Go back to the word. */
1188 			idx++;
1189 			break;
1190 		}
1191 	}
1192 	c->prompt_index = idx;
1193 }
1194 
1195 /* Handle keys in prompt. */
1196 int
1197 status_prompt_key(struct client *c, key_code key)
1198 {
1199 	struct options		*oo = c->session->options;
1200 	char			*s, *cp, prefix = '=';
1201 	const char		*histstr, *separators = NULL, *keystring;
1202 	size_t			 size, idx;
1203 	struct utf8_data	 tmp;
1204 	int			 keys, word_is_separators;
1205 
1206 	if (c->prompt_flags & PROMPT_KEY) {
1207 		keystring = key_string_lookup_key(key, 0);
1208 		c->prompt_inputcb(c, c->prompt_data, keystring, 1);
1209 		status_prompt_clear(c);
1210 		return (0);
1211 	}
1212 	size = utf8_strlen(c->prompt_buffer);
1213 
1214 	if (c->prompt_flags & PROMPT_NUMERIC) {
1215 		if (key >= '0' && key <= '9')
1216 			goto append_key;
1217 		s = utf8_tocstr(c->prompt_buffer);
1218 		c->prompt_inputcb(c, c->prompt_data, s, 1);
1219 		status_prompt_clear(c);
1220 		free(s);
1221 		return (1);
1222 	}
1223 	key &= ~KEYC_MASK_FLAGS;
1224 
1225 	keys = options_get_number(c->session->options, "status-keys");
1226 	if (keys == MODEKEY_VI) {
1227 		switch (status_prompt_translate_key(c, key, &key)) {
1228 		case 1:
1229 			goto process_key;
1230 		case 2:
1231 			goto append_key;
1232 		default:
1233 			return (0);
1234 		}
1235 	}
1236 
1237 process_key:
1238 	switch (key) {
1239 	case KEYC_LEFT:
1240 	case '\002': /* C-b */
1241 		if (c->prompt_index > 0) {
1242 			c->prompt_index--;
1243 			break;
1244 		}
1245 		break;
1246 	case KEYC_RIGHT:
1247 	case '\006': /* C-f */
1248 		if (c->prompt_index < size) {
1249 			c->prompt_index++;
1250 			break;
1251 		}
1252 		break;
1253 	case KEYC_HOME:
1254 	case '\001': /* C-a */
1255 		if (c->prompt_index != 0) {
1256 			c->prompt_index = 0;
1257 			break;
1258 		}
1259 		break;
1260 	case KEYC_END:
1261 	case '\005': /* C-e */
1262 		if (c->prompt_index != size) {
1263 			c->prompt_index = size;
1264 			break;
1265 		}
1266 		break;
1267 	case '\011': /* Tab */
1268 		if (status_prompt_replace_complete(c, NULL))
1269 			goto changed;
1270 		break;
1271 	case KEYC_BSPACE:
1272 	case '\010': /* C-h */
1273 		if (c->prompt_index != 0) {
1274 			if (c->prompt_index == size)
1275 				c->prompt_buffer[--c->prompt_index].size = 0;
1276 			else {
1277 				memmove(c->prompt_buffer + c->prompt_index - 1,
1278 				    c->prompt_buffer + c->prompt_index,
1279 				    (size + 1 - c->prompt_index) *
1280 				    sizeof *c->prompt_buffer);
1281 				c->prompt_index--;
1282 			}
1283 			goto changed;
1284 		}
1285 		break;
1286 	case KEYC_DC:
1287 	case '\004': /* C-d */
1288 		if (c->prompt_index != size) {
1289 			memmove(c->prompt_buffer + c->prompt_index,
1290 			    c->prompt_buffer + c->prompt_index + 1,
1291 			    (size + 1 - c->prompt_index) *
1292 			    sizeof *c->prompt_buffer);
1293 			goto changed;
1294 		}
1295 		break;
1296 	case '\025': /* C-u */
1297 		c->prompt_buffer[0].size = 0;
1298 		c->prompt_index = 0;
1299 		goto changed;
1300 	case '\013': /* C-k */
1301 		if (c->prompt_index < size) {
1302 			c->prompt_buffer[c->prompt_index].size = 0;
1303 			goto changed;
1304 		}
1305 		break;
1306 	case '\027': /* C-w */
1307 		separators = options_get_string(oo, "word-separators");
1308 		idx = c->prompt_index;
1309 
1310 		/* Find non-whitespace. */
1311 		while (idx != 0) {
1312 			idx--;
1313 			if (!status_prompt_space(&c->prompt_buffer[idx]))
1314 				break;
1315 		}
1316 		word_is_separators = status_prompt_in_list(separators,
1317 		    &c->prompt_buffer[idx]);
1318 
1319 		/* Find the character before the beginning of the word. */
1320 		while (idx != 0) {
1321 			idx--;
1322 			if (status_prompt_space(&c->prompt_buffer[idx]) ||
1323 			    word_is_separators != status_prompt_in_list(
1324 			    separators, &c->prompt_buffer[idx])) {
1325 				/* Go back to the word. */
1326 				idx++;
1327 				break;
1328 			}
1329 		}
1330 
1331 		free(c->prompt_saved);
1332 		c->prompt_saved = xcalloc(sizeof *c->prompt_buffer,
1333 		    (c->prompt_index - idx) + 1);
1334 		memcpy(c->prompt_saved, c->prompt_buffer + idx,
1335 		    (c->prompt_index - idx) * sizeof *c->prompt_buffer);
1336 
1337 		memmove(c->prompt_buffer + idx,
1338 		    c->prompt_buffer + c->prompt_index,
1339 		    (size + 1 - c->prompt_index) *
1340 		    sizeof *c->prompt_buffer);
1341 		memset(c->prompt_buffer + size - (c->prompt_index - idx),
1342 		    '\0', (c->prompt_index - idx) * sizeof *c->prompt_buffer);
1343 		c->prompt_index = idx;
1344 
1345 		goto changed;
1346 	case KEYC_RIGHT|KEYC_CTRL:
1347 	case 'f'|KEYC_META:
1348 		separators = options_get_string(oo, "word-separators");
1349 		status_prompt_forward_word(c, size, 0, separators);
1350 		goto changed;
1351 	case 'E'|KEYC_VI:
1352 		status_prompt_end_word(c, size, "");
1353 		goto changed;
1354 	case 'e'|KEYC_VI:
1355 		separators = options_get_string(oo, "word-separators");
1356 		status_prompt_end_word(c, size, separators);
1357 		goto changed;
1358 	case 'W'|KEYC_VI:
1359 		status_prompt_forward_word(c, size, 1, "");
1360 		goto changed;
1361 	case 'w'|KEYC_VI:
1362 		separators = options_get_string(oo, "word-separators");
1363 		status_prompt_forward_word(c, size, 1, separators);
1364 		goto changed;
1365 	case 'B'|KEYC_VI:
1366 		status_prompt_backward_word(c, "");
1367 		goto changed;
1368 	case KEYC_LEFT|KEYC_CTRL:
1369 	case 'b'|KEYC_META:
1370 		separators = options_get_string(oo, "word-separators");
1371 		status_prompt_backward_word(c, separators);
1372 		goto changed;
1373 	case KEYC_UP:
1374 	case '\020': /* C-p */
1375 		histstr = status_prompt_up_history(c->prompt_hindex,
1376 		    c->prompt_type);
1377 		if (histstr == NULL)
1378 			break;
1379 		free(c->prompt_buffer);
1380 		c->prompt_buffer = utf8_fromcstr(histstr);
1381 		c->prompt_index = utf8_strlen(c->prompt_buffer);
1382 		goto changed;
1383 	case KEYC_DOWN:
1384 	case '\016': /* C-n */
1385 		histstr = status_prompt_down_history(c->prompt_hindex,
1386 		    c->prompt_type);
1387 		if (histstr == NULL)
1388 			break;
1389 		free(c->prompt_buffer);
1390 		c->prompt_buffer = utf8_fromcstr(histstr);
1391 		c->prompt_index = utf8_strlen(c->prompt_buffer);
1392 		goto changed;
1393 	case '\031': /* C-y */
1394 		if (status_prompt_paste(c))
1395 			goto changed;
1396 		break;
1397 	case '\024': /* C-t */
1398 		idx = c->prompt_index;
1399 		if (idx < size)
1400 			idx++;
1401 		if (idx >= 2) {
1402 			utf8_copy(&tmp, &c->prompt_buffer[idx - 2]);
1403 			utf8_copy(&c->prompt_buffer[idx - 2],
1404 			    &c->prompt_buffer[idx - 1]);
1405 			utf8_copy(&c->prompt_buffer[idx - 1], &tmp);
1406 			c->prompt_index = idx;
1407 			goto changed;
1408 		}
1409 		break;
1410 	case '\r':
1411 	case '\n':
1412 		s = utf8_tocstr(c->prompt_buffer);
1413 		if (*s != '\0')
1414 			status_prompt_add_history(s, c->prompt_type);
1415 		if (c->prompt_inputcb(c, c->prompt_data, s, 1) == 0)
1416 			status_prompt_clear(c);
1417 		free(s);
1418 		break;
1419 	case '\033': /* Escape */
1420 	case '\003': /* C-c */
1421 	case '\007': /* C-g */
1422 		if (c->prompt_inputcb(c, c->prompt_data, NULL, 1) == 0)
1423 			status_prompt_clear(c);
1424 		break;
1425 	case '\022': /* C-r */
1426 		if (~c->prompt_flags & PROMPT_INCREMENTAL)
1427 			break;
1428 		if (c->prompt_buffer[0].size == 0) {
1429 			prefix = '=';
1430 			free(c->prompt_buffer);
1431 			c->prompt_buffer = utf8_fromcstr(c->prompt_last);
1432 			c->prompt_index = utf8_strlen(c->prompt_buffer);
1433 		} else
1434 			prefix = '-';
1435 		goto changed;
1436 	case '\023': /* C-s */
1437 		if (~c->prompt_flags & PROMPT_INCREMENTAL)
1438 			break;
1439 		if (c->prompt_buffer[0].size == 0) {
1440 			prefix = '=';
1441 			free(c->prompt_buffer);
1442 			c->prompt_buffer = utf8_fromcstr(c->prompt_last);
1443 			c->prompt_index = utf8_strlen(c->prompt_buffer);
1444 		} else
1445 			prefix = '+';
1446 		goto changed;
1447 	default:
1448 		goto append_key;
1449 	}
1450 
1451 	c->flags |= CLIENT_REDRAWSTATUS;
1452 	return (0);
1453 
1454 append_key:
1455 	if (key <= 0x1f || (key >= KEYC_BASE && key < KEYC_BASE_END))
1456 		return (0);
1457 	if (key <= 0x7f)
1458 		utf8_set(&tmp, key);
1459 	else if (KEYC_IS_UNICODE(key))
1460 		utf8_to_data(key, &tmp);
1461 	else
1462 		return (0);
1463 
1464 	c->prompt_buffer = xreallocarray(c->prompt_buffer, size + 2,
1465 	    sizeof *c->prompt_buffer);
1466 
1467 	if (c->prompt_index == size) {
1468 		utf8_copy(&c->prompt_buffer[c->prompt_index], &tmp);
1469 		c->prompt_index++;
1470 		c->prompt_buffer[c->prompt_index].size = 0;
1471 	} else {
1472 		memmove(c->prompt_buffer + c->prompt_index + 1,
1473 		    c->prompt_buffer + c->prompt_index,
1474 		    (size + 1 - c->prompt_index) *
1475 		    sizeof *c->prompt_buffer);
1476 		utf8_copy(&c->prompt_buffer[c->prompt_index], &tmp);
1477 		c->prompt_index++;
1478 	}
1479 
1480 	if (c->prompt_flags & PROMPT_SINGLE) {
1481 		if (utf8_strlen(c->prompt_buffer) != 1)
1482 			status_prompt_clear(c);
1483 		else {
1484 			s = utf8_tocstr(c->prompt_buffer);
1485 			if (c->prompt_inputcb(c, c->prompt_data, s, 1) == 0)
1486 				status_prompt_clear(c);
1487 			free(s);
1488 		}
1489 	}
1490 
1491 changed:
1492 	c->flags |= CLIENT_REDRAWSTATUS;
1493 	if (c->prompt_flags & PROMPT_INCREMENTAL) {
1494 		s = utf8_tocstr(c->prompt_buffer);
1495 		xasprintf(&cp, "%c%s", prefix, s);
1496 		c->prompt_inputcb(c, c->prompt_data, cp, 0);
1497 		free(cp);
1498 		free(s);
1499 	}
1500 	return (0);
1501 }
1502 
1503 /* Get previous line from the history. */
1504 static const char *
1505 status_prompt_up_history(u_int *idx, u_int type)
1506 {
1507 	/*
1508 	 * History runs from 0 to size - 1. Index is from 0 to size. Zero is
1509 	 * empty.
1510 	 */
1511 
1512 	if (status_prompt_hsize[type] == 0 ||
1513 	    idx[type] == status_prompt_hsize[type])
1514 		return (NULL);
1515 	idx[type]++;
1516 	return (status_prompt_hlist[type][status_prompt_hsize[type] - idx[type]]);
1517 }
1518 
1519 /* Get next line from the history. */
1520 static const char *
1521 status_prompt_down_history(u_int *idx, u_int type)
1522 {
1523 	if (status_prompt_hsize[type] == 0 || idx[type] == 0)
1524 		return ("");
1525 	idx[type]--;
1526 	if (idx[type] == 0)
1527 		return ("");
1528 	return (status_prompt_hlist[type][status_prompt_hsize[type] - idx[type]]);
1529 }
1530 
1531 /* Add line to the history. */
1532 static void
1533 status_prompt_add_history(const char *line, u_int type)
1534 {
1535 	u_int	i, oldsize, newsize, freecount, hlimit, new = 1;
1536 	size_t	movesize;
1537 
1538 	oldsize = status_prompt_hsize[type];
1539 	if (oldsize > 0 &&
1540 	    strcmp(status_prompt_hlist[type][oldsize - 1], line) == 0)
1541 		new = 0;
1542 
1543 	hlimit = options_get_number(global_options, "prompt-history-limit");
1544 	if (hlimit > oldsize) {
1545 		if (new == 0)
1546 			return;
1547 		newsize = oldsize + new;
1548 	} else {
1549 		newsize = hlimit;
1550 		freecount = oldsize + new - newsize;
1551 		if (freecount > oldsize)
1552 			freecount = oldsize;
1553 		if (freecount == 0)
1554 			return;
1555 		for (i = 0; i < freecount; i++)
1556 			free(status_prompt_hlist[type][i]);
1557 		movesize = (oldsize - freecount) *
1558 		    sizeof *status_prompt_hlist[type];
1559 		if (movesize > 0) {
1560 			memmove(&status_prompt_hlist[type][0],
1561 			    &status_prompt_hlist[type][freecount], movesize);
1562 		}
1563 	}
1564 
1565 	if (newsize == 0) {
1566 		free(status_prompt_hlist[type]);
1567 		status_prompt_hlist[type] = NULL;
1568 	} else if (newsize != oldsize) {
1569 		status_prompt_hlist[type] =
1570 		    xreallocarray(status_prompt_hlist[type], newsize,
1571 			sizeof *status_prompt_hlist[type]);
1572 	}
1573 
1574 	if (new == 1 && newsize > 0)
1575 		status_prompt_hlist[type][newsize - 1] = xstrdup(line);
1576 	status_prompt_hsize[type] = newsize;
1577 }
1578 
1579 /* Build completion list. */
1580 static char **
1581 status_prompt_complete_list(u_int *size, const char *s, int at_start)
1582 {
1583 	char					**list = NULL;
1584 	const char				**layout, *value, *cp;
1585 	const struct cmd_entry			**cmdent;
1586 	const struct options_table_entry	 *oe;
1587 	size_t					  slen = strlen(s), valuelen;
1588 	struct options_entry			 *o;
1589 	struct options_array_item		 *a;
1590 	const char				 *layouts[] = {
1591 		"even-horizontal", "even-vertical", "main-horizontal",
1592 		"main-vertical", "tiled", NULL
1593 	};
1594 
1595 	*size = 0;
1596 	for (cmdent = cmd_table; *cmdent != NULL; cmdent++) {
1597 		if (strncmp((*cmdent)->name, s, slen) == 0) {
1598 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1599 			list[(*size)++] = xstrdup((*cmdent)->name);
1600 		}
1601 		if ((*cmdent)->alias != NULL &&
1602 		    strncmp((*cmdent)->alias, s, slen) == 0) {
1603 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1604 			list[(*size)++] = xstrdup((*cmdent)->alias);
1605 		}
1606 	}
1607 	o = options_get_only(global_options, "command-alias");
1608 	if (o != NULL) {
1609 		a = options_array_first(o);
1610 		while (a != NULL) {
1611 			value = options_array_item_value(a)->string;
1612 			if ((cp = strchr(value, '=')) == NULL)
1613 				goto next;
1614 			valuelen = cp - value;
1615 			if (slen > valuelen || strncmp(value, s, slen) != 0)
1616 				goto next;
1617 
1618 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1619 			list[(*size)++] = xstrndup(value, valuelen);
1620 
1621 		next:
1622 			a = options_array_next(a);
1623 		}
1624 	}
1625 	if (at_start)
1626 		return (list);
1627 
1628 	for (oe = options_table; oe->name != NULL; oe++) {
1629 		if (strncmp(oe->name, s, slen) == 0) {
1630 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1631 			list[(*size)++] = xstrdup(oe->name);
1632 		}
1633 	}
1634 	for (layout = layouts; *layout != NULL; layout++) {
1635 		if (strncmp(*layout, s, slen) == 0) {
1636 			list = xreallocarray(list, (*size) + 1, sizeof *list);
1637 			list[(*size)++] = xstrdup(*layout);
1638 		}
1639 	}
1640 	return (list);
1641 }
1642 
1643 /* Find longest prefix. */
1644 static char *
1645 status_prompt_complete_prefix(char **list, u_int size)
1646 {
1647 	char	 *out;
1648 	u_int	  i;
1649 	size_t	  j;
1650 
1651 	if (list == NULL || size == 0)
1652 		return (NULL);
1653 	out = xstrdup(list[0]);
1654 	for (i = 1; i < size; i++) {
1655 		j = strlen(list[i]);
1656 		if (j > strlen(out))
1657 			j = strlen(out);
1658 		for (; j > 0; j--) {
1659 			if (out[j - 1] != list[i][j - 1])
1660 				out[j - 1] = '\0';
1661 		}
1662 	}
1663 	return (out);
1664 }
1665 
1666 /* Complete word menu callback. */
1667 static void
1668 status_prompt_menu_callback(__unused struct menu *menu, u_int idx, key_code key,
1669     void *data)
1670 {
1671 	struct status_prompt_menu	*spm = data;
1672 	struct client			*c = spm->c;
1673 	u_int				 i;
1674 	char				*s;
1675 
1676 	if (key != KEYC_NONE) {
1677 		idx += spm->start;
1678 		if (spm->flag == '\0')
1679 			s = xstrdup(spm->list[idx]);
1680 		else
1681 			xasprintf(&s, "-%c%s", spm->flag, spm->list[idx]);
1682 		if (c->prompt_type == PROMPT_TYPE_WINDOW_TARGET) {
1683 			free(c->prompt_buffer);
1684 			c->prompt_buffer = utf8_fromcstr(s);
1685 			c->prompt_index = utf8_strlen(c->prompt_buffer);
1686 			c->flags |= CLIENT_REDRAWSTATUS;
1687 		} else if (status_prompt_replace_complete(c, s))
1688 			c->flags |= CLIENT_REDRAWSTATUS;
1689 		free(s);
1690 	}
1691 
1692 	for (i = 0; i < spm->size; i++)
1693 		free(spm->list[i]);
1694 	free(spm->list);
1695 }
1696 
1697 /* Show complete word menu. */
1698 static int
1699 status_prompt_complete_list_menu(struct client *c, char **list, u_int size,
1700     u_int offset, char flag)
1701 {
1702 	struct menu			*menu;
1703 	struct menu_item		 item;
1704 	struct status_prompt_menu	*spm;
1705 	u_int				 lines = status_line_size(c), height, i;
1706 	u_int				 py;
1707 
1708 	if (size <= 1)
1709 		return (0);
1710 	if (c->tty.sy - lines < 3)
1711 		return (0);
1712 
1713 	spm = xmalloc(sizeof *spm);
1714 	spm->c = c;
1715 	spm->size = size;
1716 	spm->list = list;
1717 	spm->flag = flag;
1718 
1719 	height = c->tty.sy - lines - 2;
1720 	if (height > 10)
1721 		height = 10;
1722 	if (height > size)
1723 		height = size;
1724 	spm->start = size - height;
1725 
1726 	menu = menu_create("");
1727 	for (i = spm->start; i < size; i++) {
1728 		item.name = list[i];
1729 		item.key = '0' + (i - spm->start);
1730 		item.command = NULL;
1731 		menu_add_item(menu, &item, NULL, c, NULL);
1732 	}
1733 
1734 	if (options_get_number(c->session->options, "status-position") == 0)
1735 		py = lines;
1736 	else
1737 		py = c->tty.sy - 3 - height;
1738 	offset += utf8_cstrwidth(c->prompt_string);
1739 	if (offset > 2)
1740 		offset -= 2;
1741 	else
1742 		offset = 0;
1743 
1744 	if (menu_display(menu, MENU_NOMOUSE|MENU_TAB, NULL, offset,
1745 	    py, c, NULL, status_prompt_menu_callback, spm) != 0) {
1746 		menu_free(menu);
1747 		free(spm);
1748 		return (0);
1749 	}
1750 	return (1);
1751 }
1752 
1753 /* Show complete word menu. */
1754 static char *
1755 status_prompt_complete_window_menu(struct client *c, struct session *s,
1756     const char *word, u_int offset, char flag)
1757 {
1758 	struct menu			 *menu;
1759 	struct menu_item		  item;
1760 	struct status_prompt_menu	 *spm;
1761 	struct winlink			 *wl;
1762 	char				**list = NULL, *tmp;
1763 	u_int				  lines = status_line_size(c), height;
1764 	u_int				  py, size = 0;
1765 
1766 	if (c->tty.sy - lines < 3)
1767 		return (NULL);
1768 
1769 	spm = xmalloc(sizeof *spm);
1770 	spm->c = c;
1771 	spm->flag = flag;
1772 
1773 	height = c->tty.sy - lines - 2;
1774 	if (height > 10)
1775 		height = 10;
1776 	spm->start = 0;
1777 
1778 	menu = menu_create("");
1779 	RB_FOREACH(wl, winlinks, &s->windows) {
1780 		if (word != NULL && *word != '\0') {
1781 			xasprintf(&tmp, "%d", wl->idx);
1782 			if (strncmp(tmp, word, strlen(word)) != 0) {
1783 				free(tmp);
1784 				continue;
1785 			}
1786 			free(tmp);
1787 		}
1788 
1789 		list = xreallocarray(list, size + 1, sizeof *list);
1790 		if (c->prompt_type == PROMPT_TYPE_WINDOW_TARGET) {
1791 			xasprintf(&tmp, "%d (%s)", wl->idx, wl->window->name);
1792 			xasprintf(&list[size++], "%d", wl->idx);
1793 		} else {
1794 			xasprintf(&tmp, "%s:%d (%s)", s->name, wl->idx,
1795 			    wl->window->name);
1796 			xasprintf(&list[size++], "%s:%d", s->name, wl->idx);
1797 		}
1798 		item.name = tmp;
1799 		item.key = '0' + size - 1;
1800 		item.command = NULL;
1801 		menu_add_item(menu, &item, NULL, NULL, NULL);
1802 		free(tmp);
1803 
1804 		if (size == height)
1805 			break;
1806 	}
1807 	if (size == 0) {
1808 		menu_free(menu);
1809 		return (NULL);
1810 	}
1811 	if (size == 1) {
1812 		menu_free(menu);
1813 		if (flag != '\0') {
1814 			xasprintf(&tmp, "-%c%s", flag, list[0]);
1815 			free(list[0]);
1816 		} else
1817 			tmp = list[0];
1818 		free(list);
1819 		return (tmp);
1820 	}
1821 	if (height > size)
1822 		height = size;
1823 
1824 	spm->size = size;
1825 	spm->list = list;
1826 
1827 	if (options_get_number(c->session->options, "status-position") == 0)
1828 		py = lines;
1829 	else
1830 		py = c->tty.sy - 3 - height;
1831 	offset += utf8_cstrwidth(c->prompt_string);
1832 	if (offset > 2)
1833 		offset -= 2;
1834 	else
1835 		offset = 0;
1836 
1837 	if (menu_display(menu, MENU_NOMOUSE|MENU_TAB, NULL, offset,
1838 	    py, c, NULL, status_prompt_menu_callback, spm) != 0) {
1839 		menu_free(menu);
1840 		free(spm);
1841 		return (NULL);
1842 	}
1843 	return (NULL);
1844 }
1845 
1846 /* Sort complete list. */
1847 static int
1848 status_prompt_complete_sort(const void *a, const void *b)
1849 {
1850 	const char	**aa = (const char **)a, **bb = (const char **)b;
1851 
1852 	return (strcmp(*aa, *bb));
1853 }
1854 
1855 /* Complete a session. */
1856 static char *
1857 status_prompt_complete_session(char ***list, u_int *size, const char *s,
1858     char flag)
1859 {
1860 	struct session	*loop;
1861 	char		*out, *tmp, n[11];
1862 
1863 	RB_FOREACH(loop, sessions, &sessions) {
1864 		if (*s == '\0' || strncmp(loop->name, s, strlen(s)) == 0) {
1865 			*list = xreallocarray(*list, (*size) + 2,
1866 			    sizeof **list);
1867 			xasprintf(&(*list)[(*size)++], "%s:", loop->name);
1868 		} else if (*s == '$') {
1869 			xsnprintf(n, sizeof n, "%u", loop->id);
1870 			if (s[1] == '\0' ||
1871 			    strncmp(n, s + 1, strlen(s) - 1) == 0) {
1872 				*list = xreallocarray(*list, (*size) + 2,
1873 				    sizeof **list);
1874 				xasprintf(&(*list)[(*size)++], "$%s:", n);
1875 			}
1876 		}
1877 	}
1878 	out = status_prompt_complete_prefix(*list, *size);
1879 	if (out != NULL && flag != '\0') {
1880 		xasprintf(&tmp, "-%c%s", flag, out);
1881 		free(out);
1882 		out = tmp;
1883 	}
1884 	return (out);
1885 }
1886 
1887 /* Complete word. */
1888 static char *
1889 status_prompt_complete(struct client *c, const char *word, u_int offset)
1890 {
1891 	struct session	 *session;
1892 	const char	 *s, *colon;
1893 	char		**list = NULL, *copy = NULL, *out = NULL;
1894 	char		  flag = '\0';
1895 	u_int		  size = 0, i;
1896 
1897 	if (*word == '\0' &&
1898 	    c->prompt_type != PROMPT_TYPE_TARGET &&
1899 	    c->prompt_type != PROMPT_TYPE_WINDOW_TARGET)
1900 		return (NULL);
1901 
1902 	if (c->prompt_type != PROMPT_TYPE_TARGET &&
1903 	    c->prompt_type != PROMPT_TYPE_WINDOW_TARGET &&
1904 	    strncmp(word, "-t", 2) != 0 &&
1905 	    strncmp(word, "-s", 2) != 0) {
1906 		list = status_prompt_complete_list(&size, word, offset == 0);
1907 		if (size == 0)
1908 			out = NULL;
1909 		else if (size == 1)
1910 			xasprintf(&out, "%s ", list[0]);
1911 		else
1912 			out = status_prompt_complete_prefix(list, size);
1913 		goto found;
1914 	}
1915 
1916 	if (c->prompt_type == PROMPT_TYPE_TARGET ||
1917 	    c->prompt_type == PROMPT_TYPE_WINDOW_TARGET) {
1918 		s = word;
1919 		flag = '\0';
1920 	} else {
1921 		s = word + 2;
1922 		flag = word[1];
1923 		offset += 2;
1924 	}
1925 
1926 	/* If this is a window completion, open the window menu. */
1927 	if (c->prompt_type == PROMPT_TYPE_WINDOW_TARGET) {
1928 		out = status_prompt_complete_window_menu(c, c->session, s,
1929 		    offset, '\0');
1930 		goto found;
1931 	}
1932 	colon = strchr(s, ':');
1933 
1934 	/* If there is no colon, complete as a session. */
1935 	if (colon == NULL) {
1936 		out = status_prompt_complete_session(&list, &size, s, flag);
1937 		goto found;
1938 	}
1939 
1940 	/* If there is a colon but no period, find session and show a menu. */
1941 	if (strchr(colon + 1, '.') == NULL) {
1942 		if (*s == ':')
1943 			session = c->session;
1944 		else {
1945 			copy = xstrdup(s);
1946 			*strchr(copy, ':') = '\0';
1947 			session = session_find(copy);
1948 			free(copy);
1949 			if (session == NULL)
1950 				goto found;
1951 		}
1952 		out = status_prompt_complete_window_menu(c, session, colon + 1,
1953 		    offset, flag);
1954 		if (out == NULL)
1955 			return (NULL);
1956 	}
1957 
1958 found:
1959 	if (size != 0) {
1960 		qsort(list, size, sizeof *list, status_prompt_complete_sort);
1961 		for (i = 0; i < size; i++)
1962 			log_debug("complete %u: %s", i, list[i]);
1963 	}
1964 
1965 	if (out != NULL && strcmp(word, out) == 0) {
1966 		free(out);
1967 		out = NULL;
1968 	}
1969 	if (out != NULL ||
1970 	    !status_prompt_complete_list_menu(c, list, size, offset, flag)) {
1971 		for (i = 0; i < size; i++)
1972 			free(list[i]);
1973 		free(list);
1974 	}
1975 	return (out);
1976 }
1977 
1978 /* Return the type of the prompt as an enum. */
1979 enum prompt_type
1980 status_prompt_type(const char *type)
1981 {
1982 	u_int	i;
1983 
1984 	for (i = 0; i < PROMPT_NTYPES; i++) {
1985 		if (strcmp(type, status_prompt_type_string(i)) == 0)
1986 			return (i);
1987 	}
1988 	return (PROMPT_TYPE_INVALID);
1989 }
1990 
1991 /* Accessor for prompt_type_strings. */
1992 const char *
1993 status_prompt_type_string(u_int type)
1994 {
1995 	if (type >= PROMPT_NTYPES)
1996 		return ("invalid");
1997 	return (prompt_type_strings[type]);
1998 }
1999