xref: /openbsd-src/usr.bin/tmux/format.c (revision c90a81c56dcebd6a1b73fe4aff9b03385b8e63b3)
1 /* $OpenBSD: format.c,v 1.165 2018/11/19 13:35:41 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2011 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/wait.h>
21 
22 #include <ctype.h>
23 #include <errno.h>
24 #include <fnmatch.h>
25 #include <libgen.h>
26 #include <stdarg.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <time.h>
30 #include <unistd.h>
31 
32 #include "tmux.h"
33 
34 /*
35  * Build a list of key-value pairs and use them to expand #{key} entries in a
36  * string.
37  */
38 
39 struct format_entry;
40 typedef void (*format_cb)(struct format_tree *, struct format_entry *);
41 
42 static char	*format_job_get(struct format_tree *, const char *);
43 static void	 format_job_timer(int, short, void *);
44 
45 static char	*format_find(struct format_tree *, const char *, int);
46 static void	 format_add_cb(struct format_tree *, const char *, format_cb);
47 static void	 format_add_tv(struct format_tree *, const char *,
48 		     struct timeval *);
49 static int	 format_replace(struct format_tree *, const char *, size_t,
50 		     char **, size_t *, size_t *);
51 
52 static void	 format_defaults_session(struct format_tree *,
53 		     struct session *);
54 static void	 format_defaults_client(struct format_tree *, struct client *);
55 static void	 format_defaults_winlink(struct format_tree *, struct winlink *);
56 
57 /* Entry in format job tree. */
58 struct format_job {
59 	struct client		*client;
60 	u_int			 tag;
61 	const char		*cmd;
62 	const char		*expanded;
63 
64 	time_t			 last;
65 	char			*out;
66 	int			 updated;
67 
68 	struct job		*job;
69 	int			 status;
70 
71 	RB_ENTRY(format_job)	 entry;
72 };
73 
74 /* Format job tree. */
75 static struct event format_job_event;
76 static int format_job_cmp(struct format_job *, struct format_job *);
77 static RB_HEAD(format_job_tree, format_job) format_jobs = RB_INITIALIZER();
78 RB_GENERATE_STATIC(format_job_tree, format_job, entry, format_job_cmp);
79 
80 /* Format job tree comparison function. */
81 static int
82 format_job_cmp(struct format_job *fj1, struct format_job *fj2)
83 {
84 	if (fj1->tag < fj2->tag)
85 		return (-1);
86 	if (fj1->tag > fj2->tag)
87 		return (1);
88 	return (strcmp(fj1->cmd, fj2->cmd));
89 }
90 
91 /* Format modifiers. */
92 #define FORMAT_TIMESTRING 0x1
93 #define FORMAT_BASENAME 0x2
94 #define FORMAT_DIRNAME 0x4
95 #define FORMAT_SUBSTITUTE 0x8
96 #define FORMAT_QUOTE 0x10
97 
98 /* Entry in format tree. */
99 struct format_entry {
100 	char			*key;
101 	char			*value;
102 	time_t			 t;
103 	format_cb		 cb;
104 	RB_ENTRY(format_entry)	 entry;
105 };
106 
107 /* Format entry tree. */
108 struct format_tree {
109 	struct client		*c;
110 	struct session		*s;
111 	struct winlink		*wl;
112 	struct window		*w;
113 	struct window_pane	*wp;
114 
115 	struct client		*client;
116 	u_int			 tag;
117 	int			 flags;
118 
119 	RB_HEAD(format_entry_tree, format_entry) tree;
120 };
121 static int format_entry_cmp(struct format_entry *, struct format_entry *);
122 RB_GENERATE_STATIC(format_entry_tree, format_entry, entry, format_entry_cmp);
123 
124 /* Format entry tree comparison function. */
125 static int
126 format_entry_cmp(struct format_entry *fe1, struct format_entry *fe2)
127 {
128 	return (strcmp(fe1->key, fe2->key));
129 }
130 
131 /* Single-character uppercase aliases. */
132 static const char *format_upper[] = {
133 	NULL,		/* A */
134 	NULL,		/* B */
135 	NULL,		/* C */
136 	"pane_id",	/* D */
137 	NULL,		/* E */
138 	"window_flags",	/* F */
139 	NULL,		/* G */
140 	"host",		/* H */
141 	"window_index",	/* I */
142 	NULL,		/* J */
143 	NULL,		/* K */
144 	NULL,		/* L */
145 	NULL,		/* M */
146 	NULL,		/* N */
147 	NULL,		/* O */
148 	"pane_index",	/* P */
149 	NULL,		/* Q */
150 	NULL,		/* R */
151 	"session_name",	/* S */
152 	"pane_title",	/* T */
153 	NULL,		/* U */
154 	NULL,		/* V */
155 	"window_name",	/* W */
156 	NULL,		/* X */
157 	NULL,		/* Y */
158 	NULL 		/* Z */
159 };
160 
161 /* Single-character lowercase aliases. */
162 static const char *format_lower[] = {
163 	NULL,		/* a */
164 	NULL,		/* b */
165 	NULL,		/* c */
166 	NULL,		/* d */
167 	NULL,		/* e */
168 	NULL,		/* f */
169 	NULL,		/* g */
170 	"host_short",	/* h */
171 	NULL,		/* i */
172 	NULL,		/* j */
173 	NULL,		/* k */
174 	NULL,		/* l */
175 	NULL,		/* m */
176 	NULL,		/* n */
177 	NULL,		/* o */
178 	NULL,		/* p */
179 	NULL,		/* q */
180 	NULL,		/* r */
181 	NULL,		/* s */
182 	NULL,		/* t */
183 	NULL,		/* u */
184 	NULL,		/* v */
185 	NULL,		/* w */
186 	NULL,		/* x */
187 	NULL,		/* y */
188 	NULL		/* z */
189 };
190 
191 /* Format job update callback. */
192 static void
193 format_job_update(struct job *job)
194 {
195 	struct format_job	*fj = job_get_data(job);
196 	struct evbuffer		*evb = job_get_event(job)->input;
197 	char			*line = NULL, *next;
198 	time_t			 t;
199 
200 	while ((next = evbuffer_readline(evb)) != NULL) {
201 		free(line);
202 		line = next;
203 	}
204 	if (line == NULL)
205 		return;
206 	fj->updated = 1;
207 
208 	free(fj->out);
209 	fj->out = line;
210 
211 	log_debug("%s: %p %s: %s", __func__, fj, fj->cmd, fj->out);
212 
213 	t = time(NULL);
214 	if (fj->status && fj->last != t) {
215 		if (fj->client != NULL)
216 			server_status_client(fj->client);
217 		fj->last = t;
218 	}
219 }
220 
221 /* Format job complete callback. */
222 static void
223 format_job_complete(struct job *job)
224 {
225 	struct format_job	*fj = job_get_data(job);
226 	struct evbuffer		*evb = job_get_event(job)->input;
227 	char			*line, *buf;
228 	size_t			 len;
229 
230 	fj->job = NULL;
231 
232 	buf = NULL;
233 	if ((line = evbuffer_readline(evb)) == NULL) {
234 		len = EVBUFFER_LENGTH(evb);
235 		buf = xmalloc(len + 1);
236 		if (len != 0)
237 			memcpy(buf, EVBUFFER_DATA(evb), len);
238 		buf[len] = '\0';
239 	} else
240 		buf = line;
241 
242 	log_debug("%s: %p %s: %s", __func__, fj, fj->cmd, buf);
243 
244 	if (*buf != '\0' || !fj->updated) {
245 		free(fj->out);
246 		fj->out = buf;
247 	} else
248 		free(buf);
249 
250 	if (fj->status) {
251 		if (fj->client != NULL)
252 			server_status_client(fj->client);
253 		fj->status = 0;
254 	}
255 }
256 
257 /* Find a job. */
258 static char *
259 format_job_get(struct format_tree *ft, const char *cmd)
260 {
261 	struct format_job_tree	*jobs;
262 	struct format_job	 fj0, *fj;
263 	time_t			 t;
264 	char			*expanded;
265 	int			 force;
266 
267 	if (ft->client == NULL)
268 		jobs = &format_jobs;
269 	else if (ft->client->jobs != NULL)
270 		jobs = ft->client->jobs;
271 	else {
272 		jobs = ft->client->jobs = xmalloc(sizeof *ft->client->jobs);
273 		RB_INIT(jobs);
274 	}
275 
276 	fj0.tag = ft->tag;
277 	fj0.cmd = cmd;
278 	if ((fj = RB_FIND(format_job_tree, jobs, &fj0)) == NULL) {
279 		fj = xcalloc(1, sizeof *fj);
280 		fj->client = ft->client;
281 		fj->tag = ft->tag;
282 		fj->cmd = xstrdup(cmd);
283 		fj->expanded = NULL;
284 
285 		xasprintf(&fj->out, "<'%s' not ready>", fj->cmd);
286 
287 		RB_INSERT(format_job_tree, jobs, fj);
288 	}
289 
290 	expanded = format_expand(ft, cmd);
291 	if (fj->expanded == NULL || strcmp(expanded, fj->expanded) != 0) {
292 		free((void *)fj->expanded);
293 		fj->expanded = xstrdup(expanded);
294 		force = 1;
295 	} else
296 		force = (ft->flags & FORMAT_FORCE);
297 
298 	t = time(NULL);
299 	if (fj->job == NULL && (force || fj->last != t)) {
300 		fj->job = job_run(expanded, NULL,
301 		    server_client_get_cwd(ft->client, NULL), format_job_update,
302 		    format_job_complete, NULL, fj, JOB_NOWAIT);
303 		if (fj->job == NULL) {
304 			free(fj->out);
305 			xasprintf(&fj->out, "<'%s' didn't start>", fj->cmd);
306 		}
307 		fj->last = t;
308 		fj->updated = 0;
309 	}
310 
311 	if (ft->flags & FORMAT_STATUS)
312 		fj->status = 1;
313 
314 	free(expanded);
315 	return (format_expand(ft, fj->out));
316 }
317 
318 /* Remove old jobs. */
319 static void
320 format_job_tidy(struct format_job_tree *jobs, int force)
321 {
322 	struct format_job	*fj, *fj1;
323 	time_t			 now;
324 
325 	now = time(NULL);
326 	RB_FOREACH_SAFE(fj, format_job_tree, jobs, fj1) {
327 		if (!force && (fj->last > now || now - fj->last < 3600))
328 			continue;
329 		RB_REMOVE(format_job_tree, jobs, fj);
330 
331 		log_debug("%s: %s", __func__, fj->cmd);
332 
333 		if (fj->job != NULL)
334 			job_free(fj->job);
335 
336 		free((void *)fj->expanded);
337 		free((void *)fj->cmd);
338 		free(fj->out);
339 
340 		free(fj);
341 	}
342 }
343 
344 /* Remove old jobs for client. */
345 void
346 format_lost_client(struct client *c)
347 {
348 	if (c->jobs != NULL)
349 		format_job_tidy(c->jobs, 1);
350 	free(c->jobs);
351 }
352 
353 /* Remove old jobs periodically. */
354 static void
355 format_job_timer(__unused int fd, __unused short events, __unused void *arg)
356 {
357 	struct client	*c;
358 	struct timeval	 tv = { .tv_sec = 60 };
359 
360 	format_job_tidy(&format_jobs, 0);
361 	TAILQ_FOREACH(c, &clients, entry) {
362 		if (c->jobs != NULL)
363 			format_job_tidy(c->jobs, 0);
364 	}
365 
366 	evtimer_del(&format_job_event);
367 	evtimer_add(&format_job_event, &tv);
368 }
369 
370 /* Callback for host. */
371 static void
372 format_cb_host(__unused struct format_tree *ft, struct format_entry *fe)
373 {
374 	char host[HOST_NAME_MAX + 1];
375 
376 	if (gethostname(host, sizeof host) != 0)
377 		fe->value = xstrdup("");
378 	else
379 		fe->value = xstrdup(host);
380 }
381 
382 /* Callback for host_short. */
383 static void
384 format_cb_host_short(__unused struct format_tree *ft, struct format_entry *fe)
385 {
386 	char host[HOST_NAME_MAX + 1], *cp;
387 
388 	if (gethostname(host, sizeof host) != 0)
389 		fe->value = xstrdup("");
390 	else {
391 		if ((cp = strchr(host, '.')) != NULL)
392 			*cp = '\0';
393 		fe->value = xstrdup(host);
394 	}
395 }
396 
397 /* Callback for pid. */
398 static void
399 format_cb_pid(__unused struct format_tree *ft, struct format_entry *fe)
400 {
401 	xasprintf(&fe->value, "%ld", (long)getpid());
402 }
403 
404 /* Callback for session_alerts. */
405 static void
406 format_cb_session_alerts(struct format_tree *ft, struct format_entry *fe)
407 {
408 	struct session	*s = ft->s;
409 	struct winlink	*wl;
410 	char		 alerts[1024], tmp[16];
411 
412 	if (s == NULL)
413 		return;
414 
415 	*alerts = '\0';
416 	RB_FOREACH(wl, winlinks, &s->windows) {
417 		if ((wl->flags & WINLINK_ALERTFLAGS) == 0)
418 			continue;
419 		xsnprintf(tmp, sizeof tmp, "%u", wl->idx);
420 
421 		if (*alerts != '\0')
422 			strlcat(alerts, ",", sizeof alerts);
423 		strlcat(alerts, tmp, sizeof alerts);
424 		if (wl->flags & WINLINK_ACTIVITY)
425 			strlcat(alerts, "#", sizeof alerts);
426 		if (wl->flags & WINLINK_BELL)
427 			strlcat(alerts, "!", sizeof alerts);
428 		if (wl->flags & WINLINK_SILENCE)
429 			strlcat(alerts, "~", sizeof alerts);
430 	}
431 	fe->value = xstrdup(alerts);
432 }
433 
434 /* Callback for session_stack. */
435 static void
436 format_cb_session_stack(struct format_tree *ft, struct format_entry *fe)
437 {
438 	struct session	*s = ft->s;
439 	struct winlink	*wl;
440 	char		 result[1024], tmp[16];
441 
442 	if (s == NULL)
443 		return;
444 
445 	xsnprintf(result, sizeof result, "%u", s->curw->idx);
446 	TAILQ_FOREACH(wl, &s->lastw, sentry) {
447 		xsnprintf(tmp, sizeof tmp, "%u", wl->idx);
448 
449 		if (*result != '\0')
450 			strlcat(result, ",", sizeof result);
451 		strlcat(result, tmp, sizeof result);
452 	}
453 	fe->value = xstrdup(result);
454 }
455 
456 /* Callback for window_stack_index. */
457 static void
458 format_cb_window_stack_index(struct format_tree *ft, struct format_entry *fe)
459 {
460 	struct session	*s = ft->wl->session;
461 	struct winlink	*wl;
462 	u_int		 idx;
463 
464 	idx = 0;
465 	TAILQ_FOREACH(wl, &s->lastw, sentry) {
466 		idx++;
467 		if (wl == ft->wl)
468 			break;
469 	}
470 	if (wl != NULL)
471 		xasprintf(&fe->value, "%u", idx);
472 	else
473 		fe->value = xstrdup("0");
474 }
475 
476 /* Callback for window_layout. */
477 static void
478 format_cb_window_layout(struct format_tree *ft, struct format_entry *fe)
479 {
480 	struct window	*w = ft->w;
481 
482 	if (w == NULL)
483 		return;
484 
485 	if (w->saved_layout_root != NULL)
486 		fe->value = layout_dump(w->saved_layout_root);
487 	else
488 		fe->value = layout_dump(w->layout_root);
489 }
490 
491 /* Callback for window_visible_layout. */
492 static void
493 format_cb_window_visible_layout(struct format_tree *ft, struct format_entry *fe)
494 {
495 	struct window	*w = ft->w;
496 
497 	if (w == NULL)
498 		return;
499 
500 	fe->value = layout_dump(w->layout_root);
501 }
502 
503 /* Callback for pane_start_command. */
504 static void
505 format_cb_start_command(struct format_tree *ft, struct format_entry *fe)
506 {
507 	struct window_pane	*wp = ft->wp;
508 
509 	if (wp == NULL)
510 		return;
511 
512 	fe->value = cmd_stringify_argv(wp->argc, wp->argv);
513 }
514 
515 /* Callback for pane_current_command. */
516 static void
517 format_cb_current_command(struct format_tree *ft, struct format_entry *fe)
518 {
519 	struct window_pane	*wp = ft->wp;
520 	char			*cmd;
521 
522 	if (wp == NULL)
523 		return;
524 
525 	cmd = get_proc_name(wp->fd, wp->tty);
526 	if (cmd == NULL || *cmd == '\0') {
527 		free(cmd);
528 		cmd = cmd_stringify_argv(wp->argc, wp->argv);
529 		if (cmd == NULL || *cmd == '\0') {
530 			free(cmd);
531 			cmd = xstrdup(wp->shell);
532 		}
533 	}
534 	fe->value = parse_window_name(cmd);
535 	free(cmd);
536 }
537 
538 /* Callback for history_bytes. */
539 static void
540 format_cb_history_bytes(struct format_tree *ft, struct format_entry *fe)
541 {
542 	struct window_pane	*wp = ft->wp;
543 	struct grid		*gd;
544 	struct grid_line	*gl;
545 	unsigned long long	 size;
546 	u_int			 i;
547 
548 	if (wp == NULL)
549 		return;
550 	gd = wp->base.grid;
551 
552 	size = 0;
553 	for (i = 0; i < gd->hsize; i++) {
554 		gl = grid_get_line(gd, i);
555 		size += gl->cellsize * sizeof *gl->celldata;
556 		size += gl->extdsize * sizeof *gl->extddata;
557 	}
558 	size += gd->hsize * sizeof *gl;
559 
560 	xasprintf(&fe->value, "%llu", size);
561 }
562 
563 /* Callback for pane_tabs. */
564 static void
565 format_cb_pane_tabs(struct format_tree *ft, struct format_entry *fe)
566 {
567 	struct window_pane	*wp = ft->wp;
568 	struct evbuffer		*buffer;
569 	u_int			 i;
570 	int			 size;
571 
572 	if (wp == NULL)
573 		return;
574 
575 	buffer = evbuffer_new();
576 	if (buffer == NULL)
577 		fatalx("out of memory");
578 	for (i = 0; i < wp->base.grid->sx; i++) {
579 		if (!bit_test(wp->base.tabs, i))
580 			continue;
581 
582 		if (EVBUFFER_LENGTH(buffer) > 0)
583 			evbuffer_add(buffer, ",", 1);
584 		evbuffer_add_printf(buffer, "%u", i);
585 	}
586 	if ((size = EVBUFFER_LENGTH(buffer)) != 0)
587 		xasprintf(&fe->value, "%.*s", size, EVBUFFER_DATA(buffer));
588 	evbuffer_free(buffer);
589 }
590 
591 /* Callback for session_group_list. */
592 static void
593 format_cb_session_group_list(struct format_tree *ft, struct format_entry *fe)
594 {
595 	struct session		*s = ft->s;
596 	struct session_group	*sg;
597 	struct session		*loop;
598 	struct evbuffer		*buffer;
599 	int			 size;
600 
601 	if (s == NULL)
602 		return;
603 	sg = session_group_contains(s);
604 	if (sg == NULL)
605 		return;
606 
607 	buffer = evbuffer_new();
608 	if (buffer == NULL)
609 		fatalx("out of memory");
610 	TAILQ_FOREACH(loop, &sg->sessions, gentry) {
611 		if (EVBUFFER_LENGTH(buffer) > 0)
612 			evbuffer_add(buffer, ",", 1);
613 		evbuffer_add_printf(buffer, "%s", loop->name);
614 	}
615 	if ((size = EVBUFFER_LENGTH(buffer)) != 0)
616 		xasprintf(&fe->value, "%.*s", size, EVBUFFER_DATA(buffer));
617 	evbuffer_free(buffer);
618 }
619 
620 /* Merge a format tree. */
621 static void
622 format_merge(struct format_tree *ft, struct format_tree *from)
623 {
624 	struct format_entry	*fe;
625 
626 	RB_FOREACH(fe, format_entry_tree, &from->tree) {
627 		if (fe->value != NULL)
628 			format_add(ft, fe->key, "%s", fe->value);
629 	}
630 }
631 
632 /* Create a new tree. */
633 struct format_tree *
634 format_create(struct client *c, struct cmdq_item *item, int tag, int flags)
635 {
636 	struct format_tree	*ft;
637 
638 	if (!event_initialized(&format_job_event)) {
639 		evtimer_set(&format_job_event, format_job_timer, NULL);
640 		format_job_timer(-1, 0, NULL);
641 	}
642 
643 	ft = xcalloc(1, sizeof *ft);
644 	RB_INIT(&ft->tree);
645 
646 	if (c != NULL) {
647 		ft->client = c;
648 		ft->client->references++;
649 	}
650 
651 	ft->tag = tag;
652 	ft->flags = flags;
653 
654 	format_add_cb(ft, "host", format_cb_host);
655 	format_add_cb(ft, "host_short", format_cb_host_short);
656 	format_add_cb(ft, "pid", format_cb_pid);
657 	format_add(ft, "socket_path", "%s", socket_path);
658 	format_add_tv(ft, "start_time", &start_time);
659 
660 	if (item != NULL) {
661 		if (item->cmd != NULL)
662 			format_add(ft, "command", "%s", item->cmd->entry->name);
663 		if (item->shared != NULL && item->shared->formats != NULL)
664 			format_merge(ft, item->shared->formats);
665 	}
666 
667 	return (ft);
668 }
669 
670 /* Free a tree. */
671 void
672 format_free(struct format_tree *ft)
673 {
674 	struct format_entry	*fe, *fe1;
675 
676 	RB_FOREACH_SAFE(fe, format_entry_tree, &ft->tree, fe1) {
677 		RB_REMOVE(format_entry_tree, &ft->tree, fe);
678 		free(fe->value);
679 		free(fe->key);
680 		free(fe);
681 	}
682 
683 	if (ft->client != NULL)
684 		server_client_unref(ft->client);
685 	free(ft);
686 }
687 
688 /* Add a key-value pair. */
689 void
690 format_add(struct format_tree *ft, const char *key, const char *fmt, ...)
691 {
692 	struct format_entry	*fe;
693 	struct format_entry	*fe_now;
694 	va_list			 ap;
695 
696 	fe = xmalloc(sizeof *fe);
697 	fe->key = xstrdup(key);
698 
699 	fe_now = RB_INSERT(format_entry_tree, &ft->tree, fe);
700 	if (fe_now != NULL) {
701 		free(fe->key);
702 		free(fe);
703 		free(fe_now->value);
704 		fe = fe_now;
705 	}
706 
707 	fe->cb = NULL;
708 	fe->t = 0;
709 
710 	va_start(ap, fmt);
711 	xvasprintf(&fe->value, fmt, ap);
712 	va_end(ap);
713 }
714 
715 /* Add a key and time. */
716 static void
717 format_add_tv(struct format_tree *ft, const char *key, struct timeval *tv)
718 {
719 	struct format_entry	*fe;
720 	struct format_entry	*fe_now;
721 
722 	fe = xmalloc(sizeof *fe);
723 	fe->key = xstrdup(key);
724 
725 	fe_now = RB_INSERT(format_entry_tree, &ft->tree, fe);
726 	if (fe_now != NULL) {
727 		free(fe->key);
728 		free(fe);
729 		free(fe_now->value);
730 		fe = fe_now;
731 	}
732 
733 	fe->cb = NULL;
734 	fe->t = tv->tv_sec;
735 
736 	fe->value = NULL;
737 }
738 
739 /* Add a key and function. */
740 static void
741 format_add_cb(struct format_tree *ft, const char *key, format_cb cb)
742 {
743 	struct format_entry	*fe;
744 	struct format_entry	*fe_now;
745 
746 	fe = xmalloc(sizeof *fe);
747 	fe->key = xstrdup(key);
748 
749 	fe_now = RB_INSERT(format_entry_tree, &ft->tree, fe);
750 	if (fe_now != NULL) {
751 		free(fe->key);
752 		free(fe);
753 		free(fe_now->value);
754 		fe = fe_now;
755 	}
756 
757 	fe->cb = cb;
758 	fe->t = 0;
759 
760 	fe->value = NULL;
761 }
762 
763 /* Quote special characters in string. */
764 static char *
765 format_quote(const char *s)
766 {
767 	const char	*cp;
768 	char		*out, *at;
769 
770 	at = out = xmalloc(strlen(s) * 2 + 1);
771 	for (cp = s; *cp != '\0'; cp++) {
772 		if (strchr("|&;<>()$`\\\"'*?[# =%", *cp) != NULL)
773 			*at++ = '\\';
774 		*at++ = *cp;
775 	}
776 	*at = '\0';
777 	return (out);
778 }
779 
780 /* Find a format entry. */
781 static char *
782 format_find(struct format_tree *ft, const char *key, int modifiers)
783 {
784 	struct format_entry	*fe, fe_find;
785 	struct environ_entry	*envent;
786 	static char		 s[64];
787 	struct options_entry	*o;
788 	const char		*found;
789 	int			 idx;
790 	char			*copy, *saved;
791 
792 	if (~modifiers & FORMAT_TIMESTRING) {
793 		o = options_parse_get(global_options, key, &idx, 0);
794 		if (o == NULL && ft->w != NULL)
795 			o = options_parse_get(ft->w->options, key, &idx, 0);
796 		if (o == NULL)
797 			o = options_parse_get(global_w_options, key, &idx, 0);
798 		if (o == NULL && ft->s != NULL)
799 			o = options_parse_get(ft->s->options, key, &idx, 0);
800 		if (o == NULL)
801 			o = options_parse_get(global_s_options, key, &idx, 0);
802 		if (o != NULL) {
803 			found = options_tostring(o, idx, 1);
804 			goto found;
805 		}
806 	}
807 	found = NULL;
808 
809 	fe_find.key = (char *) key;
810 	fe = RB_FIND(format_entry_tree, &ft->tree, &fe_find);
811 	if (fe != NULL) {
812 		if (modifiers & FORMAT_TIMESTRING) {
813 			if (fe->t == 0)
814 				return (NULL);
815 			ctime_r(&fe->t, s);
816 			s[strcspn(s, "\n")] = '\0';
817 			found = s;
818 			goto found;
819 		}
820 		if (fe->t != 0) {
821 			xsnprintf(s, sizeof s, "%lld", (long long)fe->t);
822 			found = s;
823 			goto found;
824 		}
825 		if (fe->value == NULL && fe->cb != NULL) {
826 			fe->cb(ft, fe);
827 			if (fe->value == NULL)
828 				fe->value = xstrdup("");
829 		}
830 		found = fe->value;
831 		goto found;
832 	}
833 
834 	if (~modifiers & FORMAT_TIMESTRING) {
835 		envent = NULL;
836 		if (ft->s != NULL)
837 			envent = environ_find(ft->s->environ, key);
838 		if (envent == NULL)
839 			envent = environ_find(global_environ, key);
840 		if (envent != NULL) {
841 			found = envent->value;
842 			goto found;
843 		}
844 	}
845 
846 	return (NULL);
847 
848 found:
849 	if (found == NULL)
850 		return (NULL);
851 	copy = xstrdup(found);
852 	if (modifiers & FORMAT_BASENAME) {
853 		saved = copy;
854 		copy = xstrdup(basename(saved));
855 		free(saved);
856 	}
857 	if (modifiers & FORMAT_DIRNAME) {
858 		saved = copy;
859 		copy = xstrdup(dirname(saved));
860 		free(saved);
861 	}
862 	if (modifiers & FORMAT_QUOTE) {
863 		saved = copy;
864 		copy = xstrdup(format_quote(saved));
865 		free(saved);
866 	}
867 	return (copy);
868 }
869 
870 /* Skip until end. */
871 static const char *
872 format_skip(const char *s, char end)
873 {
874 	int	brackets = 0;
875 
876 	for (; *s != '\0'; s++) {
877 		if (*s == '#' && s[1] == '{')
878 			brackets++;
879 		if (*s == '#' && strchr(",#{}", s[1]) != NULL) {
880 			s++;
881 			continue;
882 		}
883 		if (*s == '}')
884 			brackets--;
885 		if (*s == end && brackets == 0)
886 			break;
887 	}
888 	if (*s == '\0')
889 		return (NULL);
890 	return (s);
891 }
892 
893 /* Return left and right alternatives separated by commas. */
894 static int
895 format_choose(char *s, char **left, char **right)
896 {
897 	char	*cp;
898 
899 	cp = (char *)format_skip(s, ',');
900 	if (cp == NULL)
901 		return (-1);
902 	*cp = '\0';
903 
904 	*left = s;
905 	*right = cp + 1;
906 	return (0);
907 }
908 
909 /* Is this true? */
910 int
911 format_true(const char *s)
912 {
913 	if (s != NULL && *s != '\0' && (s[0] != '0' || s[1] != '\0'))
914 		return (1);
915 	return (0);
916 }
917 
918 /* Replace a key. */
919 static int
920 format_replace(struct format_tree *ft, const char *key, size_t keylen,
921     char **buf, size_t *len, size_t *off)
922 {
923 	struct window_pane	*wp = ft->wp;
924 	char			*copy, *copy0, *endptr, *ptr, *found, *new, sep;
925 	char			*value, *from = NULL, *to = NULL, *left, *right;
926 	size_t			 valuelen, newlen, fromlen, tolen, used;
927 	long			 limit = 0;
928 	int			 modifiers = 0, compare = 0, search = 0;
929 	int			 literal = 0;
930 
931 	/* Make a copy of the key. */
932 	copy0 = copy = xmalloc(keylen + 1);
933 	memcpy(copy, key, keylen);
934 	copy[keylen] = '\0';
935 
936 	/* Is there a length limit or whatnot? */
937 	switch (copy[0]) {
938 	case 'l':
939 		if (copy[1] != ':')
940 			break;
941 		literal = 1;
942 		copy += 2;
943 		break;
944 	case 'm':
945 		if (copy[1] != ':')
946 			break;
947 		compare = -2;
948 		copy += 2;
949 		break;
950 	case 'C':
951 		if (copy[1] != ':')
952 			break;
953 		search = 1;
954 		copy += 2;
955 		break;
956 	case '|':
957 		if (copy[1] != '|' || copy[2] != ':')
958 			break;
959 		compare = -3;
960 		copy += 3;
961 		break;
962 	case '&':
963 		if (copy[1] != '&' || copy[2] != ':')
964 			break;
965 		compare = -4;
966 		copy += 3;
967 		break;
968 	case '!':
969 		if (copy[1] == '=' && copy[2] == ':') {
970 			compare = -1;
971 			copy += 3;
972 			break;
973 		}
974 		break;
975 	case '=':
976 		if (copy[1] == '=' && copy[2] == ':') {
977 			compare = 1;
978 			copy += 3;
979 			break;
980 		}
981 		errno = 0;
982 		limit = strtol(copy + 1, &endptr, 10);
983 		if (errno == ERANGE && (limit == LONG_MIN || limit == LONG_MAX))
984 			break;
985 		if (*endptr != ':')
986 			break;
987 		copy = endptr + 1;
988 		break;
989 	case 'b':
990 		if (copy[1] != ':')
991 			break;
992 		modifiers |= FORMAT_BASENAME;
993 		copy += 2;
994 		break;
995 	case 'd':
996 		if (copy[1] != ':')
997 			break;
998 		modifiers |= FORMAT_DIRNAME;
999 		copy += 2;
1000 		break;
1001 	case 't':
1002 		if (copy[1] != ':')
1003 			break;
1004 		modifiers |= FORMAT_TIMESTRING;
1005 		copy += 2;
1006 		break;
1007 	case 'q':
1008 		if (copy[1] != ':')
1009 			break;
1010 		modifiers |= FORMAT_QUOTE;
1011 		copy += 2;
1012 		break;
1013 	case 's':
1014 		sep = copy[1];
1015 		if (sep == ':' || !ispunct((u_char)sep))
1016 			break;
1017 		from = copy + 2;
1018 		for (copy = from; *copy != '\0' && *copy != sep; copy++)
1019 			/* nothing */;
1020 		if (copy[0] != sep || copy == from) {
1021 			copy = copy0;
1022 			break;
1023 		}
1024 		copy[0] = '\0';
1025 		to = copy + 1;
1026 		for (copy = to; *copy != '\0' && *copy != sep; copy++)
1027 			/* nothing */;
1028 		if (copy[0] != sep || copy[1] != ':') {
1029 			copy = copy0;
1030 			break;
1031 		}
1032 		copy[0] = '\0';
1033 
1034 		modifiers |= FORMAT_SUBSTITUTE;
1035 		copy += 2;
1036 		break;
1037 	}
1038 
1039 	/* Is this a literal string? */
1040 	if (literal) {
1041 		value = xstrdup(copy);
1042 		goto done;
1043 	}
1044 
1045 	/* Is this a comparison or a conditional? */
1046 	if (search) {
1047 		/* Search in pane. */
1048 		if (wp == NULL)
1049 			value = xstrdup("0");
1050 		else
1051 			xasprintf(&value, "%u", window_pane_search(wp, copy));
1052 	} else if (compare != 0) {
1053 		/* Comparison: compare comma-separated left and right. */
1054 		if (format_choose(copy, &left, &right) != 0)
1055 			goto fail;
1056 		left = format_expand(ft, left);
1057 		right = format_expand(ft, right);
1058 		if (compare == -3 &&
1059 		    (format_true(left) || format_true(right)))
1060 			value = xstrdup("1");
1061 		else if (compare == -4 &&
1062 		    (format_true(left) && format_true(right)))
1063 			value = xstrdup("1");
1064 		else if (compare == 1 && strcmp(left, right) == 0)
1065 			value = xstrdup("1");
1066 		else if (compare == -1 && strcmp(left, right) != 0)
1067 			value = xstrdup("1");
1068 		else if (compare == -2 && fnmatch(left, right, 0) == 0)
1069 			value = xstrdup("1");
1070 		else
1071 			value = xstrdup("0");
1072 		free(right);
1073 		free(left);
1074 	} else if (*copy == '?') {
1075 		/* Conditional: check first and choose second or third. */
1076 		ptr = (char *)format_skip(copy, ',');
1077 		if (ptr == NULL)
1078 			goto fail;
1079 		*ptr = '\0';
1080 
1081 		found = format_find(ft, copy + 1, modifiers);
1082 		if (found == NULL) {
1083 			/*
1084 			 * If the conditional not found, try to expand it. If
1085 			 * the expansion doesn't have any effect, then assume
1086 			 * false.
1087 			 */
1088 			found = format_expand(ft, copy + 1);
1089 			if (strcmp(found, copy + 1) == 0) {
1090 				free(found);
1091 				found = xstrdup("");
1092 			}
1093 		}
1094 		if (format_choose(ptr + 1, &left, &right) != 0) {
1095 			free(found);
1096 			goto fail;
1097 		}
1098 
1099 		if (format_true(found))
1100 			value = format_expand(ft, left);
1101 		else
1102 			value = format_expand(ft, right);
1103 		free(found);
1104 	} else {
1105 		/* Neither: look up directly. */
1106 		value = format_find(ft, copy, modifiers);
1107 		if (value == NULL)
1108 			value = xstrdup("");
1109 	}
1110 
1111 	/* Perform substitution if any. */
1112 	if (modifiers & FORMAT_SUBSTITUTE) {
1113 		fromlen = strlen(from);
1114 		tolen = strlen(to);
1115 
1116 		newlen = strlen(value) + 1;
1117 		copy = new = xmalloc(newlen);
1118 		for (ptr = value; *ptr != '\0'; /* nothing */) {
1119 			if (strncmp(ptr, from, fromlen) != 0) {
1120 				*new++ = *ptr++;
1121 				continue;
1122 			}
1123 			used = new - copy;
1124 
1125 			newlen += tolen;
1126 			copy = xrealloc(copy, newlen);
1127 
1128 			new = copy + used;
1129 			memcpy(new, to, tolen);
1130 
1131 			new += tolen;
1132 			ptr += fromlen;
1133 		}
1134 		*new = '\0';
1135 		free(value);
1136 		value = copy;
1137 	}
1138 
1139 	/* Truncate the value if needed. */
1140 	if (limit > 0) {
1141 		new = utf8_trimcstr(value, limit);
1142 		free(value);
1143 		value = new;
1144 	} else if (limit < 0) {
1145 		new = utf8_rtrimcstr(value, -limit);
1146 		free(value);
1147 		value = new;
1148 	}
1149 
1150 done:
1151 	/* Expand the buffer and copy in the value. */
1152 	valuelen = strlen(value);
1153 	while (*len - *off < valuelen + 1) {
1154 		*buf = xreallocarray(*buf, 2, *len);
1155 		*len *= 2;
1156 	}
1157 	memcpy(*buf + *off, value, valuelen);
1158 	*off += valuelen;
1159 
1160 	free(value);
1161 	free(copy0);
1162 	return (0);
1163 
1164 fail:
1165 	free(copy0);
1166 	return (-1);
1167 }
1168 
1169 /* Expand keys in a template, passing through strftime first. */
1170 char *
1171 format_expand_time(struct format_tree *ft, const char *fmt, time_t t)
1172 {
1173 	struct tm	*tm;
1174 	char		 s[2048];
1175 
1176 	if (fmt == NULL || *fmt == '\0')
1177 		return (xstrdup(""));
1178 
1179 	tm = localtime(&t);
1180 
1181 	if (strftime(s, sizeof s, fmt, tm) == 0)
1182 		return (xstrdup(""));
1183 
1184 	return (format_expand(ft, s));
1185 }
1186 
1187 /* Expand keys in a template. */
1188 char *
1189 format_expand(struct format_tree *ft, const char *fmt)
1190 {
1191 	char		*buf, *out, *name;
1192 	const char	*ptr, *s, *saved = fmt;
1193 	size_t		 off, len, n, outlen;
1194 	int     	 ch, brackets;
1195 
1196 	if (fmt == NULL)
1197 		return (xstrdup(""));
1198 
1199 	len = 64;
1200 	buf = xmalloc(len);
1201 	off = 0;
1202 
1203 	while (*fmt != '\0') {
1204 		if (*fmt != '#') {
1205 			while (len - off < 2) {
1206 				buf = xreallocarray(buf, 2, len);
1207 				len *= 2;
1208 			}
1209 			buf[off++] = *fmt++;
1210 			continue;
1211 		}
1212 		fmt++;
1213 
1214 		ch = (u_char) *fmt++;
1215 		switch (ch) {
1216 		case '(':
1217 			brackets = 1;
1218 			for (ptr = fmt; *ptr != '\0'; ptr++) {
1219 				if (*ptr == '(')
1220 					brackets++;
1221 				if (*ptr == ')' && --brackets == 0)
1222 					break;
1223 			}
1224 			if (*ptr != ')' || brackets != 0)
1225 				break;
1226 			n = ptr - fmt;
1227 
1228 			if (ft->flags & FORMAT_NOJOBS)
1229 				out = xstrdup("");
1230 			else {
1231 				name = xstrndup(fmt, n);
1232 				out = format_job_get(ft, name);
1233 				free(name);
1234 			}
1235 			outlen = strlen(out);
1236 
1237 			while (len - off < outlen + 1) {
1238 				buf = xreallocarray(buf, 2, len);
1239 				len *= 2;
1240 			}
1241 			memcpy(buf + off, out, outlen);
1242 			off += outlen;
1243 
1244 			free(out);
1245 
1246 			fmt += n + 1;
1247 			continue;
1248 		case '{':
1249 			ptr = format_skip(fmt - 2, '}');
1250 			if (ptr == NULL)
1251 				break;
1252 			n = ptr - fmt;
1253 
1254 			if (format_replace(ft, fmt, n, &buf, &len, &off) != 0)
1255 				break;
1256 			fmt += n + 1;
1257 			continue;
1258 		case '}':
1259 		case '#':
1260 		case ',':
1261 			while (len - off < 2) {
1262 				buf = xreallocarray(buf, 2, len);
1263 				len *= 2;
1264 			}
1265 			buf[off++] = ch;
1266 			continue;
1267 		default:
1268 			s = NULL;
1269 			if (ch >= 'A' && ch <= 'Z')
1270 				s = format_upper[ch - 'A'];
1271 			else if (ch >= 'a' && ch <= 'z')
1272 				s = format_lower[ch - 'a'];
1273 			if (s == NULL) {
1274 				while (len - off < 3) {
1275 					buf = xreallocarray(buf, 2, len);
1276 					len *= 2;
1277 				}
1278 				buf[off++] = '#';
1279 				buf[off++] = ch;
1280 				continue;
1281 			}
1282 			n = strlen(s);
1283 			if (format_replace(ft, s, n, &buf, &len, &off) != 0)
1284 				break;
1285 			continue;
1286 		}
1287 
1288 		break;
1289 	}
1290 	buf[off] = '\0';
1291 
1292 	log_debug("format '%s' -> '%s'", saved, buf);
1293 	return (buf);
1294 }
1295 
1296 /* Expand a single string. */
1297 char *
1298 format_single(struct cmdq_item *item, const char *fmt, struct client *c,
1299     struct session *s, struct winlink *wl, struct window_pane *wp)
1300 {
1301 	struct format_tree	*ft;
1302 	char			*expanded;
1303 
1304 	if (item != NULL)
1305 		ft = format_create(item->client, item, FORMAT_NONE, 0);
1306 	else
1307 		ft = format_create(NULL, item, FORMAT_NONE, 0);
1308 	format_defaults(ft, c, s, wl, wp);
1309 
1310 	expanded = format_expand(ft, fmt);
1311 	format_free(ft);
1312 	return (expanded);
1313 }
1314 
1315 /* Set defaults for any of arguments that are not NULL. */
1316 void
1317 format_defaults(struct format_tree *ft, struct client *c, struct session *s,
1318     struct winlink *wl, struct window_pane *wp)
1319 {
1320 	if (c != NULL && s != NULL && c->session != s)
1321 		log_debug("%s: session does not match", __func__);
1322 
1323 	format_add(ft, "session_format", "%d", s != NULL);
1324 	format_add(ft, "window_format", "%d", wl != NULL);
1325 	format_add(ft, "pane_format", "%d", wp != NULL);
1326 
1327 	if (s == NULL && c != NULL)
1328 		s = c->session;
1329 	if (wl == NULL && s != NULL)
1330 		wl = s->curw;
1331 	if (wp == NULL && wl != NULL)
1332 		wp = wl->window->active;
1333 
1334 	if (c != NULL)
1335 		format_defaults_client(ft, c);
1336 	if (s != NULL)
1337 		format_defaults_session(ft, s);
1338 	if (wl != NULL)
1339 		format_defaults_winlink(ft, wl);
1340 	if (wp != NULL)
1341 		format_defaults_pane(ft, wp);
1342 }
1343 
1344 /* Set default format keys for a session. */
1345 static void
1346 format_defaults_session(struct format_tree *ft, struct session *s)
1347 {
1348 	struct session_group	*sg;
1349 
1350 	ft->s = s;
1351 
1352 	format_add(ft, "session_name", "%s", s->name);
1353 	format_add(ft, "session_windows", "%u", winlink_count(&s->windows));
1354 	format_add(ft, "session_id", "$%u", s->id);
1355 
1356 	sg = session_group_contains(s);
1357 	format_add(ft, "session_grouped", "%d", sg != NULL);
1358 	if (sg != NULL) {
1359 		format_add(ft, "session_group", "%s", sg->name);
1360 		format_add(ft, "session_group_size", "%u",
1361 		    session_group_count (sg));
1362 		format_add_cb(ft, "session_group_list",
1363 		    format_cb_session_group_list);
1364 	}
1365 
1366 	format_add_tv(ft, "session_created", &s->creation_time);
1367 	format_add_tv(ft, "session_last_attached", &s->last_attached_time);
1368 	format_add_tv(ft, "session_activity", &s->activity_time);
1369 
1370 	format_add(ft, "session_attached", "%u", s->attached);
1371 	format_add(ft, "session_many_attached", "%d", s->attached > 1);
1372 
1373 	format_add_cb(ft, "session_alerts", format_cb_session_alerts);
1374 	format_add_cb(ft, "session_stack", format_cb_session_stack);
1375 }
1376 
1377 /* Set default format keys for a client. */
1378 static void
1379 format_defaults_client(struct format_tree *ft, struct client *c)
1380 {
1381 	struct session	*s;
1382 	const char	*name;
1383 	struct tty	*tty = &c->tty;
1384 	const char	*types[] = TTY_TYPES;
1385 
1386 	if (ft->s == NULL)
1387 		ft->s = c->session;
1388 	ft->c = c;
1389 
1390 	format_add(ft, "client_name", "%s", c->name);
1391 	format_add(ft, "client_pid", "%ld", (long) c->pid);
1392 	format_add(ft, "client_height", "%u", tty->sy);
1393 	format_add(ft, "client_width", "%u", tty->sx);
1394 	format_add(ft, "client_tty", "%s", c->ttyname);
1395 	format_add(ft, "client_control_mode", "%d",
1396 		!!(c->flags & CLIENT_CONTROL));
1397 
1398 	if (tty->term_name != NULL)
1399 		format_add(ft, "client_termname", "%s", tty->term_name);
1400 	if (tty->term_name != NULL)
1401 		format_add(ft, "client_termtype", "%s", types[tty->term_type]);
1402 
1403 	format_add_tv(ft, "client_created", &c->creation_time);
1404 	format_add_tv(ft, "client_activity", &c->activity_time);
1405 
1406 	format_add(ft, "client_written", "%zu", c->written);
1407 	format_add(ft, "client_discarded", "%zu", c->discarded);
1408 
1409 	name = server_client_get_key_table(c);
1410 	if (strcmp(c->keytable->name, name) == 0)
1411 		format_add(ft, "client_prefix", "%d", 0);
1412 	else
1413 		format_add(ft, "client_prefix", "%d", 1);
1414 	format_add(ft, "client_key_table", "%s", c->keytable->name);
1415 
1416 	if (tty->flags & TTY_UTF8)
1417 		format_add(ft, "client_utf8", "%d", 1);
1418 	else
1419 		format_add(ft, "client_utf8", "%d", 0);
1420 
1421 	if (c->flags & CLIENT_READONLY)
1422 		format_add(ft, "client_readonly", "%d", 1);
1423 	else
1424 		format_add(ft, "client_readonly", "%d", 0);
1425 
1426 	s = c->session;
1427 	if (s != NULL)
1428 		format_add(ft, "client_session", "%s", s->name);
1429 	s = c->last_session;
1430 	if (s != NULL && session_alive(s))
1431 		format_add(ft, "client_last_session", "%s", s->name);
1432 }
1433 
1434 /* Set default format keys for a window. */
1435 void
1436 format_defaults_window(struct format_tree *ft, struct window *w)
1437 {
1438 	ft->w = w;
1439 
1440 	format_add_tv(ft, "window_activity", &w->activity_time);
1441 	format_add(ft, "window_id", "@%u", w->id);
1442 	format_add(ft, "window_name", "%s", w->name);
1443 	format_add(ft, "window_width", "%u", w->sx);
1444 	format_add(ft, "window_height", "%u", w->sy);
1445 	format_add_cb(ft, "window_layout", format_cb_window_layout);
1446 	format_add_cb(ft, "window_visible_layout",
1447 	    format_cb_window_visible_layout);
1448 	format_add(ft, "window_panes", "%u", window_count_panes(w));
1449 	format_add(ft, "window_zoomed_flag", "%d",
1450 	    !!(w->flags & WINDOW_ZOOMED));
1451 }
1452 
1453 /* Set default format keys for a winlink. */
1454 static void
1455 format_defaults_winlink(struct format_tree *ft, struct winlink *wl)
1456 {
1457 	struct client	*c = ft->c;
1458 	struct session	*s = wl->session;
1459 	struct window	*w = wl->window;
1460 	int		 flag;
1461 	u_int		 ox, oy, sx, sy;
1462 
1463 	if (ft->w == NULL)
1464 		ft->w = wl->window;
1465 	ft->wl = wl;
1466 
1467 	format_defaults_window(ft, w);
1468 
1469 	if (c != NULL) {
1470 		flag = tty_window_offset(&c->tty, &ox, &oy, &sx, &sy);
1471 		format_add(ft, "window_bigger", "%d", flag);
1472 		if (flag) {
1473 			format_add(ft, "window_offset_x", "%u", ox);
1474 			format_add(ft, "window_offset_y", "%u", oy);
1475 		}
1476 	}
1477 
1478 	format_add(ft, "window_index", "%d", wl->idx);
1479 	format_add_cb(ft, "window_stack_index", format_cb_window_stack_index);
1480 	format_add(ft, "window_flags", "%s", window_printable_flags(wl));
1481 	format_add(ft, "window_active", "%d", wl == s->curw);
1482 
1483 	format_add(ft, "window_bell_flag", "%d",
1484 	    !!(wl->flags & WINLINK_BELL));
1485 	format_add(ft, "window_activity_flag", "%d",
1486 	    !!(wl->flags & WINLINK_ACTIVITY));
1487 	format_add(ft, "window_silence_flag", "%d",
1488 	    !!(wl->flags & WINLINK_SILENCE));
1489 	format_add(ft, "window_last_flag", "%d",
1490 	    !!(wl == TAILQ_FIRST(&s->lastw)));
1491 	format_add(ft, "window_linked", "%d", session_is_linked(s, wl->window));
1492 }
1493 
1494 /* Set default format keys for a window pane. */
1495 void
1496 format_defaults_pane(struct format_tree *ft, struct window_pane *wp)
1497 {
1498 	struct window	*w = wp->window;
1499 	struct grid	*gd = wp->base.grid;
1500 	int  		 status = wp->status;
1501 	u_int		 idx;
1502 
1503 	if (ft->w == NULL)
1504 		ft->w = w;
1505 	ft->wp = wp;
1506 
1507 	format_add(ft, "history_size", "%u", gd->hsize);
1508 	format_add(ft, "history_limit", "%u", gd->hlimit);
1509 	format_add_cb(ft, "history_bytes", format_cb_history_bytes);
1510 
1511 	if (window_pane_index(wp, &idx) != 0)
1512 		fatalx("index not found");
1513 	format_add(ft, "pane_index", "%u", idx);
1514 
1515 	format_add(ft, "pane_width", "%u", wp->sx);
1516 	format_add(ft, "pane_height", "%u", wp->sy);
1517 	format_add(ft, "pane_title", "%s", wp->base.title);
1518 	format_add(ft, "pane_id", "%%%u", wp->id);
1519 	format_add(ft, "pane_active", "%d", wp == w->active);
1520 	format_add(ft, "pane_input_off", "%d", !!(wp->flags & PANE_INPUTOFF));
1521 	format_add(ft, "pane_pipe", "%d", wp->pipe_fd != -1);
1522 
1523 	if ((wp->flags & PANE_STATUSREADY) && WIFEXITED(status))
1524 		format_add(ft, "pane_dead_status", "%d", WEXITSTATUS(status));
1525 	format_add(ft, "pane_dead", "%d", wp->fd == -1);
1526 
1527 	format_add(ft, "pane_left", "%u", wp->xoff);
1528 	format_add(ft, "pane_top", "%u", wp->yoff);
1529 	format_add(ft, "pane_right", "%u", wp->xoff + wp->sx - 1);
1530 	format_add(ft, "pane_bottom", "%u", wp->yoff + wp->sy - 1);
1531 	format_add(ft, "pane_at_left", "%d", wp->xoff == 0);
1532 	format_add(ft, "pane_at_top", "%d", wp->yoff == 0);
1533 	format_add(ft, "pane_at_right", "%d", wp->xoff + wp->sx == w->sx);
1534 	format_add(ft, "pane_at_bottom", "%d", wp->yoff + wp->sy == w->sy);
1535 
1536 	format_add(ft, "pane_in_mode", "%d", wp->screen != &wp->base);
1537 	if (wp->mode != NULL)
1538 		format_add(ft, "pane_mode", "%s", wp->mode->name);
1539 
1540 	format_add(ft, "pane_synchronized", "%d",
1541 	    !!options_get_number(w->options, "synchronize-panes"));
1542 	if (wp->searchstr != NULL)
1543 		format_add(ft, "pane_search_string", "%s", wp->searchstr);
1544 
1545 	format_add(ft, "pane_tty", "%s", wp->tty);
1546 	format_add(ft, "pane_pid", "%ld", (long) wp->pid);
1547 	format_add_cb(ft, "pane_start_command", format_cb_start_command);
1548 	format_add_cb(ft, "pane_current_command", format_cb_current_command);
1549 
1550 	format_add(ft, "cursor_x", "%u", wp->base.cx);
1551 	format_add(ft, "cursor_y", "%u", wp->base.cy);
1552 	format_add(ft, "scroll_region_upper", "%u", wp->base.rupper);
1553 	format_add(ft, "scroll_region_lower", "%u", wp->base.rlower);
1554 
1555 	window_copy_add_formats(wp, ft);
1556 
1557 	format_add(ft, "alternate_on", "%d", wp->saved_grid ? 1 : 0);
1558 	format_add(ft, "alternate_saved_x", "%u", wp->saved_cx);
1559 	format_add(ft, "alternate_saved_y", "%u", wp->saved_cy);
1560 
1561 	format_add(ft, "cursor_flag", "%d",
1562 	    !!(wp->base.mode & MODE_CURSOR));
1563 	format_add(ft, "insert_flag", "%d",
1564 	    !!(wp->base.mode & MODE_INSERT));
1565 	format_add(ft, "keypad_cursor_flag", "%d",
1566 	    !!(wp->base.mode & MODE_KCURSOR));
1567 	format_add(ft, "keypad_flag", "%d",
1568 	    !!(wp->base.mode & MODE_KKEYPAD));
1569 	format_add(ft, "wrap_flag", "%d",
1570 	    !!(wp->base.mode & MODE_WRAP));
1571 
1572 	format_add(ft, "mouse_any_flag", "%d",
1573 	    !!(wp->base.mode & ALL_MOUSE_MODES));
1574 	format_add(ft, "mouse_standard_flag", "%d",
1575 	    !!(wp->base.mode & MODE_MOUSE_STANDARD));
1576 	format_add(ft, "mouse_button_flag", "%d",
1577 	    !!(wp->base.mode & MODE_MOUSE_BUTTON));
1578 	format_add(ft, "mouse_all_flag", "%d",
1579 	    !!(wp->base.mode & MODE_MOUSE_ALL));
1580 
1581 	format_add_cb(ft, "pane_tabs", format_cb_pane_tabs);
1582 }
1583 
1584 /* Set default format keys for paste buffer. */
1585 void
1586 format_defaults_paste_buffer(struct format_tree *ft, struct paste_buffer *pb)
1587 {
1588 	struct timeval	 tv;
1589 	size_t		 size;
1590 	char		*s;
1591 
1592 	timerclear(&tv);
1593 	tv.tv_sec = paste_buffer_created(pb);
1594 	paste_buffer_data(pb, &size);
1595 
1596 	format_add(ft, "buffer_size", "%zu", size);
1597 	format_add(ft, "buffer_name", "%s", paste_buffer_name(pb));
1598 	format_add_tv(ft, "buffer_created", &tv);
1599 
1600 	s = paste_make_sample(pb);
1601 	format_add(ft, "buffer_sample", "%s", s);
1602 	free(s);
1603 }
1604