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