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