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