xref: /openbsd-src/usr.bin/tmux/cmd-find.c (revision c0dd97bfcad3dab6c31ec12b9de1274fd2d2f993)
1 /* $OpenBSD: cmd-find.c,v 1.57 2017/08/30 10:33:57 nicm Exp $ */
2 
3 /*
4  * Copyright (c) 2015 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 
21 #include <fnmatch.h>
22 #include <limits.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <paths.h>
26 #include <unistd.h>
27 
28 #include "tmux.h"
29 
30 static int	cmd_find_session_better(struct session *, struct session *,
31 		    int);
32 static struct session *cmd_find_best_session(struct session **, u_int, int);
33 static int	cmd_find_best_session_with_window(struct cmd_find_state *);
34 static int	cmd_find_best_winlink_with_window(struct cmd_find_state *);
35 
36 static const char *cmd_find_map_table(const char *[][2], const char *);
37 
38 static int	cmd_find_get_session(struct cmd_find_state *, const char *);
39 static int	cmd_find_get_window(struct cmd_find_state *, const char *, int);
40 static int	cmd_find_get_window_with_session(struct cmd_find_state *,
41 		    const char *);
42 static int	cmd_find_get_pane(struct cmd_find_state *, const char *, int);
43 static int	cmd_find_get_pane_with_session(struct cmd_find_state *,
44 		    const char *);
45 static int	cmd_find_get_pane_with_window(struct cmd_find_state *,
46 		    const char *);
47 
48 static const char *cmd_find_session_table[][2] = {
49 	{ NULL, NULL }
50 };
51 static const char *cmd_find_window_table[][2] = {
52 	{ "{start}", "^" },
53 	{ "{last}", "!" },
54 	{ "{end}", "$" },
55 	{ "{next}", "+" },
56 	{ "{previous}", "-" },
57 	{ NULL, NULL }
58 };
59 static const char *cmd_find_pane_table[][2] = {
60 	{ "{last}", "!" },
61 	{ "{next}", "+" },
62 	{ "{previous}", "-" },
63 	{ "{top}", "top" },
64 	{ "{bottom}", "bottom" },
65 	{ "{left}", "left" },
66 	{ "{right}", "right" },
67 	{ "{top-left}", "top-left" },
68 	{ "{top-right}", "top-right" },
69 	{ "{bottom-left}", "bottom-left" },
70 	{ "{bottom-right}", "bottom-right" },
71 	{ "{up-of}", "{up-of}" },
72 	{ "{down-of}", "{down-of}" },
73 	{ "{left-of}", "{left-of}" },
74 	{ "{right-of}", "{right-of}" },
75 	{ NULL, NULL }
76 };
77 
78 /* Get session from TMUX if present. */
79 static struct session *
80 cmd_find_try_TMUX(struct client *c)
81 {
82 	struct environ_entry	*envent;
83 	char			 tmp[256];
84 	long long		 pid;
85 	u_int			 session;
86 
87 	envent = environ_find(c->environ, "TMUX");
88 	if (envent == NULL)
89 		return (NULL);
90 
91 	if (sscanf(envent->value, "%255[^,],%lld,%d", tmp, &pid, &session) != 3)
92 		return (NULL);
93 	if (pid != getpid())
94 		return (NULL);
95 	log_debug("client %p TMUX %s (session @%u)", c, envent->value, session);
96 	return (session_find_by_id(session));
97 }
98 
99 /* Find pane containing client if any. */
100 static struct window_pane *
101 cmd_find_inside_pane(struct client *c)
102 {
103 	struct window_pane	*wp;
104 
105 	if (c == NULL)
106 		return (NULL);
107 
108 	RB_FOREACH(wp, window_pane_tree, &all_window_panes) {
109 		if (strcmp(wp->tty, c->ttyname) == 0)
110 			break;
111 	}
112 	return (wp);
113 }
114 
115 /* Is this client better? */
116 static int
117 cmd_find_client_better(struct client *c, struct client *than)
118 {
119 	if (than == NULL)
120 		return (1);
121 	return (timercmp(&c->activity_time, &than->activity_time, >));
122 }
123 
124 /* Find best client for session. */
125 static struct client *
126 cmd_find_best_client(struct session *s)
127 {
128 	struct client	*c_loop, *c;
129 
130 	if (s->flags & SESSION_UNATTACHED)
131 		s = NULL;
132 
133 	c = NULL;
134 	TAILQ_FOREACH(c_loop, &clients, entry) {
135 		if (c_loop->session == NULL)
136 			continue;
137 		if (s != NULL && c_loop->session != s)
138 			continue;
139 		if (cmd_find_client_better(c_loop, c))
140 			c = c_loop;
141 	}
142 	return (c);
143 }
144 
145 /* Is this session better? */
146 static int
147 cmd_find_session_better(struct session *s, struct session *than, int flags)
148 {
149 	int	attached;
150 
151 	if (than == NULL)
152 		return (1);
153 	if (flags & CMD_FIND_PREFER_UNATTACHED) {
154 		attached = (~than->flags & SESSION_UNATTACHED);
155 		if (attached && (s->flags & SESSION_UNATTACHED))
156 			return (1);
157 		else if (!attached && (~s->flags & SESSION_UNATTACHED))
158 			return (0);
159 	}
160 	return (timercmp(&s->activity_time, &than->activity_time, >));
161 }
162 
163 /* Find best session from a list, or all if list is NULL. */
164 static struct session *
165 cmd_find_best_session(struct session **slist, u_int ssize, int flags)
166 {
167 	struct session	 *s_loop, *s;
168 	u_int		  i;
169 
170 	s = NULL;
171 	if (slist != NULL) {
172 		for (i = 0; i < ssize; i++) {
173 			if (cmd_find_session_better(slist[i], s, flags))
174 				s = slist[i];
175 		}
176 	} else {
177 		RB_FOREACH(s_loop, sessions, &sessions) {
178 			if (cmd_find_session_better(s_loop, s, flags))
179 				s = s_loop;
180 		}
181 	}
182 	return (s);
183 }
184 
185 /* Find best session and winlink for window. */
186 static int
187 cmd_find_best_session_with_window(struct cmd_find_state *fs)
188 {
189 	struct session	**slist = NULL;
190 	u_int		  ssize;
191 	struct session	 *s;
192 
193 	ssize = 0;
194 	RB_FOREACH(s, sessions, &sessions) {
195 		if (!session_has(s, fs->w))
196 			continue;
197 		slist = xreallocarray(slist, ssize + 1, sizeof *slist);
198 		slist[ssize++] = s;
199 	}
200 	if (ssize == 0)
201 		goto fail;
202 	fs->s = cmd_find_best_session(slist, ssize, fs->flags);
203 	if (fs->s == NULL)
204 		goto fail;
205 	free(slist);
206 	return (cmd_find_best_winlink_with_window(fs));
207 
208 fail:
209 	free(slist);
210 	return (-1);
211 }
212 
213 /*
214  * Find the best winlink for a window (the current if it contains the pane,
215  * otherwise the first).
216  */
217 static int
218 cmd_find_best_winlink_with_window(struct cmd_find_state *fs)
219 {
220 	struct winlink	 *wl, *wl_loop;
221 
222 	wl = NULL;
223 	if (fs->s->curw != NULL && fs->s->curw->window == fs->w)
224 		wl = fs->s->curw;
225 	else {
226 		RB_FOREACH(wl_loop, winlinks, &fs->s->windows) {
227 			if (wl_loop->window == fs->w) {
228 				wl = wl_loop;
229 				break;
230 			}
231 		}
232 	}
233 	if (wl == NULL)
234 		return (-1);
235 	fs->wl = wl;
236 	fs->idx = fs->wl->idx;
237 	return (0);
238 }
239 
240 /* Maps string in table. */
241 static const char *
242 cmd_find_map_table(const char *table[][2], const char *s)
243 {
244 	u_int	i;
245 
246 	for (i = 0; table[i][0] != NULL; i++) {
247 		if (strcmp(s, table[i][0]) == 0)
248 			return (table[i][1]);
249 	}
250 	return (s);
251 }
252 
253 /* Find session from string. Fills in s. */
254 static int
255 cmd_find_get_session(struct cmd_find_state *fs, const char *session)
256 {
257 	struct session	*s, *s_loop;
258 	struct client	*c;
259 
260 	log_debug("%s: %s", __func__, session);
261 
262 	/* Check for session ids starting with $. */
263 	if (*session == '$') {
264 		fs->s = session_find_by_id_str(session);
265 		if (fs->s == NULL)
266 			return (-1);
267 		return (0);
268 	}
269 
270 	/* Look for exactly this session. */
271 	fs->s = session_find(session);
272 	if (fs->s != NULL)
273 		return (0);
274 
275 	/* Look for as a client. */
276 	c = cmd_find_client(NULL, session, 1);
277 	if (c != NULL && c->session != NULL) {
278 		fs->s = c->session;
279 		return (0);
280 	}
281 
282 	/* Stop now if exact only. */
283 	if (fs->flags & CMD_FIND_EXACT_SESSION)
284 		return (-1);
285 
286 	/* Otherwise look for prefix. */
287 	s = NULL;
288 	RB_FOREACH(s_loop, sessions, &sessions) {
289 		if (strncmp(session, s_loop->name, strlen(session)) == 0) {
290 			if (s != NULL)
291 				return (-1);
292 			s = s_loop;
293 		}
294 	}
295 	if (s != NULL) {
296 		fs->s = s;
297 		return (0);
298 	}
299 
300 	/* Then as a pattern. */
301 	s = NULL;
302 	RB_FOREACH(s_loop, sessions, &sessions) {
303 		if (fnmatch(session, s_loop->name, 0) == 0) {
304 			if (s != NULL)
305 				return (-1);
306 			s = s_loop;
307 		}
308 	}
309 	if (s != NULL) {
310 		fs->s = s;
311 		return (0);
312 	}
313 
314 	return (-1);
315 }
316 
317 /* Find window from string. Fills in s, wl, w. */
318 static int
319 cmd_find_get_window(struct cmd_find_state *fs, const char *window, int only)
320 {
321 	log_debug("%s: %s", __func__, window);
322 
323 	/* Check for window ids starting with @. */
324 	if (*window == '@') {
325 		fs->w = window_find_by_id_str(window);
326 		if (fs->w == NULL)
327 			return (-1);
328 		return (cmd_find_best_session_with_window(fs));
329 	}
330 
331 	/* Not a window id, so use the current session. */
332 	fs->s = fs->current->s;
333 
334 	/* We now only need to find the winlink in this session. */
335 	if (cmd_find_get_window_with_session(fs, window) == 0)
336 		return (0);
337 
338 	/* Otherwise try as a session itself. */
339 	if (!only && cmd_find_get_session(fs, window) == 0) {
340 		fs->wl = fs->s->curw;
341 		fs->w = fs->wl->window;
342 		if (~fs->flags & CMD_FIND_WINDOW_INDEX)
343 			fs->idx = fs->wl->idx;
344 		return (0);
345 	}
346 
347 	return (-1);
348 }
349 
350 /*
351  * Find window from string, assuming it is in given session. Needs s, fills in
352  * wl and w.
353  */
354 static int
355 cmd_find_get_window_with_session(struct cmd_find_state *fs, const char *window)
356 {
357 	struct winlink	*wl;
358 	const char	*errstr;
359 	int		 idx, n, exact;
360 	struct session	*s;
361 
362 	log_debug("%s: %s", __func__, window);
363 	exact = (fs->flags & CMD_FIND_EXACT_WINDOW);
364 
365 	/*
366 	 * Start with the current window as the default. So if only an index is
367 	 * found, the window will be the current.
368 	 */
369 	fs->wl = fs->s->curw;
370 	fs->w = fs->wl->window;
371 
372 	/* Check for window ids starting with @. */
373 	if (*window == '@') {
374 		fs->w = window_find_by_id_str(window);
375 		if (fs->w == NULL || !session_has(fs->s, fs->w))
376 			return (-1);
377 		return (cmd_find_best_winlink_with_window(fs));
378 	}
379 
380 	/* Try as an offset. */
381 	if (!exact && (window[0] == '+' || window[0] == '-')) {
382 		if (window[1] != '\0')
383 			n = strtonum(window + 1, 1, INT_MAX, NULL);
384 		else
385 			n = 1;
386 		s = fs->s;
387 		if (fs->flags & CMD_FIND_WINDOW_INDEX) {
388 			if (window[0] == '+') {
389 				if (INT_MAX - s->curw->idx < n)
390 					return (-1);
391 				fs->idx = s->curw->idx + n;
392 			} else {
393 				if (n < s->curw->idx)
394 					return (-1);
395 				fs->idx = s->curw->idx - n;
396 			}
397 			return (0);
398 		}
399 		if (window[0] == '+')
400 			fs->wl = winlink_next_by_number(s->curw, s, n);
401 		else
402 			fs->wl = winlink_previous_by_number(s->curw, s, n);
403 		if (fs->wl != NULL) {
404 			fs->idx = fs->wl->idx;
405 			fs->w = fs->wl->window;
406 			return (0);
407 		}
408 	}
409 
410 	/* Try special characters. */
411 	if (!exact) {
412 		if (strcmp(window, "!") == 0) {
413 			fs->wl = TAILQ_FIRST(&fs->s->lastw);
414 			if (fs->wl == NULL)
415 				return (-1);
416 			fs->idx = fs->wl->idx;
417 			fs->w = fs->wl->window;
418 			return (0);
419 		} else if (strcmp(window, "^") == 0) {
420 			fs->wl = RB_MIN(winlinks, &fs->s->windows);
421 			if (fs->wl == NULL)
422 				return (-1);
423 			fs->idx = fs->wl->idx;
424 			fs->w = fs->wl->window;
425 			return (0);
426 		} else if (strcmp(window, "$") == 0) {
427 			fs->wl = RB_MAX(winlinks, &fs->s->windows);
428 			if (fs->wl == NULL)
429 				return (-1);
430 			fs->idx = fs->wl->idx;
431 			fs->w = fs->wl->window;
432 			return (0);
433 		}
434 	}
435 
436 	/* First see if this is a valid window index in this session. */
437 	if (window[0] != '+' && window[0] != '-') {
438 		idx = strtonum(window, 0, INT_MAX, &errstr);
439 		if (errstr == NULL) {
440 			if (fs->flags & CMD_FIND_WINDOW_INDEX) {
441 				fs->idx = idx;
442 				return (0);
443 			}
444 			fs->wl = winlink_find_by_index(&fs->s->windows, idx);
445 			if (fs->wl != NULL) {
446 				fs->w = fs->wl->window;
447 				return (0);
448 			}
449 		}
450 	}
451 
452 	/* Look for exact matches, error if more than one. */
453 	fs->wl = NULL;
454 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
455 		if (strcmp(window, wl->window->name) == 0) {
456 			if (fs->wl != NULL)
457 				return (-1);
458 			fs->wl = wl;
459 		}
460 	}
461 	if (fs->wl != NULL) {
462 		fs->idx = fs->wl->idx;
463 		fs->w = fs->wl->window;
464 		return (0);
465 	}
466 
467 	/* Stop now if exact only. */
468 	if (exact)
469 		return (-1);
470 
471 	/* Try as the start of a window name, error if multiple. */
472 	fs->wl = NULL;
473 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
474 		if (strncmp(window, wl->window->name, strlen(window)) == 0) {
475 			if (fs->wl != NULL)
476 				return (-1);
477 			fs->wl = wl;
478 		}
479 	}
480 	if (fs->wl != NULL) {
481 		fs->idx = fs->wl->idx;
482 		fs->w = fs->wl->window;
483 		return (0);
484 	}
485 
486 	/* Now look for pattern matches, again error if multiple. */
487 	fs->wl = NULL;
488 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
489 		if (fnmatch(window, wl->window->name, 0) == 0) {
490 			if (fs->wl != NULL)
491 				return (-1);
492 			fs->wl = wl;
493 		}
494 	}
495 	if (fs->wl != NULL) {
496 		fs->idx = fs->wl->idx;
497 		fs->w = fs->wl->window;
498 		return (0);
499 	}
500 
501 	return (-1);
502 }
503 
504 /* Find pane from string. Fills in s, wl, w, wp. */
505 static int
506 cmd_find_get_pane(struct cmd_find_state *fs, const char *pane, int only)
507 {
508 	log_debug("%s: %s", __func__, pane);
509 
510 	/* Check for pane ids starting with %. */
511 	if (*pane == '%') {
512 		fs->wp = window_pane_find_by_id_str(pane);
513 		if (fs->wp == NULL)
514 			return (-1);
515 		fs->w = fs->wp->window;
516 		return (cmd_find_best_session_with_window(fs));
517 	}
518 
519 	/* Not a pane id, so try the current session and window. */
520 	fs->s = fs->current->s;
521 	fs->wl = fs->current->wl;
522 	fs->idx = fs->current->idx;
523 	fs->w = fs->current->w;
524 
525 	/* We now only need to find the pane in this window. */
526 	if (cmd_find_get_pane_with_window(fs, pane) == 0)
527 		return (0);
528 
529 	/* Otherwise try as a window itself (this will also try as session). */
530 	if (!only && cmd_find_get_window(fs, pane, 0) == 0) {
531 		fs->wp = fs->w->active;
532 		return (0);
533 	}
534 
535 	return (-1);
536 }
537 
538 /*
539  * Find pane from string, assuming it is in given session. Needs s, fills in wl
540  * and w and wp.
541  */
542 static int
543 cmd_find_get_pane_with_session(struct cmd_find_state *fs, const char *pane)
544 {
545 	log_debug("%s: %s", __func__, pane);
546 
547 	/* Check for pane ids starting with %. */
548 	if (*pane == '%') {
549 		fs->wp = window_pane_find_by_id_str(pane);
550 		if (fs->wp == NULL)
551 			return (-1);
552 		fs->w = fs->wp->window;
553 		return (cmd_find_best_winlink_with_window(fs));
554 	}
555 
556 	/* Otherwise use the current window. */
557 	fs->wl = fs->s->curw;
558 	fs->idx = fs->wl->idx;
559 	fs->w = fs->wl->window;
560 
561 	/* Now we just need to look up the pane. */
562 	return (cmd_find_get_pane_with_window(fs, pane));
563 }
564 
565 /*
566  * Find pane from string, assuming it is in the given window. Needs w, fills in
567  * wp.
568  */
569 static int
570 cmd_find_get_pane_with_window(struct cmd_find_state *fs, const char *pane)
571 {
572 	const char		*errstr;
573 	int			 idx;
574 	struct window_pane	*wp;
575 	u_int			 n;
576 
577 	log_debug("%s: %s", __func__, pane);
578 
579 	/* Check for pane ids starting with %. */
580 	if (*pane == '%') {
581 		fs->wp = window_pane_find_by_id_str(pane);
582 		if (fs->wp == NULL)
583 			return (-1);
584 		if (fs->wp->window != fs->w)
585 			return (-1);
586 		return (0);
587 	}
588 
589 	/* Try special characters. */
590 	if (strcmp(pane, "!") == 0) {
591 		if (fs->w->last == NULL)
592 			return (-1);
593 		fs->wp = fs->w->last;
594 		if (fs->wp == NULL)
595 			return (-1);
596 		return (0);
597 	} else if (strcmp(pane, "{up-of}") == 0) {
598 		fs->wp = window_pane_find_up(fs->w->active);
599 		if (fs->wp == NULL)
600 			return (-1);
601 		return (0);
602 	} else if (strcmp(pane, "{down-of}") == 0) {
603 		fs->wp = window_pane_find_down(fs->w->active);
604 		if (fs->wp == NULL)
605 			return (-1);
606 		return (0);
607 	} else if (strcmp(pane, "{left-of}") == 0) {
608 		fs->wp = window_pane_find_left(fs->w->active);
609 		if (fs->wp == NULL)
610 			return (-1);
611 		return (0);
612 	} else if (strcmp(pane, "{right-of}") == 0) {
613 		fs->wp = window_pane_find_right(fs->w->active);
614 		if (fs->wp == NULL)
615 			return (-1);
616 		return (0);
617 	}
618 
619 	/* Try as an offset. */
620 	if (pane[0] == '+' || pane[0] == '-') {
621 		if (pane[1] != '\0')
622 			n = strtonum(pane + 1, 1, INT_MAX, NULL);
623 		else
624 			n = 1;
625 		wp = fs->w->active;
626 		if (pane[0] == '+')
627 			fs->wp = window_pane_next_by_number(fs->w, wp, n);
628 		else
629 			fs->wp = window_pane_previous_by_number(fs->w, wp, n);
630 		if (fs->wp != NULL)
631 			return (0);
632 	}
633 
634 	/* Get pane by index. */
635 	idx = strtonum(pane, 0, INT_MAX, &errstr);
636 	if (errstr == NULL) {
637 		fs->wp = window_pane_at_index(fs->w, idx);
638 		if (fs->wp != NULL)
639 			return (0);
640 	}
641 
642 	/* Try as a description. */
643 	fs->wp = window_find_string(fs->w, pane);
644 	if (fs->wp != NULL)
645 		return (0);
646 
647 	return (-1);
648 }
649 
650 /* Clear state. */
651 void
652 cmd_find_clear_state(struct cmd_find_state *fs, int flags)
653 {
654 	memset(fs, 0, sizeof *fs);
655 
656 	fs->flags = flags;
657 
658 	fs->idx = -1;
659 }
660 
661 /* Check if state is empty. */
662 int
663 cmd_find_empty_state(struct cmd_find_state *fs)
664 {
665 	if (fs->s == NULL && fs->wl == NULL && fs->w == NULL && fs->wp == NULL)
666 		return (1);
667 	return (0);
668 }
669 
670 /* Check if a state if valid. */
671 int
672 cmd_find_valid_state(struct cmd_find_state *fs)
673 {
674 	struct winlink	*wl;
675 
676 	if (fs->s == NULL || fs->wl == NULL || fs->w == NULL || fs->wp == NULL)
677 		return (0);
678 
679 	if (!session_alive(fs->s))
680 		return (0);
681 
682 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
683 		if (wl->window == fs->w && wl == fs->wl)
684 			break;
685 	}
686 	if (wl == NULL)
687 		return (0);
688 
689 	if (fs->w != fs->wl->window)
690 		return (0);
691 
692 	return (window_has_pane(fs->w, fs->wp));
693 }
694 
695 /* Copy a state. */
696 void
697 cmd_find_copy_state(struct cmd_find_state *dst, struct cmd_find_state *src)
698 {
699 	dst->s = src->s;
700 	dst->wl = src->wl;
701 	dst->idx = src->idx;
702 	dst->w = src->w;
703 	dst->wp = src->wp;
704 }
705 
706 /* Log the result. */
707 void
708 cmd_find_log_state(const char *prefix, struct cmd_find_state *fs)
709 {
710 	if (fs->s != NULL)
711 		log_debug("%s: s=$%u", prefix, fs->s->id);
712 	else
713 		log_debug("%s: s=none", prefix);
714 	if (fs->wl != NULL) {
715 		log_debug("%s: wl=%u %d w=@%u %s", prefix, fs->wl->idx,
716 		    fs->wl->window == fs->w, fs->w->id, fs->w->name);
717 	} else
718 		log_debug("%s: wl=none", prefix);
719 	if (fs->wp != NULL)
720 		log_debug("%s: wp=%%%u", prefix, fs->wp->id);
721 	else
722 		log_debug("%s: wp=none", prefix);
723 	if (fs->idx != -1)
724 		log_debug("%s: idx=%d", prefix, fs->idx);
725 	else
726 		log_debug("%s: idx=none", prefix);
727 }
728 
729 /* Find state from a session. */
730 void
731 cmd_find_from_session(struct cmd_find_state *fs, struct session *s, int flags)
732 {
733 	cmd_find_clear_state(fs, flags);
734 
735 	fs->s = s;
736 	fs->wl = fs->s->curw;
737 	fs->w = fs->wl->window;
738 	fs->wp = fs->w->active;
739 
740 	cmd_find_log_state(__func__, fs);
741 }
742 
743 /* Find state from a winlink. */
744 void
745 cmd_find_from_winlink(struct cmd_find_state *fs, struct winlink *wl, int flags)
746 {
747 	cmd_find_clear_state(fs, flags);
748 
749 	fs->s = wl->session;
750 	fs->wl = wl;
751 	fs->w = wl->window;
752 	fs->wp = wl->window->active;
753 
754 	cmd_find_log_state(__func__, fs);
755 }
756 
757 /* Find state from a session and window. */
758 int
759 cmd_find_from_session_window(struct cmd_find_state *fs, struct session *s,
760     struct window *w, int flags)
761 {
762 	cmd_find_clear_state(fs, flags);
763 
764 	fs->s = s;
765 	fs->w = w;
766 	if (cmd_find_best_winlink_with_window(fs) != 0) {
767 		cmd_find_clear_state(fs, flags);
768 		return (-1);
769 	}
770 	fs->wp = fs->w->active;
771 
772 	cmd_find_log_state(__func__, fs);
773 	return (0);
774 }
775 
776 /* Find state from a window. */
777 int
778 cmd_find_from_window(struct cmd_find_state *fs, struct window *w, int flags)
779 {
780 	cmd_find_clear_state(fs, flags);
781 
782 	fs->w = w;
783 	if (cmd_find_best_session_with_window(fs) != 0) {
784 		cmd_find_clear_state(fs, flags);
785 		return (-1);
786 	}
787 	if (cmd_find_best_winlink_with_window(fs) != 0) {
788 		cmd_find_clear_state(fs, flags);
789 		return (-1);
790 	}
791 	fs->wp = fs->w->active;
792 
793 	cmd_find_log_state(__func__, fs);
794 	return (0);
795 }
796 
797 /* Find state from a winlink and pane. */
798 void
799 cmd_find_from_winlink_pane(struct cmd_find_state *fs, struct winlink *wl,
800     struct window_pane *wp, int flags)
801 {
802 	cmd_find_clear_state(fs, flags);
803 
804 	fs->s = wl->session;
805 	fs->wl = wl;
806 	fs->idx = fs->wl->idx;
807 	fs->w = fs->wl->window;
808 	fs->wp = wp;
809 
810 	cmd_find_log_state(__func__, fs);
811 }
812 
813 /* Find state from a pane. */
814 int
815 cmd_find_from_pane(struct cmd_find_state *fs, struct window_pane *wp, int flags)
816 {
817 	if (cmd_find_from_window(fs, wp->window, flags) != 0)
818 		return (-1);
819 	fs->wp = wp;
820 
821 	cmd_find_log_state(__func__, fs);
822 	return (0);
823 }
824 
825 /* Find state from nothing. */
826 int
827 cmd_find_from_nothing(struct cmd_find_state *fs, int flags)
828 {
829 	cmd_find_clear_state(fs, flags);
830 
831 	fs->s = cmd_find_best_session(NULL, 0, flags);
832 	if (fs->s == NULL) {
833 		cmd_find_clear_state(fs, flags);
834 		return (-1);
835 	}
836 	fs->wl = fs->s->curw;
837 	fs->idx = fs->wl->idx;
838 	fs->w = fs->wl->window;
839 	fs->wp = fs->w->active;
840 
841 	cmd_find_log_state(__func__, fs);
842 	return (0);
843 }
844 
845 /* Find state from mouse. */
846 int
847 cmd_find_from_mouse(struct cmd_find_state *fs, struct mouse_event *m, int flags)
848 {
849 	cmd_find_clear_state(fs, flags);
850 
851 	if (!m->valid)
852 		return (-1);
853 
854 	fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
855 	if (fs->wp == NULL) {
856 		cmd_find_clear_state(fs, flags);
857 		return (-1);
858 	}
859 	fs->w = fs->wl->window;
860 
861 	cmd_find_log_state(__func__, fs);
862 	return (0);
863 }
864 
865 /* Find state from client. */
866 int
867 cmd_find_from_client(struct cmd_find_state *fs, struct client *c, int flags)
868 {
869 	struct session		*s;
870 	struct winlink		*wl;
871 	struct window_pane	*wp;
872 
873 	/* If no client, treat as from nothing. */
874 	if (c == NULL)
875 		return (cmd_find_from_nothing(fs, flags));
876 
877 	/* If this is an attached client, all done. */
878 	if (c->session != NULL) {
879 		cmd_find_from_session(fs, c->session, flags);
880 		return (0);
881 	}
882 	cmd_find_clear_state(fs, flags);
883 
884 	/*
885 	 * If this is an unattached client running in a pane, we can use that
886 	 * to limit the list of sessions to those containing that pane.
887 	 */
888 	wp = cmd_find_inside_pane(c);
889 	if (wp == NULL)
890 		goto unknown_pane;
891 
892 	/* If we have a session in TMUX, see if it has this pane. */
893 	s = cmd_find_try_TMUX(c);
894 	if (s != NULL) {
895 		RB_FOREACH(wl, winlinks, &s->windows) {
896 			if (window_has_pane(wl->window, wp))
897 				break;
898 		}
899 		if (wl != NULL) {
900 			fs->s = s;
901 			fs->wl = s->curw; /* use current session */
902 			fs->w = fs->wl->window;
903 			fs->wp = fs->w->active; /* use active pane */
904 
905 			cmd_find_log_state(__func__, fs);
906 			return (0);
907 		}
908 	}
909 
910 	/*
911 	 * Don't have a session, or it doesn't have this pane. Try all
912 	 * sessions.
913 	 */
914 	fs->w = wp->window;
915 	if (cmd_find_best_session_with_window(fs) != 0) {
916 		if (wp != NULL) {
917 			/*
918 			 * The window may have been destroyed but the pane
919 			 * still on all_window_panes due to something else
920 			 * holding a reference.
921 			 */
922 			goto unknown_pane;
923 		}
924 		cmd_find_clear_state(fs, 0);
925 		return (-1);
926 	}
927 	fs->wl = fs->s->curw;
928 	fs->w = fs->wl->window;
929 	fs->wp = fs->w->active; /* use active pane */
930 
931 	cmd_find_log_state(__func__, fs);
932 	return (0);
933 
934 unknown_pane:
935 	/*
936 	 * We're not running in a known pane, but maybe this client has TMUX
937 	 * in the environment. That'd give us a session.
938 	 */
939 	s = cmd_find_try_TMUX(c);
940 	if (s != NULL) {
941 		cmd_find_from_session(fs, s, flags);
942 		return (0);
943 	}
944 
945 	/* Otherwise we need to guess. */
946 	return (cmd_find_from_nothing(fs, flags));
947 }
948 
949 /*
950  * Split target into pieces and resolve for the given type. Fills in the given
951  * state. Returns 0 on success or -1 on error.
952  */
953 int
954 cmd_find_target(struct cmd_find_state *fs, struct cmdq_item *item,
955     const char *target, enum cmd_find_type type, int flags)
956 {
957 	struct mouse_event	*m;
958 	struct cmd_find_state	 current;
959 	char			*colon, *period, *copy = NULL;
960 	const char		*session, *window, *pane, *s;
961 	int			 window_only = 0, pane_only = 0;
962 
963 	/* Can fail flag implies quiet. */
964 	if (flags & CMD_FIND_CANFAIL)
965 		flags |= CMD_FIND_QUIET;
966 
967 	/* Log the arguments. */
968 	if (type == CMD_FIND_PANE)
969 		s = "pane";
970 	else if (type == CMD_FIND_WINDOW)
971 		s = "window";
972 	else if (type == CMD_FIND_SESSION)
973 		s = "session";
974 	else
975 		s = "unknown";
976 	if (target == NULL)
977 		log_debug("%s: target none, type %s", __func__, s);
978 	else
979 		log_debug("%s: target %s, type %s", __func__, target, s);
980 	log_debug("%s: item %p, flags %#x", __func__, item, flags);
981 
982 	/* Clear new state. */
983 	cmd_find_clear_state(fs, flags);
984 
985 	/* Find current state. */
986 	if (server_check_marked() && (flags & CMD_FIND_DEFAULT_MARKED)) {
987 		fs->current = &marked_pane;
988 		log_debug("%s: current is marked pane", __func__);
989 	} else if (cmd_find_valid_state(&item->shared->current)) {
990 		fs->current = &item->shared->current;
991 		log_debug("%s: current is from queue", __func__);
992 	} else if (cmd_find_from_client(&current, item->client, flags) == 0) {
993 		fs->current = &current;
994 		log_debug("%s: current is from client", __func__);
995 	} else {
996 		if (~flags & CMD_FIND_QUIET)
997 			cmdq_error(item, "no current target");
998 		goto error;
999 	}
1000 	if (!cmd_find_valid_state(fs->current))
1001 		fatalx("invalid current find state");
1002 
1003 	/* An empty or NULL target is the current. */
1004 	if (target == NULL || *target == '\0')
1005 		goto current;
1006 
1007 	/* Mouse target is a plain = or {mouse}. */
1008 	if (strcmp(target, "=") == 0 || strcmp(target, "{mouse}") == 0) {
1009 		m = &item->shared->mouse;
1010 		switch (type) {
1011 		case CMD_FIND_PANE:
1012 			fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
1013 			if (fs->wp != NULL)
1014 				fs->w = fs->wl->window;
1015 			break;
1016 		case CMD_FIND_WINDOW:
1017 		case CMD_FIND_SESSION:
1018 			fs->wl = cmd_mouse_window(m, &fs->s);
1019 			if (fs->wl != NULL) {
1020 				fs->w = fs->wl->window;
1021 				fs->wp = fs->w->active;
1022 			}
1023 			break;
1024 		}
1025 		if (fs->wp == NULL) {
1026 			if (~flags & CMD_FIND_QUIET)
1027 				cmdq_error(item, "no mouse target");
1028 			goto error;
1029 		}
1030 		goto found;
1031 	}
1032 
1033 	/* Marked target is a plain ~ or {marked}. */
1034 	if (strcmp(target, "~") == 0 || strcmp(target, "{marked}") == 0) {
1035 		if (!server_check_marked()) {
1036 			if (~flags & CMD_FIND_QUIET)
1037 				cmdq_error(item, "no marked target");
1038 			goto error;
1039 		}
1040 		cmd_find_copy_state(fs, &marked_pane);
1041 		goto found;
1042 	}
1043 
1044 	/* Find separators if they exist. */
1045 	copy = xstrdup(target);
1046 	colon = strchr(copy, ':');
1047 	if (colon != NULL)
1048 		*colon++ = '\0';
1049 	if (colon == NULL)
1050 		period = strchr(copy, '.');
1051 	else
1052 		period = strchr(colon, '.');
1053 	if (period != NULL)
1054 		*period++ = '\0';
1055 
1056 	/* Set session, window and pane parts. */
1057 	session = window = pane = NULL;
1058 	if (colon != NULL && period != NULL) {
1059 		session = copy;
1060 		window = colon;
1061 		window_only = 1;
1062 		pane = period;
1063 		pane_only = 1;
1064 	} else if (colon != NULL && period == NULL) {
1065 		session = copy;
1066 		window = colon;
1067 		window_only = 1;
1068 	} else if (colon == NULL && period != NULL) {
1069 		window = copy;
1070 		pane = period;
1071 		pane_only = 1;
1072 	} else {
1073 		if (*copy == '$')
1074 			session = copy;
1075 		else if (*copy == '@')
1076 			window = copy;
1077 		else if (*copy == '%')
1078 			pane = copy;
1079 		else {
1080 			switch (type) {
1081 			case CMD_FIND_SESSION:
1082 				session = copy;
1083 				break;
1084 			case CMD_FIND_WINDOW:
1085 				window = copy;
1086 				break;
1087 			case CMD_FIND_PANE:
1088 				pane = copy;
1089 				break;
1090 			}
1091 		}
1092 	}
1093 
1094 	/* Set exact match flags. */
1095 	if (session != NULL && *session == '=') {
1096 		session++;
1097 		fs->flags |= CMD_FIND_EXACT_SESSION;
1098 	}
1099 	if (window != NULL && *window == '=') {
1100 		window++;
1101 		fs->flags |= CMD_FIND_EXACT_WINDOW;
1102 	}
1103 
1104 	/* Empty is the same as NULL. */
1105 	if (session != NULL && *session == '\0')
1106 		session = NULL;
1107 	if (window != NULL && *window == '\0')
1108 		window = NULL;
1109 	if (pane != NULL && *pane == '\0')
1110 		pane = NULL;
1111 
1112 	/* Map though conversion table. */
1113 	if (session != NULL)
1114 		session = cmd_find_map_table(cmd_find_session_table, session);
1115 	if (window != NULL)
1116 		window = cmd_find_map_table(cmd_find_window_table, window);
1117 	if (pane != NULL)
1118 		pane = cmd_find_map_table(cmd_find_pane_table, pane);
1119 
1120 	log_debug("%s: target %s (flags %#x): session=%s, window=%s, pane=%s",
1121 	    __func__, target, flags, session == NULL ? "none" : session,
1122 	    window == NULL ? "none" : window, pane == NULL ? "none" : pane);
1123 
1124 	/* No pane is allowed if want an index. */
1125 	if (pane != NULL && (flags & CMD_FIND_WINDOW_INDEX)) {
1126 		if (~flags & CMD_FIND_QUIET)
1127 			cmdq_error(item, "can't specify pane here");
1128 		goto error;
1129 	}
1130 
1131 	/* If the session isn't NULL, look it up. */
1132 	if (session != NULL) {
1133 		/* This will fill in session. */
1134 		if (cmd_find_get_session(fs, session) != 0)
1135 			goto no_session;
1136 
1137 		/* If window and pane are NULL, use that session's current. */
1138 		if (window == NULL && pane == NULL) {
1139 			fs->wl = fs->s->curw;
1140 			fs->idx = -1;
1141 			fs->w = fs->wl->window;
1142 			fs->wp = fs->w->active;
1143 			goto found;
1144 		}
1145 
1146 		/* If window is present but pane not, find window in session. */
1147 		if (window != NULL && pane == NULL) {
1148 			/* This will fill in winlink and window. */
1149 			if (cmd_find_get_window_with_session(fs, window) != 0)
1150 				goto no_window;
1151 			fs->wp = fs->wl->window->active;
1152 			goto found;
1153 		}
1154 
1155 		/* If pane is present but window not, find pane. */
1156 		if (window == NULL && pane != NULL) {
1157 			/* This will fill in winlink and window and pane. */
1158 			if (cmd_find_get_pane_with_session(fs, pane) != 0)
1159 				goto no_pane;
1160 			goto found;
1161 		}
1162 
1163 		/*
1164 		 * If window and pane are present, find both in session. This
1165 		 * will fill in winlink and window.
1166 		 */
1167 		if (cmd_find_get_window_with_session(fs, window) != 0)
1168 			goto no_window;
1169 		/* This will fill in pane. */
1170 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1171 			goto no_pane;
1172 		goto found;
1173 	}
1174 
1175 	/* No session. If window and pane, try them. */
1176 	if (window != NULL && pane != NULL) {
1177 		/* This will fill in session, winlink and window. */
1178 		if (cmd_find_get_window(fs, window, window_only) != 0)
1179 			goto no_window;
1180 		/* This will fill in pane. */
1181 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1182 			goto no_pane;
1183 		goto found;
1184 	}
1185 
1186 	/* If just window is present, try it. */
1187 	if (window != NULL && pane == NULL) {
1188 		/* This will fill in session, winlink and window. */
1189 		if (cmd_find_get_window(fs, window, window_only) != 0)
1190 			goto no_window;
1191 		fs->wp = fs->wl->window->active;
1192 		goto found;
1193 	}
1194 
1195 	/* If just pane is present, try it. */
1196 	if (window == NULL && pane != NULL) {
1197 		/* This will fill in session, winlink, window and pane. */
1198 		if (cmd_find_get_pane(fs, pane, pane_only) != 0)
1199 			goto no_pane;
1200 		goto found;
1201 	}
1202 
1203 current:
1204 	/* Use the current session. */
1205 	cmd_find_copy_state(fs, fs->current);
1206 	if (flags & CMD_FIND_WINDOW_INDEX)
1207 		fs->idx = -1;
1208 	goto found;
1209 
1210 error:
1211 	fs->current = NULL;
1212 	log_debug("%s: error", __func__);
1213 
1214 	free(copy);
1215 	if (flags & CMD_FIND_CANFAIL)
1216 		return (0);
1217 	return (-1);
1218 
1219 found:
1220 	fs->current = NULL;
1221 	cmd_find_log_state(__func__, fs);
1222 
1223 	free(copy);
1224 	return (0);
1225 
1226 no_session:
1227 	if (~flags & CMD_FIND_QUIET)
1228 		cmdq_error(item, "can't find session %s", session);
1229 	goto error;
1230 
1231 no_window:
1232 	if (~flags & CMD_FIND_QUIET)
1233 		cmdq_error(item, "can't find window %s", window);
1234 	goto error;
1235 
1236 no_pane:
1237 	if (~flags & CMD_FIND_QUIET)
1238 		cmdq_error(item, "can't find pane %s", pane);
1239 	goto error;
1240 }
1241 
1242 /* Find the current client. */
1243 static struct client *
1244 cmd_find_current_client(struct cmdq_item *item, int quiet)
1245 {
1246 	struct client		*c;
1247 	struct session		*s;
1248 	struct window_pane	*wp;
1249 	struct cmd_find_state	 fs;
1250 
1251 	if (item->client != NULL && item->client->session != NULL)
1252 		return (item->client);
1253 
1254 	c = NULL;
1255 	if ((wp = cmd_find_inside_pane(item->client)) != NULL) {
1256 		cmd_find_clear_state(&fs, CMD_FIND_QUIET);
1257 		fs.w = wp->window;
1258 		if (cmd_find_best_session_with_window(&fs) == 0)
1259 			c = cmd_find_best_client(fs.s);
1260 	} else {
1261 		s = cmd_find_best_session(NULL, 0, CMD_FIND_QUIET);
1262 		if (s != NULL)
1263 			c = cmd_find_best_client(s);
1264 	}
1265 	if (c == NULL && !quiet)
1266 		cmdq_error(item, "no current client");
1267 	log_debug("%s: no target, return %p", __func__, c);
1268 	return (c);
1269 }
1270 
1271 /* Find the target client or report an error and return NULL. */
1272 struct client *
1273 cmd_find_client(struct cmdq_item *item, const char *target, int quiet)
1274 {
1275 	struct client	*c;
1276 	char		*copy;
1277 	size_t		 size;
1278 
1279 	/* A NULL argument means the current client. */
1280 	if (target == NULL)
1281 		return (cmd_find_current_client(item, quiet));
1282 	copy = xstrdup(target);
1283 
1284 	/* Trim a single trailing colon if any. */
1285 	size = strlen(copy);
1286 	if (size != 0 && copy[size - 1] == ':')
1287 		copy[size - 1] = '\0';
1288 
1289 	/* Check name and path of each client. */
1290 	TAILQ_FOREACH(c, &clients, entry) {
1291 		if (c->session == NULL)
1292 			continue;
1293 		if (strcmp(copy, c->name) == 0)
1294 			break;
1295 
1296 		if (*c->ttyname == '\0')
1297 			continue;
1298 		if (strcmp(copy, c->ttyname) == 0)
1299 			break;
1300 		if (strncmp(c->ttyname, _PATH_DEV, (sizeof _PATH_DEV) - 1) != 0)
1301 			continue;
1302 		if (strcmp(copy, c->ttyname + (sizeof _PATH_DEV) - 1) == 0)
1303 			break;
1304 	}
1305 
1306 	/* If no client found, report an error. */
1307 	if (c == NULL && !quiet)
1308 		cmdq_error(item, "can't find client %s", copy);
1309 
1310 	free(copy);
1311 	log_debug("%s: target %s, return %p", __func__, target, c);
1312 	return (c);
1313 }
1314