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