xref: /openbsd-src/usr.bin/tmux/cmd-find.c (revision d1df930ffab53da22f3324c32bed7ac5709915e6)
1 /* $OpenBSD: cmd-find.c,v 1.68 2018/08/18 20:08:52 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->w = fs->wl->window;
458 				return (0);
459 			}
460 			if (fs->flags & CMD_FIND_WINDOW_INDEX) {
461 				fs->idx = idx;
462 				return (0);
463 			}
464 		}
465 	}
466 
467 	/* Look for exact matches, error if more than one. */
468 	fs->wl = NULL;
469 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
470 		if (strcmp(window, wl->window->name) == 0) {
471 			if (fs->wl != NULL)
472 				return (-1);
473 			fs->wl = wl;
474 		}
475 	}
476 	if (fs->wl != NULL) {
477 		fs->idx = fs->wl->idx;
478 		fs->w = fs->wl->window;
479 		return (0);
480 	}
481 
482 	/* Stop now if exact only. */
483 	if (exact)
484 		return (-1);
485 
486 	/* Try as the start of a window name, error if multiple. */
487 	fs->wl = NULL;
488 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
489 		if (strncmp(window, wl->window->name, strlen(window)) == 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 	/* Now look for pattern matches, again error if multiple. */
502 	fs->wl = NULL;
503 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
504 		if (fnmatch(window, wl->window->name, 0) == 0) {
505 			if (fs->wl != NULL)
506 				return (-1);
507 			fs->wl = wl;
508 		}
509 	}
510 	if (fs->wl != NULL) {
511 		fs->idx = fs->wl->idx;
512 		fs->w = fs->wl->window;
513 		return (0);
514 	}
515 
516 	return (-1);
517 }
518 
519 /* Find pane from string. Fills in s, wl, w, wp. */
520 static int
521 cmd_find_get_pane(struct cmd_find_state *fs, const char *pane, int only)
522 {
523 	log_debug("%s: %s", __func__, pane);
524 
525 	/* Check for pane ids starting with %. */
526 	if (*pane == '%') {
527 		fs->wp = window_pane_find_by_id_str(pane);
528 		if (fs->wp == NULL)
529 			return (-1);
530 		fs->w = fs->wp->window;
531 		return (cmd_find_best_session_with_window(fs));
532 	}
533 
534 	/* Not a pane id, so try the current session and window. */
535 	fs->s = fs->current->s;
536 	fs->wl = fs->current->wl;
537 	fs->idx = fs->current->idx;
538 	fs->w = fs->current->w;
539 
540 	/* We now only need to find the pane in this window. */
541 	if (cmd_find_get_pane_with_window(fs, pane) == 0)
542 		return (0);
543 
544 	/* Otherwise try as a window itself (this will also try as session). */
545 	if (!only && cmd_find_get_window(fs, pane, 0) == 0) {
546 		fs->wp = fs->w->active;
547 		return (0);
548 	}
549 
550 	return (-1);
551 }
552 
553 /*
554  * Find pane from string, assuming it is in given session. Needs s, fills in wl
555  * and w and wp.
556  */
557 static int
558 cmd_find_get_pane_with_session(struct cmd_find_state *fs, const char *pane)
559 {
560 	log_debug("%s: %s", __func__, pane);
561 
562 	/* Check for pane ids starting with %. */
563 	if (*pane == '%') {
564 		fs->wp = window_pane_find_by_id_str(pane);
565 		if (fs->wp == NULL)
566 			return (-1);
567 		fs->w = fs->wp->window;
568 		return (cmd_find_best_winlink_with_window(fs));
569 	}
570 
571 	/* Otherwise use the current window. */
572 	fs->wl = fs->s->curw;
573 	fs->idx = fs->wl->idx;
574 	fs->w = fs->wl->window;
575 
576 	/* Now we just need to look up the pane. */
577 	return (cmd_find_get_pane_with_window(fs, pane));
578 }
579 
580 /*
581  * Find pane from string, assuming it is in the given window. Needs w, fills in
582  * wp.
583  */
584 static int
585 cmd_find_get_pane_with_window(struct cmd_find_state *fs, const char *pane)
586 {
587 	const char		*errstr;
588 	int			 idx;
589 	struct window_pane	*wp;
590 	u_int			 n;
591 
592 	log_debug("%s: %s", __func__, pane);
593 
594 	/* Check for pane ids starting with %. */
595 	if (*pane == '%') {
596 		fs->wp = window_pane_find_by_id_str(pane);
597 		if (fs->wp == NULL)
598 			return (-1);
599 		if (fs->wp->window != fs->w)
600 			return (-1);
601 		return (0);
602 	}
603 
604 	/* Try special characters. */
605 	if (strcmp(pane, "!") == 0) {
606 		fs->wp = fs->w->last;
607 		if (fs->wp == NULL)
608 			return (-1);
609 		return (0);
610 	} else if (strcmp(pane, "{up-of}") == 0) {
611 		fs->wp = window_pane_find_up(fs->w->active);
612 		if (fs->wp == NULL)
613 			return (-1);
614 		return (0);
615 	} else if (strcmp(pane, "{down-of}") == 0) {
616 		fs->wp = window_pane_find_down(fs->w->active);
617 		if (fs->wp == NULL)
618 			return (-1);
619 		return (0);
620 	} else if (strcmp(pane, "{left-of}") == 0) {
621 		fs->wp = window_pane_find_left(fs->w->active);
622 		if (fs->wp == NULL)
623 			return (-1);
624 		return (0);
625 	} else if (strcmp(pane, "{right-of}") == 0) {
626 		fs->wp = window_pane_find_right(fs->w->active);
627 		if (fs->wp == NULL)
628 			return (-1);
629 		return (0);
630 	}
631 
632 	/* Try as an offset. */
633 	if (pane[0] == '+' || pane[0] == '-') {
634 		if (pane[1] != '\0')
635 			n = strtonum(pane + 1, 1, INT_MAX, NULL);
636 		else
637 			n = 1;
638 		wp = fs->w->active;
639 		if (pane[0] == '+')
640 			fs->wp = window_pane_next_by_number(fs->w, wp, n);
641 		else
642 			fs->wp = window_pane_previous_by_number(fs->w, wp, n);
643 		if (fs->wp != NULL)
644 			return (0);
645 	}
646 
647 	/* Get pane by index. */
648 	idx = strtonum(pane, 0, INT_MAX, &errstr);
649 	if (errstr == NULL) {
650 		fs->wp = window_pane_at_index(fs->w, idx);
651 		if (fs->wp != NULL)
652 			return (0);
653 	}
654 
655 	/* Try as a description. */
656 	fs->wp = window_find_string(fs->w, pane);
657 	if (fs->wp != NULL)
658 		return (0);
659 
660 	return (-1);
661 }
662 
663 /* Clear state. */
664 void
665 cmd_find_clear_state(struct cmd_find_state *fs, int flags)
666 {
667 	memset(fs, 0, sizeof *fs);
668 
669 	fs->flags = flags;
670 
671 	fs->idx = -1;
672 }
673 
674 /* Check if state is empty. */
675 int
676 cmd_find_empty_state(struct cmd_find_state *fs)
677 {
678 	if (fs->s == NULL && fs->wl == NULL && fs->w == NULL && fs->wp == NULL)
679 		return (1);
680 	return (0);
681 }
682 
683 /* Check if a state if valid. */
684 int
685 cmd_find_valid_state(struct cmd_find_state *fs)
686 {
687 	struct winlink	*wl;
688 
689 	if (fs->s == NULL || fs->wl == NULL || fs->w == NULL || fs->wp == NULL)
690 		return (0);
691 
692 	if (!session_alive(fs->s))
693 		return (0);
694 
695 	RB_FOREACH(wl, winlinks, &fs->s->windows) {
696 		if (wl->window == fs->w && wl == fs->wl)
697 			break;
698 	}
699 	if (wl == NULL)
700 		return (0);
701 
702 	if (fs->w != fs->wl->window)
703 		return (0);
704 
705 	return (window_has_pane(fs->w, fs->wp));
706 }
707 
708 /* Copy a state. */
709 void
710 cmd_find_copy_state(struct cmd_find_state *dst, struct cmd_find_state *src)
711 {
712 	dst->s = src->s;
713 	dst->wl = src->wl;
714 	dst->idx = src->idx;
715 	dst->w = src->w;
716 	dst->wp = src->wp;
717 }
718 
719 /* Log the result. */
720 static void
721 cmd_find_log_state(const char *prefix, struct cmd_find_state *fs)
722 {
723 	if (fs->s != NULL)
724 		log_debug("%s: s=$%u %s", prefix, fs->s->id, fs->s->name);
725 	else
726 		log_debug("%s: s=none", prefix);
727 	if (fs->wl != NULL) {
728 		log_debug("%s: wl=%u %d w=@%u %s", prefix, fs->wl->idx,
729 		    fs->wl->window == fs->w, fs->w->id, fs->w->name);
730 	} else
731 		log_debug("%s: wl=none", prefix);
732 	if (fs->wp != NULL)
733 		log_debug("%s: wp=%%%u", prefix, fs->wp->id);
734 	else
735 		log_debug("%s: wp=none", prefix);
736 	if (fs->idx != -1)
737 		log_debug("%s: idx=%d", prefix, fs->idx);
738 	else
739 		log_debug("%s: idx=none", prefix);
740 }
741 
742 /* Find state from a session. */
743 void
744 cmd_find_from_session(struct cmd_find_state *fs, struct session *s, int flags)
745 {
746 	cmd_find_clear_state(fs, flags);
747 
748 	fs->s = s;
749 	fs->wl = fs->s->curw;
750 	fs->w = fs->wl->window;
751 	fs->wp = fs->w->active;
752 
753 	cmd_find_log_state(__func__, fs);
754 }
755 
756 /* Find state from a winlink. */
757 void
758 cmd_find_from_winlink(struct cmd_find_state *fs, struct winlink *wl, int flags)
759 {
760 	cmd_find_clear_state(fs, flags);
761 
762 	fs->s = wl->session;
763 	fs->wl = wl;
764 	fs->w = wl->window;
765 	fs->wp = wl->window->active;
766 
767 	cmd_find_log_state(__func__, fs);
768 }
769 
770 /* Find state from a session and window. */
771 int
772 cmd_find_from_session_window(struct cmd_find_state *fs, struct session *s,
773     struct window *w, int flags)
774 {
775 	cmd_find_clear_state(fs, flags);
776 
777 	fs->s = s;
778 	fs->w = w;
779 	if (cmd_find_best_winlink_with_window(fs) != 0) {
780 		cmd_find_clear_state(fs, flags);
781 		return (-1);
782 	}
783 	fs->wp = fs->w->active;
784 
785 	cmd_find_log_state(__func__, fs);
786 	return (0);
787 }
788 
789 /* Find state from a window. */
790 int
791 cmd_find_from_window(struct cmd_find_state *fs, struct window *w, int flags)
792 {
793 	cmd_find_clear_state(fs, flags);
794 
795 	fs->w = w;
796 	if (cmd_find_best_session_with_window(fs) != 0) {
797 		cmd_find_clear_state(fs, flags);
798 		return (-1);
799 	}
800 	if (cmd_find_best_winlink_with_window(fs) != 0) {
801 		cmd_find_clear_state(fs, flags);
802 		return (-1);
803 	}
804 	fs->wp = fs->w->active;
805 
806 	cmd_find_log_state(__func__, fs);
807 	return (0);
808 }
809 
810 /* Find state from a winlink and pane. */
811 void
812 cmd_find_from_winlink_pane(struct cmd_find_state *fs, struct winlink *wl,
813     struct window_pane *wp, int flags)
814 {
815 	cmd_find_clear_state(fs, flags);
816 
817 	fs->s = wl->session;
818 	fs->wl = wl;
819 	fs->idx = fs->wl->idx;
820 	fs->w = fs->wl->window;
821 	fs->wp = wp;
822 
823 	cmd_find_log_state(__func__, fs);
824 }
825 
826 /* Find state from a pane. */
827 int
828 cmd_find_from_pane(struct cmd_find_state *fs, struct window_pane *wp, int flags)
829 {
830 	if (cmd_find_from_window(fs, wp->window, flags) != 0)
831 		return (-1);
832 	fs->wp = wp;
833 
834 	cmd_find_log_state(__func__, fs);
835 	return (0);
836 }
837 
838 /* Find state from nothing. */
839 int
840 cmd_find_from_nothing(struct cmd_find_state *fs, int flags)
841 {
842 	cmd_find_clear_state(fs, flags);
843 
844 	fs->s = cmd_find_best_session(NULL, 0, flags);
845 	if (fs->s == NULL) {
846 		cmd_find_clear_state(fs, flags);
847 		return (-1);
848 	}
849 	fs->wl = fs->s->curw;
850 	fs->idx = fs->wl->idx;
851 	fs->w = fs->wl->window;
852 	fs->wp = fs->w->active;
853 
854 	cmd_find_log_state(__func__, fs);
855 	return (0);
856 }
857 
858 /* Find state from mouse. */
859 int
860 cmd_find_from_mouse(struct cmd_find_state *fs, struct mouse_event *m, int flags)
861 {
862 	cmd_find_clear_state(fs, flags);
863 
864 	if (!m->valid)
865 		return (-1);
866 
867 	fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
868 	if (fs->wp == NULL) {
869 		cmd_find_clear_state(fs, flags);
870 		return (-1);
871 	}
872 	fs->w = fs->wl->window;
873 
874 	cmd_find_log_state(__func__, fs);
875 	return (0);
876 }
877 
878 /* Find state from client. */
879 int
880 cmd_find_from_client(struct cmd_find_state *fs, struct client *c, int flags)
881 {
882 	struct session		*s;
883 	struct winlink		*wl;
884 	struct window_pane	*wp;
885 
886 	/* If no client, treat as from nothing. */
887 	if (c == NULL)
888 		return (cmd_find_from_nothing(fs, flags));
889 
890 	/* If this is an attached client, all done. */
891 	if (c->session != NULL) {
892 		cmd_find_from_session(fs, c->session, flags);
893 		return (0);
894 	}
895 	cmd_find_clear_state(fs, flags);
896 
897 	/*
898 	 * If this is an unattached client running in a pane, we can use that
899 	 * to limit the list of sessions to those containing that pane.
900 	 */
901 	wp = cmd_find_inside_pane(c);
902 	if (wp == NULL)
903 		goto unknown_pane;
904 
905 	/* If we have a session in TMUX, see if it has this pane. */
906 	s = cmd_find_try_TMUX(c);
907 	if (s != NULL) {
908 		RB_FOREACH(wl, winlinks, &s->windows) {
909 			if (window_has_pane(wl->window, wp))
910 				break;
911 		}
912 		if (wl != NULL) {
913 			log_debug("%s: session $%u has pane %%%u", __func__,
914 			    s->id, wp->id);
915 
916 			fs->s = s;
917 			fs->wl = s->curw; /* use current session */
918 			fs->w = fs->wl->window;
919 			fs->wp = fs->w->active; /* use active pane */
920 
921 			cmd_find_log_state(__func__, fs);
922 			return (0);
923 		} else {
924 			log_debug("%s: session $%u does not have pane %%%u",
925 			    __func__, s->id, wp->id);
926 		}
927 	}
928 
929 	/*
930 	 * Don't have a session, or it doesn't have this pane. Try all
931 	 * sessions.
932 	 */
933 	fs->w = wp->window;
934 	if (cmd_find_best_session_with_window(fs) != 0) {
935 		/*
936 		 * The window may have been destroyed but the pane
937 		 * still on all_window_panes due to something else
938 		 * holding a reference.
939 		 */
940 		goto unknown_pane;
941 	}
942 	fs->wl = fs->s->curw;
943 	fs->w = fs->wl->window;
944 	fs->wp = fs->w->active; /* use active pane */
945 
946 	cmd_find_log_state(__func__, fs);
947 	return (0);
948 
949 unknown_pane:
950 	/*
951 	 * We're not running in a known pane, but maybe this client has TMUX
952 	 * in the environment. That'd give us a session.
953 	 */
954 	s = cmd_find_try_TMUX(c);
955 	if (s != NULL) {
956 		cmd_find_from_session(fs, s, flags);
957 		return (0);
958 	}
959 
960 	/* Otherwise we need to guess. */
961 	return (cmd_find_from_nothing(fs, flags));
962 }
963 
964 /*
965  * Split target into pieces and resolve for the given type. Fills in the given
966  * state. Returns 0 on success or -1 on error.
967  */
968 int
969 cmd_find_target(struct cmd_find_state *fs, struct cmdq_item *item,
970     const char *target, enum cmd_find_type type, int flags)
971 {
972 	struct mouse_event	*m;
973 	struct cmd_find_state	 current;
974 	char			*colon, *period, *copy = NULL;
975 	const char		*session, *window, *pane, *s;
976 	int			 window_only = 0, pane_only = 0;
977 
978 	/* Can fail flag implies quiet. */
979 	if (flags & CMD_FIND_CANFAIL)
980 		flags |= CMD_FIND_QUIET;
981 
982 	/* Log the arguments. */
983 	if (type == CMD_FIND_PANE)
984 		s = "pane";
985 	else if (type == CMD_FIND_WINDOW)
986 		s = "window";
987 	else if (type == CMD_FIND_SESSION)
988 		s = "session";
989 	else
990 		s = "unknown";
991 	if (target == NULL)
992 		log_debug("%s: target none, type %s", __func__, s);
993 	else
994 		log_debug("%s: target %s, type %s", __func__, target, s);
995 	log_debug("%s: item %p, flags %#x", __func__, item, flags);
996 
997 	/* Clear new state. */
998 	cmd_find_clear_state(fs, flags);
999 
1000 	/* Find current state. */
1001 	if (server_check_marked() && (flags & CMD_FIND_DEFAULT_MARKED)) {
1002 		fs->current = &marked_pane;
1003 		log_debug("%s: current is marked pane", __func__);
1004 	} else if (cmd_find_valid_state(&item->shared->current)) {
1005 		fs->current = &item->shared->current;
1006 		log_debug("%s: current is from queue", __func__);
1007 	} else if (cmd_find_from_client(&current, item->client, flags) == 0) {
1008 		fs->current = &current;
1009 		log_debug("%s: current is from client", __func__);
1010 	} else {
1011 		if (~flags & CMD_FIND_QUIET)
1012 			cmdq_error(item, "no current target");
1013 		goto error;
1014 	}
1015 	if (!cmd_find_valid_state(fs->current))
1016 		fatalx("invalid current find state");
1017 
1018 	/* An empty or NULL target is the current. */
1019 	if (target == NULL || *target == '\0')
1020 		goto current;
1021 
1022 	/* Mouse target is a plain = or {mouse}. */
1023 	if (strcmp(target, "=") == 0 || strcmp(target, "{mouse}") == 0) {
1024 		m = &item->shared->mouse;
1025 		switch (type) {
1026 		case CMD_FIND_PANE:
1027 			fs->wp = cmd_mouse_pane(m, &fs->s, &fs->wl);
1028 			if (fs->wp != NULL)
1029 				fs->w = fs->wl->window;
1030 			break;
1031 		case CMD_FIND_WINDOW:
1032 		case CMD_FIND_SESSION:
1033 			fs->wl = cmd_mouse_window(m, &fs->s);
1034 			if (fs->wl != NULL) {
1035 				fs->w = fs->wl->window;
1036 				fs->wp = fs->w->active;
1037 			}
1038 			break;
1039 		}
1040 		if (fs->wp == NULL) {
1041 			if (~flags & CMD_FIND_QUIET)
1042 				cmdq_error(item, "no mouse target");
1043 			goto error;
1044 		}
1045 		goto found;
1046 	}
1047 
1048 	/* Marked target is a plain ~ or {marked}. */
1049 	if (strcmp(target, "~") == 0 || strcmp(target, "{marked}") == 0) {
1050 		if (!server_check_marked()) {
1051 			if (~flags & CMD_FIND_QUIET)
1052 				cmdq_error(item, "no marked target");
1053 			goto error;
1054 		}
1055 		cmd_find_copy_state(fs, &marked_pane);
1056 		goto found;
1057 	}
1058 
1059 	/* Find separators if they exist. */
1060 	copy = xstrdup(target);
1061 	colon = strchr(copy, ':');
1062 	if (colon != NULL)
1063 		*colon++ = '\0';
1064 	if (colon == NULL)
1065 		period = strchr(copy, '.');
1066 	else
1067 		period = strchr(colon, '.');
1068 	if (period != NULL)
1069 		*period++ = '\0';
1070 
1071 	/* Set session, window and pane parts. */
1072 	session = window = pane = NULL;
1073 	if (colon != NULL && period != NULL) {
1074 		session = copy;
1075 		window = colon;
1076 		window_only = 1;
1077 		pane = period;
1078 		pane_only = 1;
1079 	} else if (colon != NULL && period == NULL) {
1080 		session = copy;
1081 		window = colon;
1082 		window_only = 1;
1083 	} else if (colon == NULL && period != NULL) {
1084 		window = copy;
1085 		pane = period;
1086 		pane_only = 1;
1087 	} else {
1088 		if (*copy == '$')
1089 			session = copy;
1090 		else if (*copy == '@')
1091 			window = copy;
1092 		else if (*copy == '%')
1093 			pane = copy;
1094 		else {
1095 			switch (type) {
1096 			case CMD_FIND_SESSION:
1097 				session = copy;
1098 				break;
1099 			case CMD_FIND_WINDOW:
1100 				window = copy;
1101 				break;
1102 			case CMD_FIND_PANE:
1103 				pane = copy;
1104 				break;
1105 			}
1106 		}
1107 	}
1108 
1109 	/* Set exact match flags. */
1110 	if (session != NULL && *session == '=') {
1111 		session++;
1112 		fs->flags |= CMD_FIND_EXACT_SESSION;
1113 	}
1114 	if (window != NULL && *window == '=') {
1115 		window++;
1116 		fs->flags |= CMD_FIND_EXACT_WINDOW;
1117 	}
1118 
1119 	/* Empty is the same as NULL. */
1120 	if (session != NULL && *session == '\0')
1121 		session = NULL;
1122 	if (window != NULL && *window == '\0')
1123 		window = NULL;
1124 	if (pane != NULL && *pane == '\0')
1125 		pane = NULL;
1126 
1127 	/* Map though conversion table. */
1128 	if (session != NULL)
1129 		session = cmd_find_map_table(cmd_find_session_table, session);
1130 	if (window != NULL)
1131 		window = cmd_find_map_table(cmd_find_window_table, window);
1132 	if (pane != NULL)
1133 		pane = cmd_find_map_table(cmd_find_pane_table, pane);
1134 
1135 	log_debug("%s: target %s (flags %#x): session=%s, window=%s, pane=%s",
1136 	    __func__, target, flags, session == NULL ? "none" : session,
1137 	    window == NULL ? "none" : window, pane == NULL ? "none" : pane);
1138 
1139 	/* No pane is allowed if want an index. */
1140 	if (pane != NULL && (flags & CMD_FIND_WINDOW_INDEX)) {
1141 		if (~flags & CMD_FIND_QUIET)
1142 			cmdq_error(item, "can't specify pane here");
1143 		goto error;
1144 	}
1145 
1146 	/* If the session isn't NULL, look it up. */
1147 	if (session != NULL) {
1148 		/* This will fill in session. */
1149 		if (cmd_find_get_session(fs, session) != 0)
1150 			goto no_session;
1151 
1152 		/* If window and pane are NULL, use that session's current. */
1153 		if (window == NULL && pane == NULL) {
1154 			fs->wl = fs->s->curw;
1155 			fs->idx = -1;
1156 			fs->w = fs->wl->window;
1157 			fs->wp = fs->w->active;
1158 			goto found;
1159 		}
1160 
1161 		/* If window is present but pane not, find window in session. */
1162 		if (window != NULL && pane == NULL) {
1163 			/* This will fill in winlink and window. */
1164 			if (cmd_find_get_window_with_session(fs, window) != 0)
1165 				goto no_window;
1166 			if (fs->wl != NULL) /* can be NULL if index only */
1167 				fs->wp = fs->wl->window->active;
1168 			goto found;
1169 		}
1170 
1171 		/* If pane is present but window not, find pane. */
1172 		if (window == NULL && pane != NULL) {
1173 			/* This will fill in winlink and window and pane. */
1174 			if (cmd_find_get_pane_with_session(fs, pane) != 0)
1175 				goto no_pane;
1176 			goto found;
1177 		}
1178 
1179 		/*
1180 		 * If window and pane are present, find both in session. This
1181 		 * will fill in winlink and window.
1182 		 */
1183 		if (cmd_find_get_window_with_session(fs, window) != 0)
1184 			goto no_window;
1185 		/* This will fill in pane. */
1186 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1187 			goto no_pane;
1188 		goto found;
1189 	}
1190 
1191 	/* No session. If window and pane, try them. */
1192 	if (window != NULL && pane != NULL) {
1193 		/* This will fill in session, winlink and window. */
1194 		if (cmd_find_get_window(fs, window, window_only) != 0)
1195 			goto no_window;
1196 		/* This will fill in pane. */
1197 		if (cmd_find_get_pane_with_window(fs, pane) != 0)
1198 			goto no_pane;
1199 		goto found;
1200 	}
1201 
1202 	/* If just window is present, try it. */
1203 	if (window != NULL && pane == NULL) {
1204 		/* This will fill in session, winlink and window. */
1205 		if (cmd_find_get_window(fs, window, window_only) != 0)
1206 			goto no_window;
1207 		if (fs->wl != NULL) /* can be NULL if index only */
1208 			fs->wp = fs->wl->window->active;
1209 		goto found;
1210 	}
1211 
1212 	/* If just pane is present, try it. */
1213 	if (window == NULL && pane != NULL) {
1214 		/* This will fill in session, winlink, window and pane. */
1215 		if (cmd_find_get_pane(fs, pane, pane_only) != 0)
1216 			goto no_pane;
1217 		goto found;
1218 	}
1219 
1220 current:
1221 	/* Use the current session. */
1222 	cmd_find_copy_state(fs, fs->current);
1223 	if (flags & CMD_FIND_WINDOW_INDEX)
1224 		fs->idx = -1;
1225 	goto found;
1226 
1227 error:
1228 	fs->current = NULL;
1229 	log_debug("%s: error", __func__);
1230 
1231 	free(copy);
1232 	if (flags & CMD_FIND_CANFAIL)
1233 		return (0);
1234 	return (-1);
1235 
1236 found:
1237 	fs->current = NULL;
1238 	cmd_find_log_state(__func__, fs);
1239 
1240 	free(copy);
1241 	return (0);
1242 
1243 no_session:
1244 	if (~flags & CMD_FIND_QUIET)
1245 		cmdq_error(item, "can't find session %s", session);
1246 	goto error;
1247 
1248 no_window:
1249 	if (~flags & CMD_FIND_QUIET)
1250 		cmdq_error(item, "can't find window %s", window);
1251 	goto error;
1252 
1253 no_pane:
1254 	if (~flags & CMD_FIND_QUIET)
1255 		cmdq_error(item, "can't find pane %s", pane);
1256 	goto error;
1257 }
1258 
1259 /* Find the current client. */
1260 static struct client *
1261 cmd_find_current_client(struct cmdq_item *item, int quiet)
1262 {
1263 	struct client		*c;
1264 	struct session		*s;
1265 	struct window_pane	*wp;
1266 	struct cmd_find_state	 fs;
1267 
1268 	if (item->client != NULL && item->client->session != NULL)
1269 		return (item->client);
1270 
1271 	c = NULL;
1272 	if ((wp = cmd_find_inside_pane(item->client)) != NULL) {
1273 		cmd_find_clear_state(&fs, CMD_FIND_QUIET);
1274 		fs.w = wp->window;
1275 		if (cmd_find_best_session_with_window(&fs) == 0)
1276 			c = cmd_find_best_client(fs.s);
1277 	} else {
1278 		s = cmd_find_best_session(NULL, 0, CMD_FIND_QUIET);
1279 		if (s != NULL)
1280 			c = cmd_find_best_client(s);
1281 	}
1282 	if (c == NULL && !quiet)
1283 		cmdq_error(item, "no current client");
1284 	log_debug("%s: no target, return %p", __func__, c);
1285 	return (c);
1286 }
1287 
1288 /* Find the target client or report an error and return NULL. */
1289 struct client *
1290 cmd_find_client(struct cmdq_item *item, const char *target, int quiet)
1291 {
1292 	struct client	*c;
1293 	char		*copy;
1294 	size_t		 size;
1295 
1296 	/* A NULL argument means the current client. */
1297 	if (target == NULL)
1298 		return (cmd_find_current_client(item, quiet));
1299 	copy = xstrdup(target);
1300 
1301 	/* Trim a single trailing colon if any. */
1302 	size = strlen(copy);
1303 	if (size != 0 && copy[size - 1] == ':')
1304 		copy[size - 1] = '\0';
1305 
1306 	/* Check name and path of each client. */
1307 	TAILQ_FOREACH(c, &clients, entry) {
1308 		if (c->session == NULL)
1309 			continue;
1310 		if (strcmp(copy, c->name) == 0)
1311 			break;
1312 
1313 		if (*c->ttyname == '\0')
1314 			continue;
1315 		if (strcmp(copy, c->ttyname) == 0)
1316 			break;
1317 		if (strncmp(c->ttyname, _PATH_DEV, (sizeof _PATH_DEV) - 1) != 0)
1318 			continue;
1319 		if (strcmp(copy, c->ttyname + (sizeof _PATH_DEV) - 1) == 0)
1320 			break;
1321 	}
1322 
1323 	/* If no client found, report an error. */
1324 	if (c == NULL && !quiet)
1325 		cmdq_error(item, "can't find client %s", copy);
1326 
1327 	free(copy);
1328 	log_debug("%s: target %s, return %p", __func__, target, c);
1329 	return (c);
1330 }
1331