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