status.c revision 1.174
1/* $OpenBSD: status.c,v 1.174 2018/01/01 11:03:54 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 char	*status_redraw_get_left(struct client *, time_t,
33		     struct grid_cell *, size_t *);
34static char	*status_redraw_get_right(struct client *, time_t,
35		     struct grid_cell *, size_t *);
36static char	*status_print(struct client *, struct winlink *, time_t,
37		     struct grid_cell *);
38static char	*status_replace(struct client *, struct winlink *, const char *,
39		     time_t);
40static void	 status_message_callback(int, short, void *);
41static void	 status_timer_callback(int, short, void *);
42
43static char	*status_prompt_find_history_file(void);
44static const char *status_prompt_up_history(u_int *);
45static const char *status_prompt_down_history(u_int *);
46static void	 status_prompt_add_history(const char *);
47
48static const char **status_prompt_complete_list(u_int *, const char *);
49static char	*status_prompt_complete_prefix(const char **, u_int);
50static char	*status_prompt_complete(struct session *, const char *);
51
52/* Status prompt history. */
53#define PROMPT_HISTORY 100
54static char	**status_prompt_hlist;
55static u_int	  status_prompt_hsize;
56
57/* Find the history file to load/save from/to. */
58static char *
59status_prompt_find_history_file(void)
60{
61	const char	*home, *history_file;
62	char		*path;
63
64	history_file = options_get_string(global_options, "history-file");
65	if (*history_file == '\0')
66		return (NULL);
67	if (*history_file == '/')
68		return (xstrdup(history_file));
69
70	if (history_file[0] != '~' || history_file[1] != '/')
71		return (NULL);
72	if ((home = find_home()) == NULL)
73		return (NULL);
74	xasprintf(&path, "%s%s", home, history_file + 1);
75	return (path);
76}
77
78/* Load status prompt history from file. */
79void
80status_prompt_load_history(void)
81{
82	FILE	*f;
83	char	*history_file, *line, *tmp;
84	size_t	 length;
85
86	if ((history_file = status_prompt_find_history_file()) == NULL)
87		return;
88	log_debug("loading history from %s", history_file);
89
90	f = fopen(history_file, "r");
91	if (f == NULL) {
92		log_debug("%s: %s", history_file, strerror(errno));
93		free(history_file);
94		return;
95	}
96	free(history_file);
97
98	for (;;) {
99		if ((line = fgetln(f, &length)) == NULL)
100			break;
101
102		if (length > 0) {
103			if (line[length - 1] == '\n') {
104				line[length - 1] = '\0';
105				status_prompt_add_history(line);
106			} else {
107				tmp = xmalloc(length + 1);
108				memcpy(tmp, line, length);
109				tmp[length] = '\0';
110				status_prompt_add_history(tmp);
111				free(tmp);
112			}
113		}
114	}
115	fclose(f);
116}
117
118/* Save status prompt history to file. */
119void
120status_prompt_save_history(void)
121{
122	FILE	*f;
123	u_int	 i;
124	char	*history_file;
125
126	if ((history_file = status_prompt_find_history_file()) == NULL)
127		return;
128	log_debug("saving history to %s", history_file);
129
130	f = fopen(history_file, "w");
131	if (f == NULL) {
132		log_debug("%s: %s", history_file, strerror(errno));
133		free(history_file);
134		return;
135	}
136	free(history_file);
137
138	for (i = 0; i < status_prompt_hsize; i++) {
139		fputs(status_prompt_hlist[i], f);
140		fputc('\n', f);
141	}
142	fclose(f);
143
144}
145
146/* Status timer callback. */
147static void
148status_timer_callback(__unused int fd, __unused short events, void *arg)
149{
150	struct client	*c = arg;
151	struct session	*s = c->session;
152	struct timeval	 tv;
153
154	evtimer_del(&c->status_timer);
155
156	if (s == NULL)
157		return;
158
159	if (c->message_string == NULL && c->prompt_string == NULL)
160		c->flags |= CLIENT_STATUS;
161
162	timerclear(&tv);
163	tv.tv_sec = options_get_number(s->options, "status-interval");
164
165	if (tv.tv_sec != 0)
166		evtimer_add(&c->status_timer, &tv);
167	log_debug("client %p, status interval %d", c, (int)tv.tv_sec);
168}
169
170/* Start status timer for client. */
171void
172status_timer_start(struct client *c)
173{
174	struct session	*s = c->session;
175
176	if (event_initialized(&c->status_timer))
177		evtimer_del(&c->status_timer);
178	else
179		evtimer_set(&c->status_timer, status_timer_callback, c);
180
181	if (s != NULL && options_get_number(s->options, "status"))
182		status_timer_callback(-1, 0, c);
183}
184
185/* Start status timer for all clients. */
186void
187status_timer_start_all(void)
188{
189	struct client	*c;
190
191	TAILQ_FOREACH(c, &clients, entry)
192		status_timer_start(c);
193}
194
195/* Update status cache. */
196void
197status_update_saved(struct session *s)
198{
199	if (!options_get_number(s->options, "status"))
200		s->statusat = -1;
201	else if (options_get_number(s->options, "status-position") == 0)
202		s->statusat = 0;
203	else
204		s->statusat = 1;
205}
206
207/* Get screen line of status line. -1 means off. */
208int
209status_at_line(struct client *c)
210{
211	struct session	*s = c->session;
212
213	if (c->flags & CLIENT_STATUSOFF)
214		return (-1);
215	if (s->statusat != 1)
216		return (s->statusat);
217	return (c->tty.sy - status_line_size(s));
218}
219
220/*
221 * Get size of status line for session. 0 means off. Note that status line may
222 * be forced off for an individual client if it is too small (the
223 * CLIENT_STATUSOFF flag is set for this).
224 */
225u_int
226status_line_size(struct session *s)
227{
228	if (s->statusat == -1)
229		return (0);
230	return (1);
231}
232
233/* Retrieve options for left string. */
234static char *
235status_redraw_get_left(struct client *c, time_t t, struct grid_cell *gc,
236    size_t *size)
237{
238	struct session	*s = c->session;
239	const char	*template;
240	char		*left;
241	size_t		 leftlen;
242
243	style_apply_update(gc, s->options, "status-left-style");
244
245	template = options_get_string(s->options, "status-left");
246	left = status_replace(c, NULL, template, t);
247
248	*size = options_get_number(s->options, "status-left-length");
249	leftlen = screen_write_cstrlen("%s", left);
250	if (leftlen < *size)
251		*size = leftlen;
252	return (left);
253}
254
255/* Retrieve options for right string. */
256static char *
257status_redraw_get_right(struct client *c, time_t t, struct grid_cell *gc,
258    size_t *size)
259{
260	struct session	*s = c->session;
261	const char	*template;
262	char		*right;
263	size_t		 rightlen;
264
265	style_apply_update(gc, s->options, "status-right-style");
266
267	template = options_get_string(s->options, "status-right");
268	right = status_replace(c, NULL, template, t);
269
270	*size = options_get_number(s->options, "status-right-length");
271	rightlen = screen_write_cstrlen("%s", right);
272	if (rightlen < *size)
273		*size = rightlen;
274	return (right);
275}
276
277/* Get window at window list position. */
278struct window *
279status_get_window_at(struct client *c, u_int x)
280{
281	struct session	*s = c->session;
282	struct winlink	*wl;
283	struct options	*oo;
284	const char	*sep;
285	size_t		 seplen;
286
287	x += c->wlmouse;
288	RB_FOREACH(wl, winlinks, &s->windows) {
289		oo = wl->window->options;
290
291		sep = options_get_string(oo, "window-status-separator");
292		seplen = screen_write_cstrlen("%s", sep);
293
294		if (x < wl->status_width)
295			return (wl->window);
296		x -= wl->status_width + seplen;
297	}
298	return (NULL);
299}
300
301/* Draw status for client on the last lines of given context. */
302int
303status_redraw(struct client *c)
304{
305	struct screen_write_ctx	 ctx;
306	struct session		*s = c->session;
307	struct winlink		*wl;
308	struct screen		 old_status, window_list;
309	struct grid_cell	 stdgc, lgc, rgc, gc;
310	struct options		*oo;
311	time_t			 t;
312	char			*left, *right;
313	const char		*sep;
314	u_int			 offset, needed, lines;
315	u_int			 wlstart, wlwidth, wlavailable, wloffset, wlsize;
316	size_t			 llen, rlen, seplen;
317	int			 larrow, rarrow;
318
319	/* Delete the saved status line, if any. */
320	if (c->old_status != NULL) {
321		screen_free(c->old_status);
322		free(c->old_status);
323		c->old_status = NULL;
324	}
325
326	/* No status line? */
327	lines = status_line_size(s);
328	if (c->tty.sy == 0 || lines == 0)
329		return (1);
330	left = right = NULL;
331	larrow = rarrow = 0;
332
333	/* Store current time. */
334	t = time(NULL);
335
336	/* Set up default colour. */
337	style_apply(&stdgc, s->options, "status-style");
338
339	/* Create the target screen. */
340	memcpy(&old_status, &c->status, sizeof old_status);
341	screen_init(&c->status, c->tty.sx, lines, 0);
342	screen_write_start(&ctx, NULL, &c->status);
343	for (offset = 0; offset < lines * c->tty.sx; offset++)
344		screen_write_putc(&ctx, &stdgc, ' ');
345	screen_write_stop(&ctx);
346
347	/* If the height is too small, blank status line. */
348	if (c->tty.sy < lines)
349		goto out;
350
351	/* Work out left and right strings. */
352	memcpy(&lgc, &stdgc, sizeof lgc);
353	left = status_redraw_get_left(c, t, &lgc, &llen);
354	memcpy(&rgc, &stdgc, sizeof rgc);
355	right = status_redraw_get_right(c, t, &rgc, &rlen);
356
357	/*
358	 * Figure out how much space we have for the window list. If there
359	 * isn't enough space, just show a blank status line.
360	 */
361	needed = 0;
362	if (llen != 0)
363		needed += llen;
364	if (rlen != 0)
365		needed += rlen;
366	if (c->tty.sx == 0 || c->tty.sx <= needed)
367		goto out;
368	wlavailable = c->tty.sx - needed;
369
370	/* Calculate the total size needed for the window list. */
371	wlstart = wloffset = wlwidth = 0;
372	RB_FOREACH(wl, winlinks, &s->windows) {
373		free(wl->status_text);
374		memcpy(&wl->status_cell, &stdgc, sizeof wl->status_cell);
375		wl->status_text = status_print(c, wl, t, &wl->status_cell);
376		wl->status_width = screen_write_cstrlen("%s", wl->status_text);
377
378		if (wl == s->curw)
379			wloffset = wlwidth;
380
381		oo = wl->window->options;
382		sep = options_get_string(oo, "window-status-separator");
383		seplen = screen_write_cstrlen("%s", sep);
384		wlwidth += wl->status_width + seplen;
385	}
386
387	/* Create a new screen for the window list. */
388	screen_init(&window_list, wlwidth, 1, 0);
389
390	/* And draw the window list into it. */
391	screen_write_start(&ctx, NULL, &window_list);
392	RB_FOREACH(wl, winlinks, &s->windows) {
393		screen_write_cnputs(&ctx, -1, &wl->status_cell, "%s",
394		    wl->status_text);
395
396		oo = wl->window->options;
397		sep = options_get_string(oo, "window-status-separator");
398		screen_write_cnputs(&ctx, -1, &stdgc, "%s", sep);
399	}
400	screen_write_stop(&ctx);
401
402	/* If there is enough space for the total width, skip to draw now. */
403	if (wlwidth <= wlavailable)
404		goto draw;
405
406	/* Find size of current window text. */
407	wlsize = s->curw->status_width;
408
409	/*
410	 * If the current window is already on screen, good to draw from the
411	 * start and just leave off the end.
412	 */
413	if (wloffset + wlsize < wlavailable) {
414		if (wlavailable > 0) {
415			rarrow = 1;
416			wlavailable--;
417		}
418		wlwidth = wlavailable;
419	} else {
420		/*
421		 * Work out how many characters we need to omit from the
422		 * start. There are wlavailable characters to fill, and
423		 * wloffset + wlsize must be the last. So, the start character
424		 * is wloffset + wlsize - wlavailable.
425		 */
426		if (wlavailable > 0) {
427			larrow = 1;
428			wlavailable--;
429		}
430
431		wlstart = wloffset + wlsize - wlavailable;
432		if (wlavailable > 0 && wlwidth > wlstart + wlavailable + 1) {
433			rarrow = 1;
434			wlstart++;
435			wlavailable--;
436		}
437		wlwidth = wlavailable;
438	}
439
440	/* Bail if anything is now too small too. */
441	if (wlwidth == 0 || wlavailable == 0) {
442		screen_free(&window_list);
443		goto out;
444	}
445
446	/*
447	 * Now the start position is known, work out the state of the left and
448	 * right arrows.
449	 */
450	offset = 0;
451	RB_FOREACH(wl, winlinks, &s->windows) {
452		if (wl->flags & WINLINK_ALERTFLAGS &&
453		    larrow == 1 && offset < wlstart)
454			larrow = -1;
455
456		offset += wl->status_width;
457
458		if (wl->flags & WINLINK_ALERTFLAGS &&
459		    rarrow == 1 && offset > wlstart + wlwidth)
460			rarrow = -1;
461	}
462
463draw:
464	/* Begin drawing. */
465	screen_write_start(&ctx, NULL, &c->status);
466
467	/* Draw the left string and arrow. */
468	screen_write_cursormove(&ctx, 0, 0);
469	if (llen != 0)
470		screen_write_cnputs(&ctx, llen, &lgc, "%s", left);
471	if (larrow != 0) {
472		memcpy(&gc, &stdgc, sizeof gc);
473		if (larrow == -1)
474			gc.attr ^= GRID_ATTR_REVERSE;
475		screen_write_putc(&ctx, &gc, '<');
476	}
477
478	/* Draw the right string and arrow. */
479	if (rarrow != 0) {
480		screen_write_cursormove(&ctx, c->tty.sx - rlen - 1, 0);
481		memcpy(&gc, &stdgc, sizeof gc);
482		if (rarrow == -1)
483			gc.attr ^= GRID_ATTR_REVERSE;
484		screen_write_putc(&ctx, &gc, '>');
485	} else
486		screen_write_cursormove(&ctx, c->tty.sx - rlen, 0);
487	if (rlen != 0)
488		screen_write_cnputs(&ctx, rlen, &rgc, "%s", right);
489
490	/* Figure out the offset for the window list. */
491	if (llen != 0)
492		wloffset = llen;
493	else
494		wloffset = 0;
495	if (wlwidth < wlavailable) {
496		switch (options_get_number(s->options, "status-justify")) {
497		case 1:	/* centred */
498			wloffset += (wlavailable - wlwidth) / 2;
499			break;
500		case 2:	/* right */
501			wloffset += (wlavailable - wlwidth);
502			break;
503		}
504	}
505	if (larrow != 0)
506		wloffset++;
507
508	/* Copy the window list. */
509	c->wlmouse = -wloffset + wlstart;
510	screen_write_cursormove(&ctx, wloffset, 0);
511	screen_write_fast_copy(&ctx, &window_list, wlstart, 0, wlwidth, 1);
512	screen_free(&window_list);
513
514	screen_write_stop(&ctx);
515
516out:
517	free(left);
518	free(right);
519
520	if (grid_compare(c->status.grid, old_status.grid) == 0) {
521		screen_free(&old_status);
522		return (0);
523	}
524	screen_free(&old_status);
525	return (1);
526}
527
528/* Replace special sequences in fmt. */
529static char *
530status_replace(struct client *c, struct winlink *wl, const char *fmt, time_t t)
531{
532	struct format_tree	*ft;
533	char			*expanded;
534	u_int			 tag;
535
536	if (fmt == NULL)
537		return (xstrdup(""));
538
539	if (wl != NULL)
540		tag = FORMAT_WINDOW|wl->window->id;
541	else
542		tag = FORMAT_NONE;
543	if (c->flags & CLIENT_STATUSFORCE)
544		ft = format_create(c, NULL, tag, FORMAT_STATUS|FORMAT_FORCE);
545	else
546		ft = format_create(c, NULL, tag, FORMAT_STATUS);
547	format_defaults(ft, c, NULL, wl, NULL);
548
549	expanded = format_expand_time(ft, fmt, t);
550
551	format_free(ft);
552	return (expanded);
553}
554
555/* Return winlink status line entry and adjust gc as necessary. */
556static char *
557status_print(struct client *c, struct winlink *wl, time_t t,
558    struct grid_cell *gc)
559{
560	struct options	*oo = wl->window->options;
561	struct session	*s = c->session;
562	const char	*fmt;
563	char   		*text;
564
565	style_apply_update(gc, oo, "window-status-style");
566	fmt = options_get_string(oo, "window-status-format");
567	if (wl == s->curw) {
568		style_apply_update(gc, oo, "window-status-current-style");
569		fmt = options_get_string(oo, "window-status-current-format");
570	}
571	if (wl == TAILQ_FIRST(&s->lastw))
572		style_apply_update(gc, oo, "window-status-last-style");
573
574	if (wl->flags & WINLINK_BELL)
575		style_apply_update(gc, oo, "window-status-bell-style");
576	else if (wl->flags & (WINLINK_ACTIVITY|WINLINK_SILENCE))
577		style_apply_update(gc, oo, "window-status-activity-style");
578
579	text = status_replace(c, wl, fmt, t);
580	return (text);
581}
582
583/* Set a status line message. */
584void
585status_message_set(struct client *c, const char *fmt, ...)
586{
587	struct timeval	tv;
588	va_list		ap;
589	int		delay;
590
591	status_message_clear(c);
592
593	if (c->old_status == NULL) {
594		c->old_status = xmalloc(sizeof *c->old_status);
595		memcpy(c->old_status, &c->status, sizeof *c->old_status);
596		screen_init(&c->status, c->tty.sx, 1, 0);
597	}
598
599	va_start(ap, fmt);
600	xvasprintf(&c->message_string, fmt, ap);
601	va_end(ap);
602
603	server_client_add_message(c, "%s", c->message_string);
604
605	delay = options_get_number(c->session->options, "display-time");
606	if (delay > 0) {
607		tv.tv_sec = delay / 1000;
608		tv.tv_usec = (delay % 1000) * 1000L;
609
610		if (event_initialized(&c->message_timer))
611			evtimer_del(&c->message_timer);
612		evtimer_set(&c->message_timer, status_message_callback, c);
613		evtimer_add(&c->message_timer, &tv);
614	}
615
616	c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
617	c->flags |= CLIENT_STATUS;
618}
619
620/* Clear status line message. */
621void
622status_message_clear(struct client *c)
623{
624	if (c->message_string == NULL)
625		return;
626
627	free(c->message_string);
628	c->message_string = NULL;
629
630	if (c->prompt_string == NULL)
631		c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
632	c->flags |= CLIENT_REDRAW; /* screen was frozen and may have changed */
633
634	screen_reinit(&c->status);
635}
636
637/* Clear status line message after timer expires. */
638static void
639status_message_callback(__unused int fd, __unused short event, void *data)
640{
641	struct client	*c = data;
642
643	status_message_clear(c);
644}
645
646/* Draw client message on status line of present else on last line. */
647int
648status_message_redraw(struct client *c)
649{
650	struct screen_write_ctx		ctx;
651	struct session		       *s = c->session;
652	struct screen		        old_status;
653	size_t			        len;
654	struct grid_cell		gc;
655	u_int				lines, offset;
656
657	if (c->tty.sx == 0 || c->tty.sy == 0)
658		return (0);
659	memcpy(&old_status, &c->status, sizeof old_status);
660
661	lines = status_line_size(c->session);
662	if (lines <= 1) {
663		lines = 1;
664		screen_init(&c->status, c->tty.sx, 1, 0);
665	} else
666		screen_init(&c->status, c->tty.sx, lines, 0);
667
668	len = screen_write_strlen("%s", c->message_string);
669	if (len > c->tty.sx)
670		len = c->tty.sx;
671
672	style_apply(&gc, s->options, "message-style");
673
674	screen_write_start(&ctx, NULL, &c->status);
675	screen_write_cursormove(&ctx, 0, 0);
676	for (offset = 0; offset < lines * c->tty.sx; offset++)
677		screen_write_putc(&ctx, &gc, ' ');
678	screen_write_cursormove(&ctx, 0, lines - 1);
679	screen_write_nputs(&ctx, len, &gc, "%s", c->message_string);
680	screen_write_stop(&ctx);
681
682	if (grid_compare(c->status.grid, old_status.grid) == 0) {
683		screen_free(&old_status);
684		return (0);
685	}
686	screen_free(&old_status);
687	return (1);
688}
689
690/* Enable status line prompt. */
691void
692status_prompt_set(struct client *c, const char *msg, const char *input,
693    prompt_input_cb inputcb, prompt_free_cb freecb, void *data, int flags)
694{
695	struct format_tree	*ft;
696	time_t			 t;
697	char			*tmp, *cp;
698
699	ft = format_create(c, NULL, FORMAT_NONE, 0);
700	format_defaults(ft, c, NULL, NULL, NULL);
701	t = time(NULL);
702
703	if (input == NULL)
704		input = "";
705	if (flags & PROMPT_NOFORMAT)
706		tmp = xstrdup(input);
707	else
708		tmp = format_expand_time(ft, input, t);
709
710	status_message_clear(c);
711	status_prompt_clear(c);
712
713	if (c->old_status == NULL) {
714		c->old_status = xmalloc(sizeof *c->old_status);
715		memcpy(c->old_status, &c->status, sizeof *c->old_status);
716		screen_init(&c->status, c->tty.sx, 1, 0);
717	}
718
719	c->prompt_string = format_expand_time(ft, msg, t);
720
721	c->prompt_buffer = utf8_fromcstr(tmp);
722	c->prompt_index = utf8_strlen(c->prompt_buffer);
723
724	c->prompt_inputcb = inputcb;
725	c->prompt_freecb = freecb;
726	c->prompt_data = data;
727
728	c->prompt_hindex = 0;
729
730	c->prompt_flags = flags;
731	c->prompt_mode = PROMPT_ENTRY;
732
733	if (~flags & PROMPT_INCREMENTAL)
734		c->tty.flags |= (TTY_NOCURSOR|TTY_FREEZE);
735	c->flags |= CLIENT_STATUS;
736
737	if ((flags & PROMPT_INCREMENTAL) && *tmp != '\0') {
738		xasprintf(&cp, "=%s", tmp);
739		c->prompt_inputcb(c, c->prompt_data, cp, 0);
740		free(cp);
741	}
742
743	free(tmp);
744	format_free(ft);
745}
746
747/* Remove status line prompt. */
748void
749status_prompt_clear(struct client *c)
750{
751	if (c->prompt_string == NULL)
752		return;
753
754	if (c->prompt_freecb != NULL && c->prompt_data != NULL)
755		c->prompt_freecb(c->prompt_data);
756
757	free(c->prompt_string);
758	c->prompt_string = NULL;
759
760	free(c->prompt_buffer);
761	c->prompt_buffer = NULL;
762
763	c->tty.flags &= ~(TTY_NOCURSOR|TTY_FREEZE);
764	c->flags |= CLIENT_REDRAW; /* screen was frozen and may have changed */
765
766	screen_reinit(&c->status);
767}
768
769/* Update status line prompt with a new prompt string. */
770void
771status_prompt_update(struct client *c, const char *msg, const char *input)
772{
773	struct format_tree	*ft;
774	time_t			 t;
775	char			*tmp;
776
777	ft = format_create(c, NULL, FORMAT_NONE, 0);
778	format_defaults(ft, c, NULL, NULL, NULL);
779
780	t = time(NULL);
781	tmp = format_expand_time(ft, input, t);
782
783	free(c->prompt_string);
784	c->prompt_string = format_expand_time(ft, msg, t);
785
786	free(c->prompt_buffer);
787	c->prompt_buffer = utf8_fromcstr(tmp);
788	c->prompt_index = utf8_strlen(c->prompt_buffer);
789
790	c->prompt_hindex = 0;
791
792	c->flags |= CLIENT_STATUS;
793
794	free(tmp);
795	format_free(ft);
796}
797
798/* Draw client prompt on status line of present else on last line. */
799int
800status_prompt_redraw(struct client *c)
801{
802	struct screen_write_ctx	 ctx;
803	struct session		*s = c->session;
804	struct screen		 old_status;
805	u_int			 i, offset, left, start, pcursor, pwidth, width;
806	u_int			 lines;
807	size_t			 len;
808	struct grid_cell	 gc, cursorgc;
809
810	if (c->tty.sx == 0 || c->tty.sy == 0)
811		return (0);
812	memcpy(&old_status, &c->status, sizeof old_status);
813
814	lines = status_line_size(c->session);
815	if (lines <= 1) {
816		lines = 1;
817		screen_init(&c->status, c->tty.sx, 1, 0);
818	} else
819		screen_init(&c->status, c->tty.sx, lines, 0);
820
821	len = screen_write_strlen("%s", c->prompt_string);
822	if (len > c->tty.sx)
823		len = c->tty.sx;
824
825	if (c->prompt_mode == PROMPT_COMMAND)
826		style_apply(&gc, s->options, "message-command-style");
827	else
828		style_apply(&gc, s->options, "message-style");
829
830	memcpy(&cursorgc, &gc, sizeof cursorgc);
831	cursorgc.attr ^= GRID_ATTR_REVERSE;
832
833	start = screen_write_strlen("%s", c->prompt_string);
834	if (start > c->tty.sx)
835		start = c->tty.sx;
836
837	screen_write_start(&ctx, NULL, &c->status);
838	screen_write_cursormove(&ctx, 0, 0);
839	for (offset = 0; offset < lines * c->tty.sx; offset++)
840		screen_write_putc(&ctx, &gc, ' ');
841	screen_write_cursormove(&ctx, 0, 0);
842	screen_write_nputs(&ctx, start, &gc, "%s", c->prompt_string);
843	screen_write_cursormove(&ctx, start, 0);
844
845	left = c->tty.sx - start;
846	if (left == 0)
847		goto finished;
848
849	pcursor = utf8_strwidth(c->prompt_buffer, c->prompt_index);
850	pwidth = utf8_strwidth(c->prompt_buffer, -1);
851	if (pcursor >= left) {
852		/*
853		 * The cursor would be outside the screen so start drawing
854		 * with it on the right.
855		 */
856		offset = (pcursor - left) + 1;
857		pwidth = left;
858	} else
859		offset = 0;
860	if (pwidth > left)
861		pwidth = left;
862
863	width = 0;
864	for (i = 0; c->prompt_buffer[i].size != 0; i++) {
865		if (width < offset) {
866			width += c->prompt_buffer[i].width;
867			continue;
868		}
869		if (width >= offset + pwidth)
870			break;
871		width += c->prompt_buffer[i].width;
872		if (width > offset + pwidth)
873			break;
874
875		if (i != c->prompt_index) {
876			utf8_copy(&gc.data, &c->prompt_buffer[i]);
877			screen_write_cell(&ctx, &gc);
878		} else {
879			utf8_copy(&cursorgc.data, &c->prompt_buffer[i]);
880			screen_write_cell(&ctx, &cursorgc);
881		}
882	}
883	if (c->status.cx < screen_size_x(&c->status) && c->prompt_index >= i)
884		screen_write_putc(&ctx, &cursorgc, ' ');
885
886finished:
887	screen_write_stop(&ctx);
888
889	if (grid_compare(c->status.grid, old_status.grid) == 0) {
890		screen_free(&old_status);
891		return (0);
892	}
893	screen_free(&old_status);
894	return (1);
895}
896
897/* Is this a separator? */
898static int
899status_prompt_in_list(const char *ws, const struct utf8_data *ud)
900{
901	if (ud->size != 1 || ud->width != 1)
902		return (0);
903	return (strchr(ws, *ud->data) != NULL);
904}
905
906/* Is this a space? */
907static int
908status_prompt_space(const struct utf8_data *ud)
909{
910	if (ud->size != 1 || ud->width != 1)
911		return (0);
912	return (*ud->data == ' ');
913}
914
915/*
916 * Translate key from emacs to vi. Return 0 to drop key, 1 to process the key
917 * as an emacs key; return 2 to append to the buffer.
918 */
919static int
920status_prompt_translate_key(struct client *c, key_code key, key_code *new_key)
921{
922	if (c->prompt_mode == PROMPT_ENTRY) {
923		switch (key) {
924		case '\003': /* C-c */
925		case '\010': /* C-h */
926		case '\011': /* Tab */
927		case '\025': /* C-u */
928		case '\027': /* C-w */
929		case '\n':
930		case '\r':
931		case KEYC_BSPACE:
932		case KEYC_DC:
933		case KEYC_DOWN:
934		case KEYC_END:
935		case KEYC_HOME:
936		case KEYC_LEFT:
937		case KEYC_RIGHT:
938		case KEYC_UP:
939			*new_key = key;
940			return (1);
941		case '\033': /* Escape */
942			c->prompt_mode = PROMPT_COMMAND;
943			c->flags |= CLIENT_STATUS;
944			return (0);
945		}
946		*new_key = key;
947		return (2);
948	}
949
950	switch (key) {
951	case 'A':
952	case 'I':
953	case 'C':
954	case 's':
955	case 'a':
956		c->prompt_mode = PROMPT_ENTRY;
957		c->flags |= CLIENT_STATUS;
958		break; /* switch mode and... */
959	case 'S':
960		c->prompt_mode = PROMPT_ENTRY;
961		c->flags |= CLIENT_STATUS;
962		*new_key = '\025'; /* C-u */
963		return (1);
964	case 'i':
965	case '\033': /* Escape */
966		c->prompt_mode = PROMPT_ENTRY;
967		c->flags |= CLIENT_STATUS;
968		return (0);
969	}
970
971	switch (key) {
972	case 'A':
973	case '$':
974		*new_key = KEYC_END;
975		return (1);
976	case 'I':
977	case '0':
978	case '^':
979		*new_key = KEYC_HOME;
980		return (1);
981	case 'C':
982	case 'D':
983		*new_key = '\013'; /* C-k */
984		return (1);
985	case KEYC_BSPACE:
986	case 'X':
987		*new_key = KEYC_BSPACE;
988		return (1);
989	case 'b':
990	case 'B':
991		*new_key = 'b'|KEYC_ESCAPE;
992		return (1);
993	case 'd':
994		*new_key = '\025';
995		return (1);
996	case 'e':
997	case 'E':
998	case 'w':
999	case 'W':
1000		*new_key = 'f'|KEYC_ESCAPE;
1001		return (1);
1002	case 'p':
1003		*new_key = '\031'; /* C-y */
1004		return (1);
1005	case 's':
1006	case KEYC_DC:
1007	case 'x':
1008		*new_key = KEYC_DC;
1009		return (1);
1010	case KEYC_DOWN:
1011	case 'j':
1012		*new_key = KEYC_DOWN;
1013		return (1);
1014	case KEYC_LEFT:
1015	case 'h':
1016		*new_key = KEYC_LEFT;
1017		return (1);
1018	case 'a':
1019	case KEYC_RIGHT:
1020	case 'l':
1021		*new_key = KEYC_RIGHT;
1022		return (1);
1023	case KEYC_UP:
1024	case 'k':
1025		*new_key = KEYC_UP;
1026		return (1);
1027	case '\010' /* C-h */:
1028	case '\003' /* C-c */:
1029	case '\n':
1030	case '\r':
1031		return (1);
1032	}
1033	return (0);
1034}
1035
1036/* Handle keys in prompt. */
1037int
1038status_prompt_key(struct client *c, key_code key)
1039{
1040	struct options		*oo = c->session->options;
1041	struct paste_buffer	*pb;
1042	char			*s, *cp, word[64], prefix = '=';
1043	const char		*histstr, *bufdata, *ws = NULL;
1044	u_char			 ch;
1045	size_t			 size, n, off, idx, bufsize, used;
1046	struct utf8_data	 tmp, *first, *last, *ud;
1047	int			 keys;
1048
1049	size = utf8_strlen(c->prompt_buffer);
1050
1051	if (c->prompt_flags & PROMPT_NUMERIC) {
1052		if (key >= '0' && key <= '9')
1053			goto append_key;
1054		s = utf8_tocstr(c->prompt_buffer);
1055		c->prompt_inputcb(c, c->prompt_data, s, 1);
1056		status_prompt_clear(c);
1057		free(s);
1058		return (1);
1059	}
1060
1061	keys = options_get_number(c->session->options, "status-keys");
1062	if (keys == MODEKEY_VI) {
1063		switch (status_prompt_translate_key(c, key, &key)) {
1064		case 1:
1065			goto process_key;
1066		case 2:
1067			goto append_key;
1068		default:
1069			return (0);
1070		}
1071	}
1072
1073process_key:
1074	switch (key) {
1075	case KEYC_LEFT:
1076	case '\002': /* C-b */
1077		if (c->prompt_index > 0) {
1078			c->prompt_index--;
1079			break;
1080		}
1081		break;
1082	case KEYC_RIGHT:
1083	case '\006': /* C-f */
1084		if (c->prompt_index < size) {
1085			c->prompt_index++;
1086			break;
1087		}
1088		break;
1089	case KEYC_HOME:
1090	case '\001': /* C-a */
1091		if (c->prompt_index != 0) {
1092			c->prompt_index = 0;
1093			break;
1094		}
1095		break;
1096	case KEYC_END:
1097	case '\005': /* C-e */
1098		if (c->prompt_index != size) {
1099			c->prompt_index = size;
1100			break;
1101		}
1102		break;
1103	case '\011': /* Tab */
1104		if (c->prompt_buffer[0].size == 0)
1105			break;
1106
1107		idx = c->prompt_index;
1108		if (idx != 0)
1109			idx--;
1110
1111		/* Find the word we are in. */
1112		first = &c->prompt_buffer[idx];
1113		while (first > c->prompt_buffer && !status_prompt_space(first))
1114			first--;
1115		while (first->size != 0 && status_prompt_space(first))
1116			first++;
1117		last = &c->prompt_buffer[idx];
1118		while (last->size != 0 && !status_prompt_space(last))
1119			last++;
1120		while (last > c->prompt_buffer && status_prompt_space(last))
1121			last--;
1122		if (last->size != 0)
1123			last++;
1124		if (last <= first)
1125			break;
1126
1127		used = 0;
1128		for (ud = first; ud < last; ud++) {
1129			if (used + ud->size >= sizeof word)
1130				break;
1131			memcpy(word + used, ud->data, ud->size);
1132			used += ud->size;
1133		}
1134		if (ud != last)
1135			break;
1136		word[used] = '\0';
1137
1138		/* And try to complete it. */
1139		if ((s = status_prompt_complete(c->session, word)) == NULL)
1140			break;
1141
1142		/* Trim out word. */
1143		n = size - (last - c->prompt_buffer) + 1; /* with \0 */
1144		memmove(first, last, n * sizeof *c->prompt_buffer);
1145		size -= last - first;
1146
1147		/* Insert the new word. */
1148		size += strlen(s);
1149		off = first - c->prompt_buffer;
1150		c->prompt_buffer = xreallocarray(c->prompt_buffer, size + 1,
1151		    sizeof *c->prompt_buffer);
1152		first = c->prompt_buffer + off;
1153		memmove(first + strlen(s), first, n * sizeof *c->prompt_buffer);
1154		for (idx = 0; idx < strlen(s); idx++)
1155			utf8_set(&first[idx], s[idx]);
1156
1157		c->prompt_index = (first - c->prompt_buffer) + strlen(s);
1158		free(s);
1159
1160		goto changed;
1161	case KEYC_BSPACE:
1162	case '\010': /* C-h */
1163		if (c->prompt_index != 0) {
1164			if (c->prompt_index == size)
1165				c->prompt_buffer[--c->prompt_index].size = 0;
1166			else {
1167				memmove(c->prompt_buffer + c->prompt_index - 1,
1168				    c->prompt_buffer + c->prompt_index,
1169				    (size + 1 - c->prompt_index) *
1170				    sizeof *c->prompt_buffer);
1171				c->prompt_index--;
1172			}
1173			goto changed;
1174		}
1175		break;
1176	case KEYC_DC:
1177	case '\004': /* C-d */
1178		if (c->prompt_index != size) {
1179			memmove(c->prompt_buffer + c->prompt_index,
1180			    c->prompt_buffer + c->prompt_index + 1,
1181			    (size + 1 - c->prompt_index) *
1182			    sizeof *c->prompt_buffer);
1183			goto changed;
1184		}
1185		break;
1186	case '\025': /* C-u */
1187		c->prompt_buffer[0].size = 0;
1188		c->prompt_index = 0;
1189		goto changed;
1190	case '\013': /* C-k */
1191		if (c->prompt_index < size) {
1192			c->prompt_buffer[c->prompt_index].size = 0;
1193			goto changed;
1194		}
1195		break;
1196	case '\027': /* C-w */
1197		ws = options_get_string(oo, "word-separators");
1198		idx = c->prompt_index;
1199
1200		/* Find a non-separator. */
1201		while (idx != 0) {
1202			idx--;
1203			if (!status_prompt_in_list(ws, &c->prompt_buffer[idx]))
1204				break;
1205		}
1206
1207		/* Find the separator at the beginning of the word. */
1208		while (idx != 0) {
1209			idx--;
1210			if (status_prompt_in_list(ws, &c->prompt_buffer[idx])) {
1211				/* Go back to the word. */
1212				idx++;
1213				break;
1214			}
1215		}
1216
1217		memmove(c->prompt_buffer + idx,
1218		    c->prompt_buffer + c->prompt_index,
1219		    (size + 1 - c->prompt_index) *
1220		    sizeof *c->prompt_buffer);
1221		memset(c->prompt_buffer + size - (c->prompt_index - idx),
1222		    '\0', (c->prompt_index - idx) * sizeof *c->prompt_buffer);
1223		c->prompt_index = idx;
1224
1225		goto changed;
1226	case 'f'|KEYC_ESCAPE:
1227		ws = options_get_string(oo, "word-separators");
1228
1229		/* Find a word. */
1230		while (c->prompt_index != size) {
1231			idx = ++c->prompt_index;
1232			if (!status_prompt_in_list(ws, &c->prompt_buffer[idx]))
1233				break;
1234		}
1235
1236		/* Find the separator at the end of the word. */
1237		while (c->prompt_index != size) {
1238			idx = ++c->prompt_index;
1239			if (status_prompt_in_list(ws, &c->prompt_buffer[idx]))
1240				break;
1241		}
1242
1243		/* Back up to the end-of-word like vi. */
1244		if (options_get_number(oo, "status-keys") == MODEKEY_VI &&
1245		    c->prompt_index != 0)
1246			c->prompt_index--;
1247
1248		goto changed;
1249	case 'b'|KEYC_ESCAPE:
1250		ws = options_get_string(oo, "word-separators");
1251
1252		/* Find a non-separator. */
1253		while (c->prompt_index != 0) {
1254			idx = --c->prompt_index;
1255			if (!status_prompt_in_list(ws, &c->prompt_buffer[idx]))
1256				break;
1257		}
1258
1259		/* Find the separator at the beginning of the word. */
1260		while (c->prompt_index != 0) {
1261			idx = --c->prompt_index;
1262			if (status_prompt_in_list(ws, &c->prompt_buffer[idx])) {
1263				/* Go back to the word. */
1264				c->prompt_index++;
1265				break;
1266			}
1267		}
1268		goto changed;
1269	case KEYC_UP:
1270	case '\020': /* C-p */
1271		histstr = status_prompt_up_history(&c->prompt_hindex);
1272		if (histstr == NULL)
1273			break;
1274		free(c->prompt_buffer);
1275		c->prompt_buffer = utf8_fromcstr(histstr);
1276		c->prompt_index = utf8_strlen(c->prompt_buffer);
1277		goto changed;
1278	case KEYC_DOWN:
1279	case '\016': /* C-n */
1280		histstr = status_prompt_down_history(&c->prompt_hindex);
1281		if (histstr == NULL)
1282			break;
1283		free(c->prompt_buffer);
1284		c->prompt_buffer = utf8_fromcstr(histstr);
1285		c->prompt_index = utf8_strlen(c->prompt_buffer);
1286		goto changed;
1287	case '\031': /* C-y */
1288		if ((pb = paste_get_top(NULL)) == NULL)
1289			break;
1290		bufdata = paste_buffer_data(pb, &bufsize);
1291		for (n = 0; n < bufsize; n++) {
1292			ch = (u_char)bufdata[n];
1293			if (ch < 32 || ch >= 127)
1294				break;
1295		}
1296
1297		c->prompt_buffer = xreallocarray(c->prompt_buffer, size + n + 1,
1298		    sizeof *c->prompt_buffer);
1299		if (c->prompt_index == size) {
1300			for (idx = 0; idx < n; idx++) {
1301				ud = &c->prompt_buffer[c->prompt_index + idx];
1302				utf8_set(ud, bufdata[idx]);
1303			}
1304			c->prompt_index += n;
1305			c->prompt_buffer[c->prompt_index].size = 0;
1306		} else {
1307			memmove(c->prompt_buffer + c->prompt_index + n,
1308			    c->prompt_buffer + c->prompt_index,
1309			    (size + 1 - c->prompt_index) *
1310			    sizeof *c->prompt_buffer);
1311			for (idx = 0; idx < n; idx++) {
1312				ud = &c->prompt_buffer[c->prompt_index + idx];
1313				utf8_set(ud, bufdata[idx]);
1314			}
1315			c->prompt_index += n;
1316		}
1317		goto changed;
1318	case '\024': /* C-t */
1319		idx = c->prompt_index;
1320		if (idx < size)
1321			idx++;
1322		if (idx >= 2) {
1323			utf8_copy(&tmp, &c->prompt_buffer[idx - 2]);
1324			utf8_copy(&c->prompt_buffer[idx - 2],
1325			    &c->prompt_buffer[idx - 1]);
1326			utf8_copy(&c->prompt_buffer[idx - 1], &tmp);
1327			c->prompt_index = idx;
1328			goto changed;
1329		}
1330		break;
1331	case '\r':
1332	case '\n':
1333		s = utf8_tocstr(c->prompt_buffer);
1334		if (*s != '\0')
1335			status_prompt_add_history(s);
1336		if (c->prompt_inputcb(c, c->prompt_data, s, 1) == 0)
1337			status_prompt_clear(c);
1338		free(s);
1339		break;
1340	case '\033': /* Escape */
1341	case '\003': /* C-c */
1342	case '\007': /* C-g */
1343		if (c->prompt_inputcb(c, c->prompt_data, NULL, 1) == 0)
1344			status_prompt_clear(c);
1345		break;
1346	case '\022': /* C-r */
1347		if (c->prompt_flags & PROMPT_INCREMENTAL) {
1348			prefix = '-';
1349			goto changed;
1350		}
1351		break;
1352	case '\023': /* C-s */
1353		if (c->prompt_flags & PROMPT_INCREMENTAL) {
1354			prefix = '+';
1355			goto changed;
1356		}
1357		break;
1358	default:
1359		goto append_key;
1360	}
1361
1362	c->flags |= CLIENT_STATUS;
1363	return (0);
1364
1365append_key:
1366	if (key <= 0x1f || key >= KEYC_BASE)
1367		return (0);
1368	if (utf8_split(key, &tmp) != UTF8_DONE)
1369		return (0);
1370
1371	c->prompt_buffer = xreallocarray(c->prompt_buffer, size + 2,
1372	    sizeof *c->prompt_buffer);
1373
1374	if (c->prompt_index == size) {
1375		utf8_copy(&c->prompt_buffer[c->prompt_index], &tmp);
1376		c->prompt_index++;
1377		c->prompt_buffer[c->prompt_index].size = 0;
1378	} else {
1379		memmove(c->prompt_buffer + c->prompt_index + 1,
1380		    c->prompt_buffer + c->prompt_index,
1381		    (size + 1 - c->prompt_index) *
1382		    sizeof *c->prompt_buffer);
1383		utf8_copy(&c->prompt_buffer[c->prompt_index], &tmp);
1384		c->prompt_index++;
1385	}
1386
1387	if (c->prompt_flags & PROMPT_SINGLE) {
1388		s = utf8_tocstr(c->prompt_buffer);
1389		if (strlen(s) != 1)
1390			status_prompt_clear(c);
1391		else if (c->prompt_inputcb(c, c->prompt_data, s, 1) == 0)
1392			status_prompt_clear(c);
1393		free(s);
1394	}
1395
1396changed:
1397	c->flags |= CLIENT_STATUS;
1398	if (c->prompt_flags & PROMPT_INCREMENTAL) {
1399		s = utf8_tocstr(c->prompt_buffer);
1400		xasprintf(&cp, "%c%s", prefix, s);
1401		c->prompt_inputcb(c, c->prompt_data, cp, 0);
1402		free(cp);
1403		free(s);
1404	}
1405	return (0);
1406}
1407
1408/* Get previous line from the history. */
1409static const char *
1410status_prompt_up_history(u_int *idx)
1411{
1412	/*
1413	 * History runs from 0 to size - 1. Index is from 0 to size. Zero is
1414	 * empty.
1415	 */
1416
1417	if (status_prompt_hsize == 0 || *idx == status_prompt_hsize)
1418		return (NULL);
1419	(*idx)++;
1420	return (status_prompt_hlist[status_prompt_hsize - *idx]);
1421}
1422
1423/* Get next line from the history. */
1424static const char *
1425status_prompt_down_history(u_int *idx)
1426{
1427	if (status_prompt_hsize == 0 || *idx == 0)
1428		return ("");
1429	(*idx)--;
1430	if (*idx == 0)
1431		return ("");
1432	return (status_prompt_hlist[status_prompt_hsize - *idx]);
1433}
1434
1435/* Add line to the history. */
1436static void
1437status_prompt_add_history(const char *line)
1438{
1439	size_t	size;
1440
1441	if (status_prompt_hsize > 0 &&
1442	    strcmp(status_prompt_hlist[status_prompt_hsize - 1], line) == 0)
1443		return;
1444
1445	if (status_prompt_hsize == PROMPT_HISTORY) {
1446		free(status_prompt_hlist[0]);
1447
1448		size = (PROMPT_HISTORY - 1) * sizeof *status_prompt_hlist;
1449		memmove(&status_prompt_hlist[0], &status_prompt_hlist[1], size);
1450
1451		status_prompt_hlist[status_prompt_hsize - 1] = xstrdup(line);
1452		return;
1453	}
1454
1455	status_prompt_hlist = xreallocarray(status_prompt_hlist,
1456	    status_prompt_hsize + 1, sizeof *status_prompt_hlist);
1457	status_prompt_hlist[status_prompt_hsize++] = xstrdup(line);
1458}
1459
1460/* Build completion list. */
1461static const char **
1462status_prompt_complete_list(u_int *size, const char *s)
1463{
1464	const char				**list = NULL, **layout;
1465	const struct cmd_entry			**cmdent;
1466	const struct options_table_entry	 *oe;
1467	const char				 *layouts[] = {
1468		"even-horizontal", "even-vertical", "main-horizontal",
1469		"main-vertical", "tiled", NULL
1470	};
1471
1472	*size = 0;
1473	for (cmdent = cmd_table; *cmdent != NULL; cmdent++) {
1474		if (strncmp((*cmdent)->name, s, strlen(s)) == 0) {
1475			list = xreallocarray(list, (*size) + 1, sizeof *list);
1476			list[(*size)++] = (*cmdent)->name;
1477		}
1478	}
1479	for (oe = options_table; oe->name != NULL; oe++) {
1480		if (strncmp(oe->name, s, strlen(s)) == 0) {
1481			list = xreallocarray(list, (*size) + 1, sizeof *list);
1482			list[(*size)++] = oe->name;
1483		}
1484	}
1485	for (layout = layouts; *layout != NULL; layout++) {
1486		if (strncmp(*layout, s, strlen(s)) == 0) {
1487			list = xreallocarray(list, (*size) + 1, sizeof *list);
1488			list[(*size)++] = *layout;
1489		}
1490	}
1491	return (list);
1492}
1493
1494/* Find longest prefix. */
1495static char *
1496status_prompt_complete_prefix(const char **list, u_int size)
1497{
1498	char	 *out;
1499	u_int	  i;
1500	size_t	  j;
1501
1502	out = xstrdup(list[0]);
1503	for (i = 1; i < size; i++) {
1504		j = strlen(list[i]);
1505		if (j > strlen(out))
1506			j = strlen(out);
1507		for (; j > 0; j--) {
1508			if (out[j - 1] != list[i][j - 1])
1509				out[j - 1] = '\0';
1510		}
1511	}
1512	return (out);
1513}
1514
1515/* Complete word. */
1516static char *
1517status_prompt_complete(struct session *session, const char *s)
1518{
1519	const char	**list = NULL, *colon;
1520	u_int		  size = 0, i;
1521	struct session	 *s_loop;
1522	struct winlink	 *wl;
1523	struct window	 *w;
1524	char		 *copy, *out, *tmp;
1525
1526	if (*s == '\0')
1527		return (NULL);
1528	out = NULL;
1529
1530	if (strncmp(s, "-t", 2) != 0 && strncmp(s, "-s", 2) != 0) {
1531		list = status_prompt_complete_list(&size, s);
1532		if (size == 0)
1533			out = NULL;
1534		else if (size == 1)
1535			xasprintf(&out, "%s ", list[0]);
1536		else
1537			out = status_prompt_complete_prefix(list, size);
1538		free(list);
1539		return (out);
1540	}
1541	copy = xstrdup(s);
1542
1543	colon = ":";
1544	if (copy[strlen(copy) - 1] == ':')
1545		copy[strlen(copy) - 1] = '\0';
1546	else
1547		colon = "";
1548	s = copy + 2;
1549
1550	RB_FOREACH(s_loop, sessions, &sessions) {
1551		if (strncmp(s_loop->name, s, strlen(s)) == 0) {
1552			list = xreallocarray(list, size + 2, sizeof *list);
1553			list[size++] = s_loop->name;
1554		}
1555	}
1556	if (size == 1) {
1557		out = xstrdup(list[0]);
1558		if (session_find(list[0]) != NULL)
1559			colon = ":";
1560	} else if (size != 0)
1561		out = status_prompt_complete_prefix(list, size);
1562	if (out != NULL) {
1563		xasprintf(&tmp, "-%c%s%s", copy[1], out, colon);
1564		free(out);
1565		out = tmp;
1566		goto found;
1567	}
1568
1569	colon = "";
1570	if (*s == ':') {
1571		RB_FOREACH(wl, winlinks, &session->windows) {
1572			xasprintf(&tmp, ":%s", wl->window->name);
1573			if (strncmp(tmp, s, strlen(s)) == 0){
1574				list = xreallocarray(list, size + 1,
1575				    sizeof *list);
1576				list[size++] = tmp;
1577				continue;
1578			}
1579			free(tmp);
1580
1581			xasprintf(&tmp, ":%d", wl->idx);
1582			if (strncmp(tmp, s, strlen(s)) == 0) {
1583				list = xreallocarray(list, size + 1,
1584				    sizeof *list);
1585				list[size++] = tmp;
1586				continue;
1587			}
1588			free(tmp);
1589		}
1590	} else {
1591		RB_FOREACH(s_loop, sessions, &sessions) {
1592			RB_FOREACH(wl, winlinks, &s_loop->windows) {
1593				w = wl->window;
1594
1595				xasprintf(&tmp, "%s:%s", s_loop->name, w->name);
1596				if (strncmp(tmp, s, strlen(s)) == 0) {
1597					list = xreallocarray(list, size + 1,
1598					    sizeof *list);
1599					list[size++] = tmp;
1600					continue;
1601				}
1602				free(tmp);
1603
1604				xasprintf(&tmp, "%s:%d", s_loop->name, wl->idx);
1605				if (strncmp(tmp, s, strlen(s)) == 0) {
1606					list = xreallocarray(list, size + 1,
1607					    sizeof *list);
1608					list[size++] = tmp;
1609					continue;
1610				}
1611				free(tmp);
1612			}
1613		}
1614	}
1615	if (size == 1) {
1616		out = xstrdup(list[0]);
1617		colon = " ";
1618	} else if (size != 0)
1619		out = status_prompt_complete_prefix(list, size);
1620	if (out != NULL) {
1621		xasprintf(&tmp, "-%c%s%s", copy[1], out, colon);
1622		out = tmp;
1623	}
1624
1625	for (i = 0; i < size; i++)
1626		free((void *)list[i]);
1627
1628found:
1629	free(copy);
1630	free(list);
1631	return (out);
1632}
1633