xref: /openbsd-src/usr.bin/tmux/format.c (revision e5157e49389faebcb42b7237d55fbf096d9c2523)
1 /* $OpenBSD: format.c,v 1.52 2014/11/08 12:50:38 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2011 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 
21 #include <ctype.h>
22 #include <errno.h>
23 #include <netdb.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 
32 /*
33  * Build a list of key-value pairs and use them to expand #{key} entries in a
34  * string.
35  */
36 
37 int	 format_replace(struct format_tree *, const char *, size_t, char **,
38 	     size_t *, size_t *);
39 char	*format_get_command(struct window_pane *);
40 void	 format_window_pane_tabs(struct format_tree *, struct window_pane *);
41 
42 /* Format key-value replacement entry. */
43 RB_GENERATE(format_tree, format_entry, entry, format_cmp);
44 
45 /* Format tree comparison function. */
46 int
47 format_cmp(struct format_entry *fe1, struct format_entry *fe2)
48 {
49 	return (strcmp(fe1->key, fe2->key));
50 }
51 
52 /* Single-character uppercase aliases. */
53 const char *format_upper[] = {
54 	NULL,		/* A */
55 	NULL,		/* B */
56 	NULL,		/* C */
57 	"pane_id",	/* D */
58 	NULL,		/* E */
59 	"window_flags",	/* F */
60 	NULL,		/* G */
61 	"host",		/* H */
62 	"window_index",	/* I */
63 	NULL,		/* J */
64 	NULL,		/* K */
65 	NULL,		/* L */
66 	NULL,		/* M */
67 	NULL,		/* N */
68 	NULL,		/* O */
69 	"pane_index",	/* P */
70 	NULL,		/* Q */
71 	NULL,		/* R */
72 	"session_name",	/* S */
73 	"pane_title",	/* T */
74 	NULL,		/* U */
75 	NULL,		/* V */
76 	"window_name",	/* W */
77 	NULL,		/* X */
78 	NULL,		/* Y */
79 	NULL 		/* Z */
80 };
81 
82 /* Single-character lowercase aliases. */
83 const char *format_lower[] = {
84 	NULL,		/* a */
85 	NULL,		/* b */
86 	NULL,		/* c */
87 	NULL,		/* d */
88 	NULL,		/* e */
89 	NULL,		/* f */
90 	NULL,		/* g */
91 	"host_short",	/* h */
92 	NULL,		/* i */
93 	NULL,		/* j */
94 	NULL,		/* k */
95 	NULL,		/* l */
96 	NULL,		/* m */
97 	NULL,		/* n */
98 	NULL,		/* o */
99 	NULL,		/* p */
100 	NULL,		/* q */
101 	NULL,		/* r */
102 	NULL,		/* s */
103 	NULL,		/* t */
104 	NULL,		/* u */
105 	NULL,		/* v */
106 	NULL,		/* w */
107 	NULL,		/* x */
108 	NULL,		/* y */
109 	NULL		/* z */
110 };
111 
112 /* Create a new tree. */
113 struct format_tree *
114 format_create(void)
115 {
116 	struct format_tree	*ft;
117 	char			 host[MAXHOSTNAMELEN], *ptr;
118 
119 	ft = xmalloc(sizeof *ft);
120 	RB_INIT(ft);
121 
122 	if (gethostname(host, sizeof host) == 0) {
123 		format_add(ft, "host", "%s", host);
124 		if ((ptr = strchr(host, '.')) != NULL)
125 			*ptr = '\0';
126 		format_add(ft, "host_short", "%s", host);
127 	}
128 
129 	return (ft);
130 }
131 
132 /* Free a tree. */
133 void
134 format_free(struct format_tree *ft)
135 {
136 	struct format_entry	*fe, *fe_next;
137 
138 	fe_next = RB_MIN(format_tree, ft);
139 	while (fe_next != NULL) {
140 		fe = fe_next;
141 		fe_next = RB_NEXT(format_tree, ft, fe);
142 
143 		RB_REMOVE(format_tree, ft, fe);
144 		free(fe->value);
145 		free(fe->key);
146 		free(fe);
147 	}
148 
149 	free(ft);
150 }
151 
152 /* Add a key-value pair. */
153 void
154 format_add(struct format_tree *ft, const char *key, const char *fmt, ...)
155 {
156 	struct format_entry	*fe;
157 	struct format_entry	*fe_now;
158 	va_list			 ap;
159 
160 	fe = xmalloc(sizeof *fe);
161 	fe->key = xstrdup(key);
162 
163 	va_start(ap, fmt);
164 	xvasprintf(&fe->value, fmt, ap);
165 	va_end(ap);
166 
167 	fe_now = RB_INSERT(format_tree, ft, fe);
168 	if (fe_now != NULL) {
169 		free(fe_now->value);
170 		fe_now->value = fe->value;
171 		free(fe->key);
172 		free(fe);
173 	}
174 }
175 
176 /* Find a format entry. */
177 const char *
178 format_find(struct format_tree *ft, const char *key)
179 {
180 	struct format_entry	*fe, fe_find;
181 
182 	fe_find.key = (char *) key;
183 	fe = RB_FIND(format_tree, ft, &fe_find);
184 	if (fe == NULL)
185 		return (NULL);
186 	return (fe->value);
187 }
188 
189 /*
190  * Replace a key/value pair in buffer. #{blah} is expanded directly,
191  * #{?blah,a,b} is replace with a if blah exists and is nonzero else b.
192  */
193 int
194 format_replace(struct format_tree *ft, const char *key, size_t keylen,
195     char **buf, size_t *len, size_t *off)
196 {
197 	char		*copy, *copy0, *endptr, *ptr, *saved, *trimmed;
198 	const char	*value;
199 	size_t		 valuelen;
200 	u_long		 limit = 0;
201 
202 	/* Make a copy of the key. */
203 	copy0 = copy = xmalloc(keylen + 1);
204 	memcpy(copy, key, keylen);
205 	copy[keylen] = '\0';
206 
207 	/* Is there a length limit or whatnot? */
208 	if (!islower((u_char) *copy) && *copy != '?') {
209 		while (*copy != ':' && *copy != '\0') {
210 			switch (*copy) {
211 			case '=':
212 				errno = 0;
213 				limit = strtoul(copy + 1, &endptr, 10);
214 				if (errno == ERANGE && limit == ULONG_MAX)
215 					goto fail;
216 				copy = endptr;
217 				break;
218 			default:
219 				copy++;
220 				break;
221 			}
222 		}
223 		if (*copy != ':')
224 			goto fail;
225 		copy++;
226 	}
227 
228 	/*
229 	 * Is this a conditional? If so, check it exists and extract either the
230 	 * first or second element. If not, look up the key directly.
231 	 */
232 	if (*copy == '?') {
233 		ptr = strchr(copy, ',');
234 		if (ptr == NULL)
235 			goto fail;
236 		*ptr = '\0';
237 
238 		value = format_find(ft, copy + 1);
239 		if (value != NULL && *value != '\0' &&
240 		    (value[0] != '0' || value[1] != '\0')) {
241 			value = ptr + 1;
242 			ptr = strchr(value, ',');
243 			if (ptr == NULL)
244 				goto fail;
245 			*ptr = '\0';
246 		} else {
247 			ptr = strchr(ptr + 1, ',');
248 			if (ptr == NULL)
249 				goto fail;
250 			value = ptr + 1;
251 		}
252 		saved = format_expand(ft, value);
253 		value = saved;
254 	} else {
255 		value = format_find(ft, copy);
256 		if (value == NULL)
257 			value = "";
258 		saved = NULL;
259 	}
260 
261 	/* Truncate the value if needed. */
262 	if (limit != 0) {
263 		value = trimmed = utf8_trimcstr(value, limit);
264 		free(saved);
265 		saved = trimmed;
266 	}
267 	valuelen = strlen(value);
268 
269 	/* Expand the buffer and copy in the value. */
270 	while (*len - *off < valuelen + 1) {
271 		*buf = xreallocarray(*buf, 2, *len);
272 		*len *= 2;
273 	}
274 	memcpy(*buf + *off, value, valuelen);
275 	*off += valuelen;
276 
277 	free(saved);
278 	free(copy0);
279 	return (0);
280 
281 fail:
282 	free(copy0);
283 	return (-1);
284 }
285 
286 /* Expand keys in a template. */
287 char *
288 format_expand(struct format_tree *ft, const char *fmt)
289 {
290 	char		*buf;
291 	const char	*ptr, *s;
292 	size_t		 off, len, n;
293 	int     	 ch, brackets;
294 
295 	len = 64;
296 	buf = xmalloc(len);
297 	off = 0;
298 
299 	while (*fmt != '\0') {
300 		if (*fmt != '#') {
301 			while (len - off < 2) {
302 				buf = xreallocarray(buf, 2, len);
303 				len *= 2;
304 			}
305 			buf[off++] = *fmt++;
306 			continue;
307 		}
308 		fmt++;
309 
310 		ch = (u_char) *fmt++;
311 		switch (ch) {
312 		case '{':
313 			brackets = 1;
314 			for (ptr = fmt; *ptr != '\0'; ptr++) {
315 				if (*ptr == '{')
316 					brackets++;
317 				if (*ptr == '}' && --brackets == 0)
318 					break;
319 			}
320 			if (*ptr != '}' || brackets != 0)
321 				break;
322 			n = ptr - fmt;
323 
324 			if (format_replace(ft, fmt, n, &buf, &len, &off) != 0)
325 				break;
326 			fmt += n + 1;
327 			continue;
328 		case '#':
329 			while (len - off < 2) {
330 				buf = xreallocarray(buf, 2, len);
331 				len *= 2;
332 			}
333 			buf[off++] = '#';
334 			continue;
335 		default:
336 			s = NULL;
337 			if (ch >= 'A' && ch <= 'Z')
338 				s = format_upper[ch - 'A'];
339 			else if (ch >= 'a' && ch <= 'z')
340 				s = format_lower[ch - 'a'];
341 			if (s == NULL) {
342 				while (len - off < 3) {
343 					buf = xreallocarray(buf, 2, len);
344 					len *= 2;
345 				}
346 				buf[off++] = '#';
347 				buf[off++] = ch;
348 				continue;
349 			}
350 			n = strlen(s);
351 			if (format_replace(ft, s, n, &buf, &len, &off) != 0)
352 				break;
353 			continue;
354 		}
355 
356 		break;
357 	}
358 	buf[off] = '\0';
359 
360 	return (buf);
361 }
362 
363 /* Get command name for format. */
364 char *
365 format_get_command(struct window_pane *wp)
366 {
367 	char	*cmd, *out;
368 
369 	cmd = get_proc_name(wp->fd, wp->tty);
370 	if (cmd == NULL || *cmd == '\0') {
371 		free(cmd);
372 		cmd = cmd_stringify_argv(wp->argc, wp->argv);
373 		if (cmd == NULL || *cmd == '\0') {
374 			free(cmd);
375 			cmd = xstrdup(wp->shell);
376 		}
377 	}
378 	out = parse_window_name(cmd);
379 	free(cmd);
380 	return (out);
381 }
382 
383 /* Set default format keys for a session. */
384 void
385 format_session(struct format_tree *ft, struct session *s)
386 {
387 	struct session_group	*sg;
388 	char			*tim;
389 	time_t			 t;
390 
391 	format_add(ft, "session_name", "%s", s->name);
392 	format_add(ft, "session_windows", "%u", winlink_count(&s->windows));
393 	format_add(ft, "session_width", "%u", s->sx);
394 	format_add(ft, "session_height", "%u", s->sy);
395 	format_add(ft, "session_id", "$%u", s->id);
396 
397 	sg = session_group_find(s);
398 	format_add(ft, "session_grouped", "%d", sg != NULL);
399 	if (sg != NULL)
400 		format_add(ft, "session_group", "%u", session_group_index(sg));
401 
402 	t = s->creation_time.tv_sec;
403 	format_add(ft, "session_created", "%lld", (long long) t);
404 	tim = ctime(&t);
405 	*strchr(tim, '\n') = '\0';
406 	format_add(ft, "session_created_string", "%s", tim);
407 
408 	format_add(ft, "session_attached", "%u", s->attached);
409 	format_add(ft, "session_many_attached", "%u", s->attached > 1);
410 }
411 
412 /* Set default format keys for a client. */
413 void
414 format_client(struct format_tree *ft, struct client *c)
415 {
416 	char		*tim;
417 	time_t		 t;
418 	struct session	*s;
419 
420 	format_add(ft, "client_height", "%u", c->tty.sy);
421 	format_add(ft, "client_width", "%u", c->tty.sx);
422 	if (c->tty.path != NULL)
423 		format_add(ft, "client_tty", "%s", c->tty.path);
424 	if (c->tty.termname != NULL)
425 		format_add(ft, "client_termname", "%s", c->tty.termname);
426 
427 	t = c->creation_time.tv_sec;
428 	format_add(ft, "client_created", "%lld", (long long) t);
429 	tim = ctime(&t);
430 	*strchr(tim, '\n') = '\0';
431 	format_add(ft, "client_created_string", "%s", tim);
432 
433 	t = c->activity_time.tv_sec;
434 	format_add(ft, "client_activity", "%lld", (long long) t);
435 	tim = ctime(&t);
436 	*strchr(tim, '\n') = '\0';
437 	format_add(ft, "client_activity_string", "%s", tim);
438 
439 	format_add(ft, "client_prefix", "%d", !!(c->flags & CLIENT_PREFIX));
440 
441 	if (c->tty.flags & TTY_UTF8)
442 		format_add(ft, "client_utf8", "%d", 1);
443 	else
444 		format_add(ft, "client_utf8", "%d", 0);
445 
446 	if (c->flags & CLIENT_READONLY)
447 		format_add(ft, "client_readonly", "%d", 1);
448 	else
449 		format_add(ft, "client_readonly", "%d", 0);
450 
451 	s = c->session;
452 	if (s != NULL)
453 		format_add(ft, "client_session", "%s", s->name);
454 	s = c->last_session;
455 	if (s != NULL && session_alive(s))
456 		format_add(ft, "client_last_session", "%s", s->name);
457 }
458 
459 /* Set default format keys for a window. */
460 void
461 format_window(struct format_tree *ft, struct window *w)
462 {
463 	char	*layout;
464 
465 	layout = layout_dump(w);
466 
467 	format_add(ft, "window_id", "@%u", w->id);
468 	format_add(ft, "window_name", "%s", w->name);
469 	format_add(ft, "window_width", "%u", w->sx);
470 	format_add(ft, "window_height", "%u", w->sy);
471 	format_add(ft, "window_layout", "%s", layout);
472 	format_add(ft, "window_panes", "%u", window_count_panes(w));
473 
474 	free(layout);
475 }
476 
477 /* Set default format keys for a winlink. */
478 void
479 format_winlink(struct format_tree *ft, struct session *s, struct winlink *wl)
480 {
481 	struct window	*w = wl->window;
482 	char		*flags;
483 
484 	flags = window_printable_flags(s, wl);
485 
486 	format_window(ft, w);
487 
488 	format_add(ft, "window_index", "%d", wl->idx);
489 	format_add(ft, "window_flags", "%s", flags);
490 	format_add(ft, "window_active", "%d", wl == s->curw);
491 
492 	format_add(ft, "window_bell_flag", "%u",
493 	    !!(wl->flags & WINLINK_BELL));
494 	format_add(ft, "window_activity_flag", "%u",
495 	    !!(wl->flags & WINLINK_ACTIVITY));
496 	format_add(ft, "window_silence_flag", "%u",
497 	    !!(wl->flags & WINLINK_SILENCE));
498 	format_add(ft, "window_last_flag", "%u",
499 	    !!(wl == TAILQ_FIRST(&s->lastw)));
500 	format_add(ft, "window_zoomed_flag", "%u",
501 	    !!(wl->flags & WINDOW_ZOOMED));
502 
503 	free(flags);
504 }
505 
506 /* Add window pane tabs. */
507 void
508 format_window_pane_tabs(struct format_tree *ft, struct window_pane *wp)
509 {
510 	struct evbuffer	*buffer;
511 	u_int		 i;
512 
513 	buffer = evbuffer_new();
514 	for (i = 0; i < wp->base.grid->sx; i++) {
515 		if (!bit_test(wp->base.tabs, i))
516 			continue;
517 
518 		if (EVBUFFER_LENGTH(buffer) > 0)
519 			evbuffer_add(buffer, ",", 1);
520 		evbuffer_add_printf(buffer, "%d", i);
521 	}
522 
523 	format_add(ft, "pane_tabs", "%.*s", (int) EVBUFFER_LENGTH(buffer),
524 	    EVBUFFER_DATA(buffer));
525 	evbuffer_free(buffer);
526 }
527 
528 /* Set default format keys for a window pane. */
529 void
530 format_window_pane(struct format_tree *ft, struct window_pane *wp)
531 {
532 	struct grid		*gd = wp->base.grid;
533 	struct grid_line	*gl;
534 	unsigned long long	 size;
535 	u_int			 i, idx;
536 	char			*cmd;
537 
538 	size = 0;
539 	for (i = 0; i < gd->hsize; i++) {
540 		gl = &gd->linedata[i];
541 		size += gl->cellsize * sizeof *gl->celldata;
542 	}
543 	size += gd->hsize * sizeof *gd->linedata;
544 	format_add(ft, "history_size", "%u", gd->hsize);
545 	format_add(ft, "history_limit", "%u", gd->hlimit);
546 	format_add(ft, "history_bytes", "%llu", size);
547 
548 	if (window_pane_index(wp, &idx) != 0)
549 		fatalx("index not found");
550 	format_add(ft, "pane_index", "%u", idx);
551 
552 	format_add(ft, "pane_width", "%u", wp->sx);
553 	format_add(ft, "pane_height", "%u", wp->sy);
554 	format_add(ft, "pane_title", "%s", wp->base.title);
555 	format_add(ft, "pane_id", "%%%u", wp->id);
556 	format_add(ft, "pane_active", "%d", wp == wp->window->active);
557 	format_add(ft, "pane_dead", "%d", wp->fd == -1);
558 	format_add(ft, "pane_input_off", "%d", !!(wp->flags & PANE_INPUTOFF));
559 
560 	if (window_pane_visible(wp)) {
561 		format_add(ft, "pane_left", "%u", wp->xoff);
562 		format_add(ft, "pane_top", "%u", wp->yoff);
563 		format_add(ft, "pane_right", "%u", wp->xoff + wp->sx - 1);
564 		format_add(ft, "pane_bottom", "%u", wp->yoff + wp->sy - 1);
565 	}
566 
567 	format_add(ft, "pane_in_mode", "%d", wp->screen != &wp->base);
568 	format_add(ft, "pane_synchronized", "%d",
569 	    !!options_get_number(&wp->window->options, "synchronize-panes"));
570 
571 	if (wp->tty != NULL)
572 		format_add(ft, "pane_tty", "%s", wp->tty);
573 	format_add(ft, "pane_pid", "%ld", (long) wp->pid);
574 	if ((cmd = cmd_stringify_argv(wp->argc, wp->argv)) != NULL) {
575 		format_add(ft, "pane_start_command", "%s", cmd);
576 		free(cmd);
577 	}
578 	if ((cmd = format_get_command(wp)) != NULL) {
579 		format_add(ft, "pane_current_command", "%s", cmd);
580 		free(cmd);
581 	}
582 
583 	format_add(ft, "cursor_x", "%d", wp->base.cx);
584 	format_add(ft, "cursor_y", "%d", wp->base.cy);
585 	format_add(ft, "scroll_region_upper", "%d", wp->base.rupper);
586 	format_add(ft, "scroll_region_lower", "%d", wp->base.rlower);
587 	format_add(ft, "saved_cursor_x", "%d", wp->ictx.old_cx);
588 	format_add(ft, "saved_cursor_y", "%d", wp->ictx.old_cy);
589 
590 	format_add(ft, "alternate_on", "%d", wp->saved_grid ? 1 : 0);
591 	format_add(ft, "alternate_saved_x", "%d", wp->saved_cx);
592 	format_add(ft, "alternate_saved_y", "%d", wp->saved_cy);
593 
594 	format_add(ft, "cursor_flag", "%d",
595 	    !!(wp->base.mode & MODE_CURSOR));
596 	format_add(ft, "insert_flag", "%d",
597 	    !!(wp->base.mode & MODE_INSERT));
598 	format_add(ft, "keypad_cursor_flag", "%d",
599 	    !!(wp->base.mode & MODE_KCURSOR));
600 	format_add(ft, "keypad_flag", "%d",
601 	    !!(wp->base.mode & MODE_KKEYPAD));
602 	format_add(ft, "wrap_flag", "%d",
603 	    !!(wp->base.mode & MODE_WRAP));
604 
605 	format_add(ft, "mouse_standard_flag", "%d",
606 	    !!(wp->base.mode & MODE_MOUSE_STANDARD));
607 	format_add(ft, "mouse_button_flag", "%d",
608 	    !!(wp->base.mode & MODE_MOUSE_BUTTON));
609 	format_add(ft, "mouse_utf8_flag", "%d",
610 	    !!(wp->base.mode & MODE_MOUSE_UTF8));
611 
612 	format_window_pane_tabs(ft, wp);
613 }
614 
615 /* Set default format keys for paste buffer. */
616 void
617 format_paste_buffer(struct format_tree *ft, struct paste_buffer *pb,
618     int utf8flag)
619 {
620 	char	*s;
621 
622 	format_add(ft, "buffer_size", "%zu", pb->size);
623 	format_add(ft, "buffer_name", "%s", pb->name);
624 
625 	s = paste_make_sample(pb, utf8flag);
626 	format_add(ft, "buffer_sample", "%s", s);
627 	free(s);
628 }
629