summaryrefslogtreecommitdiff
path: root/usr.bin/tmux/cmd.c
blob: f56358ab34de3d25505aa3b1f7591b17d7c87d14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
/* $OpenBSD: cmd.c,v 1.50 2011/01/23 11:03:43 nicm Exp $ */

/*
 * Copyright (c) 2007 Nicholas Marriott <nicm@users.sourceforge.net>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/time.h>

#include <fnmatch.h>
#include <paths.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "tmux.h"

const struct cmd_entry *cmd_table[] = {
	&cmd_attach_session_entry,
	&cmd_bind_key_entry,
	&cmd_break_pane_entry,
	&cmd_capture_pane_entry,
	&cmd_choose_buffer_entry,
	&cmd_choose_client_entry,
	&cmd_choose_session_entry,
	&cmd_choose_window_entry,
	&cmd_clear_history_entry,
	&cmd_clock_mode_entry,
	&cmd_command_prompt_entry,
	&cmd_confirm_before_entry,
	&cmd_copy_mode_entry,
	&cmd_delete_buffer_entry,
	&cmd_detach_client_entry,
	&cmd_display_message_entry,
	&cmd_display_panes_entry,
	&cmd_find_window_entry,
	&cmd_has_session_entry,
	&cmd_if_shell_entry,
	&cmd_join_pane_entry,
	&cmd_kill_pane_entry,
	&cmd_kill_server_entry,
	&cmd_kill_session_entry,
	&cmd_kill_window_entry,
	&cmd_last_pane_entry,
	&cmd_last_window_entry,
	&cmd_link_window_entry,
	&cmd_list_buffers_entry,
	&cmd_list_clients_entry,
	&cmd_list_commands_entry,
	&cmd_list_keys_entry,
	&cmd_list_panes_entry,
	&cmd_list_sessions_entry,
	&cmd_list_windows_entry,
	&cmd_load_buffer_entry,
	&cmd_lock_client_entry,
	&cmd_lock_server_entry,
	&cmd_lock_session_entry,
	&cmd_move_window_entry,
	&cmd_new_session_entry,
	&cmd_new_window_entry,
	&cmd_next_layout_entry,
	&cmd_next_window_entry,
	&cmd_paste_buffer_entry,
	&cmd_pipe_pane_entry,
	&cmd_previous_layout_entry,
	&cmd_previous_window_entry,
	&cmd_refresh_client_entry,
	&cmd_rename_session_entry,
	&cmd_rename_window_entry,
	&cmd_resize_pane_entry,
	&cmd_respawn_window_entry,
	&cmd_rotate_window_entry,
	&cmd_run_shell_entry,
	&cmd_save_buffer_entry,
	&cmd_select_layout_entry,
	&cmd_select_pane_entry,
	&cmd_select_window_entry,
	&cmd_send_keys_entry,
	&cmd_send_prefix_entry,
	&cmd_server_info_entry,
	&cmd_set_buffer_entry,
	&cmd_set_environment_entry,
	&cmd_set_option_entry,
	&cmd_set_window_option_entry,
	&cmd_show_buffer_entry,
	&cmd_show_environment_entry,
	&cmd_show_messages_entry,
	&cmd_show_options_entry,
	&cmd_show_window_options_entry,
	&cmd_source_file_entry,
	&cmd_split_window_entry,
	&cmd_start_server_entry,
	&cmd_suspend_client_entry,
	&cmd_swap_pane_entry,
	&cmd_swap_window_entry,
	&cmd_switch_client_entry,
	&cmd_unbind_key_entry,
	&cmd_unlink_window_entry,
	NULL
};

struct session	*cmd_choose_session_list(struct sessionslist *);
struct session	*cmd_choose_session(void);
struct client	*cmd_choose_client(struct clients *);
struct client	*cmd_lookup_client(const char *);
struct session	*cmd_lookup_session(const char *, int *);
struct winlink	*cmd_lookup_window(struct session *, const char *, int *);
int		 cmd_lookup_index(struct session *, const char *, int *);
struct winlink	*cmd_find_window_offset(const char *, struct session *, int *);
int		 cmd_find_index_offset(const char *, struct session *, int *);
struct window_pane	*cmd_find_pane_offset(const char *, struct winlink *);

int
cmd_pack_argv(int argc, char **argv, char *buf, size_t len)
{
	size_t	arglen;
	int	i;

	*buf = '\0';
	for (i = 0; i < argc; i++) {
		if (strlcpy(buf, argv[i], len) >= len)
			return (-1);
		arglen = strlen(argv[i]) + 1;
		buf += arglen;
		len -= arglen;
	}

	return (0);
}

int
cmd_unpack_argv(char *buf, size_t len, int argc, char ***argv)
{
	int	i;
	size_t	arglen;

	if (argc == 0)
		return (0);
	*argv = xcalloc(argc, sizeof **argv);

	buf[len - 1] = '\0';
	for (i = 0; i < argc; i++) {
		if (len == 0) {
			cmd_free_argv(argc, *argv);
			return (-1);
		}

		arglen = strlen(buf) + 1;
		(*argv)[i] = xstrdup(buf);
		buf += arglen;
		len -= arglen;
	}

	return (0);
}

char **
cmd_copy_argv(int argc, char *const *argv)
{
	char	**new_argv;
	int	  i;

	if (argc == 0)
		return (NULL);
	new_argv = xcalloc(argc, sizeof *new_argv);
	for (i = 0; i < argc; i++) {
		if (argv[i] != NULL)
			new_argv[i] = xstrdup(argv[i]);
	}
	return (new_argv);
}

void
cmd_free_argv(int argc, char **argv)
{
	int	i;

	if (argc == 0)
		return;
	for (i = 0; i < argc; i++) {
		if (argv[i] != NULL)
			xfree(argv[i]);
	}
	xfree(argv);
}

struct cmd *
cmd_parse(int argc, char **argv, char **cause)
{
	const struct cmd_entry **entryp, *entry;
	struct cmd		*cmd;
	struct args		*args;
	char			 s[BUFSIZ];
	int			 ambiguous = 0;

	*cause = NULL;
	if (argc == 0) {
		xasprintf(cause, "no command");
		return (NULL);
	}

	entry = NULL;
	for (entryp = cmd_table; *entryp != NULL; entryp++) {
		if ((*entryp)->alias != NULL &&
		    strcmp((*entryp)->alias, argv[0]) == 0) {
			ambiguous = 0;
			entry = *entryp;
			break;
		}

		if (strncmp((*entryp)->name, argv[0], strlen(argv[0])) != 0)
			continue;
		if (entry != NULL)
			ambiguous = 1;
		entry = *entryp;

		/* Bail now if an exact match. */
		if (strcmp(entry->name, argv[0]) == 0)
			break;
	}
	if (ambiguous)
		goto ambiguous;
	if (entry == NULL) {
		xasprintf(cause, "unknown command: %s", argv[0]);
		return (NULL);
	}

	args = args_parse(entry->args_template, argc, argv);
	if (args == NULL)
		goto usage;
	if (entry->args_lower != -1 && args->argc < entry->args_lower)
		goto usage;
	if (entry->args_upper != -1 && args->argc > entry->args_upper)
		goto usage;
	if (entry->check != NULL && entry->check(args) != 0)
		goto usage;

	cmd = xmalloc(sizeof *cmd);
	cmd->entry = entry;
	cmd->args = args;
	return (cmd);

ambiguous:
	*s = '\0';
	for (entryp = cmd_table; *entryp != NULL; entryp++) {
		if (strncmp((*entryp)->name, argv[0], strlen(argv[0])) != 0)
			continue;
		if (strlcat(s, (*entryp)->name, sizeof s) >= sizeof s)
			break;
		if (strlcat(s, ", ", sizeof s) >= sizeof s)
			break;
	}
	s[strlen(s) - 2] = '\0';
	xasprintf(cause, "ambiguous command: %s, could be: %s", argv[0], s);
	return (NULL);

usage:
	if (args != NULL)
		args_free(args);
	xasprintf(cause, "usage: %s %s", entry->name, entry->usage);
	return (NULL);
}

int
cmd_exec(struct cmd *cmd, struct cmd_ctx *ctx)
{
	return (cmd->entry->exec(cmd, ctx));
}

void
cmd_free(struct cmd *cmd)
{
	if (cmd->args != NULL)
		args_free(cmd->args);
	xfree(cmd);
}

size_t
cmd_print(struct cmd *cmd, char *buf, size_t len)
{
	size_t	off, used;

	off = xsnprintf(buf, len, "%s ", cmd->entry->name);
	if (off < len) {
		used = args_print(cmd->args, buf + off, len - off);
		if (used == 0)
			buf[off - 1] = '\0';
		else {
			off += used;
			buf[off] = '\0';
		}
	}
	return (off);
}

/*
 * Figure out the current session. Use: 1) the current session, if the command
 * context has one; 2) the most recently used session containing the pty of the
 * calling client, if any; 3) the session specified in the TMUX variable from
 * the environment (as passed from the client); 4) the most recently used
 * session from all sessions.
 */
struct session *
cmd_current_session(struct cmd_ctx *ctx)
{
	struct msg_command_data	*data = ctx->msgdata;
	struct client		*c = ctx->cmdclient;
	struct session		*s;
	struct sessionslist	 ss;
	struct winlink		*wl;
	struct window_pane	*wp;
	int			 found;

	if (ctx->curclient != NULL && ctx->curclient->session != NULL)
		return (ctx->curclient->session);

	/*
	 * If the name of the calling client's pty is know, build a list of the
	 * sessions that contain it and if any choose either the first or the
	 * newest.
	 */
	if (c != NULL && c->tty.path != NULL) {
		ARRAY_INIT(&ss);
		RB_FOREACH(s, sessions, &sessions) {
			found = 0;
			RB_FOREACH(wl, winlinks, &s->windows) {
				TAILQ_FOREACH(wp, &wl->window->panes, entry) {
					if (strcmp(wp->tty, c->tty.path) == 0) {
						found = 1;
						break;
					}
				}
				if (found)
					break;
			}
			if (found)
				ARRAY_ADD(&ss, s);
		}

		s = cmd_choose_session_list(&ss);
		ARRAY_FREE(&ss);
		if (s != NULL)
			return (s);
	}

	/* Use the session from the TMUX environment variable. */
	if (data != NULL && data->pid == getpid() && data->idx != -1) {
		s = session_find_by_index(data->idx);
		if (s != NULL)
			return (s);
	}

	return (cmd_choose_session());
}

/* Find the most recently used session. */
struct session *
cmd_choose_session(void)
{
	struct session	*s, *sbest;
	struct timeval	*tv = NULL;

	sbest = NULL;
	RB_FOREACH(s, sessions, &sessions) {
		if (tv == NULL || timercmp(&s->activity_time, tv, >)) {
			sbest = s;
			tv = &s->activity_time;
		}
	}

	return (sbest);
}

/* Find the most recently used session from a list. */
struct session *
cmd_choose_session_list(struct sessionslist *ss)
{
	struct session	*s, *sbest;
	struct timeval	*tv = NULL;
	u_int		 i;

	sbest = NULL;
	for (i = 0; i < ARRAY_LENGTH(ss); i++) {
		if ((s = ARRAY_ITEM(ss, i)) == NULL)
			continue;

		if (tv == NULL || timercmp(&s->activity_time, tv, >)) {
			sbest = s;
			tv = &s->activity_time;
		}
	}

	return (sbest);
}

/*
 * Find the current client. First try the current client if set, then pick the
 * most recently used of the clients attached to the current session if any,
 * then of all clients.
 */
struct client *
cmd_current_client(struct cmd_ctx *ctx)
{
	struct session		*s;
	struct client		*c;
	struct clients		 cc;
	u_int			 i;

	if (ctx->curclient != NULL)
		return (ctx->curclient);

	/*
	 * No current client set. Find the current session and return the
	 * newest of its clients.
	 */
	s = cmd_current_session(ctx);
	if (s != NULL && !(s->flags & SESSION_UNATTACHED)) {
		ARRAY_INIT(&cc);
		for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
			if ((c = ARRAY_ITEM(&clients, i)) == NULL)
				continue;
			if (s == c->session)
				ARRAY_ADD(&cc, c);
		}

		c = cmd_choose_client(&cc);
		ARRAY_FREE(&cc);
		if (c != NULL)
			return (c);
	}

	return (cmd_choose_client(&clients));
}

/* Choose the most recently used client from a list. */
struct client *
cmd_choose_client(struct clients *cc)
{
	struct client	*c, *cbest;
	struct timeval	*tv = NULL;
	u_int		 i;

	cbest = NULL;
	for (i = 0; i < ARRAY_LENGTH(cc); i++) {
		if ((c = ARRAY_ITEM(cc, i)) == NULL)
			continue;
		if (c->session == NULL)
			continue;

		if (tv == NULL || timercmp(&c->activity_time, tv, >)) {
			cbest = c;
			tv = &c->activity_time;
		}
	}

	return (cbest);
}

/* Find the target client or report an error and return NULL. */
struct client *
cmd_find_client(struct cmd_ctx *ctx, const char *arg)
{
	struct client	*c;
	char		*tmparg;
	size_t		 arglen;

	/* A NULL argument means the current client. */
	if (arg == NULL)
		return (cmd_current_client(ctx));
	tmparg = xstrdup(arg);

	/* Trim a single trailing colon if any. */
	arglen = strlen(tmparg);
	if (arglen != 0 && tmparg[arglen - 1] == ':')
		tmparg[arglen - 1] = '\0';

	/* Find the client, if any. */
	c = cmd_lookup_client(tmparg);

	/* If no client found, report an error. */
	if (c == NULL)
		ctx->error(ctx, "client not found: %s", tmparg);

	xfree(tmparg);
	return (c);
}

/*
 * Lookup a client by device path. Either of a full match and a match without a
 * leading _PATH_DEV ("/dev/") is accepted.
 */
struct client *
cmd_lookup_client(const char *name)
{
	struct client	*c;
	const char	*path;
	u_int		 i;

	for (i = 0; i < ARRAY_LENGTH(&clients); i++) {
		c = ARRAY_ITEM(&clients, i);
		if (c == NULL || c->session == NULL)
			continue;
		path = c->tty.path;

		/* Check for exact matches. */
		if (strcmp(name, path) == 0)
			return (c);

		/* Check without leading /dev if present. */
		if (strncmp(path, _PATH_DEV, (sizeof _PATH_DEV) - 1) != 0)
			continue;
		if (strcmp(name, path + (sizeof _PATH_DEV) - 1) == 0)
			return (c);
	}

	return (NULL);
}

/* Lookup a session by name. If no session is found, NULL is returned. */
struct session *
cmd_lookup_session(const char *name, int *ambiguous)
{
	struct session	*s, *sfound;

	*ambiguous = 0;

	/*
	 * Look for matches. First look for exact matches - session names must
	 * be unique so an exact match can't be ambigious and can just be
	 * returned.
	 */
	if ((s = session_find(name)) != NULL)
		return (s);

	/*
	 * Otherwise look for partial matches, returning early if it is found to
	 * be ambiguous.
	 */
	sfound = NULL;
	RB_FOREACH(s, sessions, &sessions) {
		if (strncmp(name, s->name, strlen(name)) == 0 ||
		    fnmatch(name, s->name, 0) == 0) {
			if (sfound != NULL) {
				*ambiguous = 1;
				return (NULL);
			}
			sfound = s;
		}
	}
	return (sfound);
}

/*
 * Lookup a window or return -1 if not found or ambigious. First try as an
 * index and if invalid, use fnmatch or leading prefix. Return NULL but fill in
 * idx if the window index is a valid number but there is no window with that
 * index.
 */
struct winlink *
cmd_lookup_window(struct session *s, const char *name, int *ambiguous)
{
	struct winlink	*wl, *wlfound;
	const char	*errstr;
	u_int		 idx;

	*ambiguous = 0;

	/* First see if this is a valid window index in this session. */
	idx = strtonum(name, 0, INT_MAX, &errstr);
	if (errstr == NULL) {
		if ((wl = winlink_find_by_index(&s->windows, idx)) != NULL)
			return (wl);
	}

	/* Look for exact matches, error if more than one. */
	wlfound = NULL;
	RB_FOREACH(wl, winlinks, &s->windows) {
		if (strcmp(name, wl->window->name) == 0) {
			if (wlfound != NULL) {
				*ambiguous = 1;
				return (NULL);
			}
			wlfound = wl;
		}
	}
	if (wlfound != NULL)
		return (wlfound);

	/* Now look for pattern matches, again error if multiple. */
	wlfound = NULL;
	RB_FOREACH(wl, winlinks, &s->windows) {
		if (strncmp(name, wl->window->name, strlen(name)) == 0 ||
		    fnmatch(name, wl->window->name, 0) == 0) {
			if (wlfound != NULL) {
				*ambiguous = 1;
				return (NULL);
			}
			wlfound = wl;
		}
	}
	if (wlfound != NULL)
		return (wlfound);

	return (NULL);
}

/*
 * Find a window index - if the window doesn't exist, check if it is a
 * potential index and return it anyway.
 */
int
cmd_lookup_index(struct session *s, const char *name, int *ambiguous)
{
	struct winlink	*wl;
	const char	*errstr;
	u_int		 idx;

	if ((wl = cmd_lookup_window(s, name, ambiguous)) != NULL)
		return (wl->idx);
	if (*ambiguous)
		return (-1);

	idx = strtonum(name, 0, INT_MAX, &errstr);
	if (errstr == NULL)
		return (idx);

	return (-1);
}

/* Find the target session or report an error and return NULL. */
struct session *
cmd_find_session(struct cmd_ctx *ctx, const char *arg)
{
	struct session	*s;
	struct client	*c;
	char		*tmparg;
	size_t		 arglen;
	int		 ambiguous;

	/* A NULL argument means the current session. */
	if (arg == NULL)
		return (cmd_current_session(ctx));
	tmparg = xstrdup(arg);

	/* Trim a single trailing colon if any. */
	arglen = strlen(tmparg);
	if (arglen != 0 && tmparg[arglen - 1] == ':')
		tmparg[arglen - 1] = '\0';

	/* Find the session, if any. */
	s = cmd_lookup_session(tmparg, &ambiguous);

	/* If it doesn't, try to match it as a client. */
	if (s == NULL && (c = cmd_lookup_client(tmparg)) != NULL)
		s = c->session;

	/* If no session found, report an error. */
	if (s == NULL) {
		if (ambiguous)
			ctx->error(ctx, "more than one session: %s", tmparg);
		else
			ctx->error(ctx, "session not found: %s", tmparg);
	}

	xfree(tmparg);
	return (s);
}

/* Find the target session and window or report an error and return NULL. */
struct winlink *
cmd_find_window(struct cmd_ctx *ctx, const char *arg, struct session **sp)
{
	struct session	*s;
	struct winlink	*wl;
	const char	*winptr;
	char		*sessptr = NULL;
	int		 ambiguous = 0;

	/*
	 * Find the current session. There must always be a current session, if
	 * it can't be found, report an error.
	 */
	if ((s = cmd_current_session(ctx)) == NULL) {
		ctx->error(ctx, "can't establish current session");
		return (NULL);
	}

	/* A NULL argument means the current session and window. */
	if (arg == NULL) {
		if (sp != NULL)
			*sp = s;
		return (s->curw);
	}

	/* Time to look at the argument. If it is empty, that is an error. */
	if (*arg == '\0')
		goto not_found;

	/* Find the separating colon and split into window and session. */
	winptr = strchr(arg, ':');
	if (winptr == NULL)
		goto no_colon;
	winptr++;	/* skip : */
	sessptr = xstrdup(arg);
	*strchr(sessptr, ':') = '\0';

	/* Try to lookup the session if present. */
	if (*sessptr != '\0') {
		if ((s = cmd_lookup_session(sessptr, &ambiguous)) == NULL)
			goto no_session;
	}
	if (sp != NULL)
		*sp = s;

	/*
	 * Then work out the window. An empty string is the current window,
	 * otherwise try special cases then to look it up in the session.
	 */
	if (*winptr == '\0')
		wl = s->curw;
	else if (winptr[0] == '!' && winptr[1] == '\0')
		wl = TAILQ_FIRST(&s->lastw);
	else if (winptr[0] == '+' || winptr[0] == '-')
		wl = cmd_find_window_offset(winptr, s, &ambiguous);
	else
		wl = cmd_lookup_window(s, winptr, &ambiguous);
	if (wl == NULL)
		goto not_found;

	if (sessptr != NULL)
		xfree(sessptr);
	return (wl);

no_colon:
	/*
	 * No colon in the string, first try special cases, then as a window
	 * and lastly as a session.
	 */
	if (arg[0] == '!' && arg[1] == '\0') {
		if ((wl = TAILQ_FIRST(&s->lastw)) == NULL)
			goto not_found;
	} else if (arg[0] == '+' || arg[0] == '-') {
		if ((wl = cmd_find_window_offset(arg, s, &ambiguous)) == NULL)
			goto lookup_session;
	} else if ((wl = cmd_lookup_window(s, arg, &ambiguous)) == NULL)
		goto lookup_session;

	if (sp != NULL)
		*sp = s;

	return (wl);

lookup_session:
	if (ambiguous)
		goto not_found;
	if ((s = cmd_lookup_session(arg, &ambiguous)) == NULL)
		goto no_session;

	if (sp != NULL)
		*sp = s;

	return (s->curw);

no_session:
	if (ambiguous)
		ctx->error(ctx, "multiple sessions: %s", arg);
	else
		ctx->error(ctx, "session not found: %s", arg);
	if (sessptr != NULL)
		xfree(sessptr);
	return (NULL);

not_found:
	if (ambiguous)
		ctx->error(ctx, "multiple windows: %s", arg);
	else
		ctx->error(ctx, "window not found: %s", arg);
	if (sessptr != NULL)
		xfree(sessptr);
	return (NULL);
}

struct winlink *
cmd_find_window_offset(const char *winptr, struct session *s, int *ambiguous)
{
	struct winlink	*wl;
	int		 offset = 1;

	if (winptr[1] != '\0')
		offset = strtonum(winptr + 1, 1, INT_MAX, NULL);
	if (offset == 0)
		wl = cmd_lookup_window(s, winptr, ambiguous);
	else {
		if (winptr[0] == '+')
			wl = winlink_next_by_number(s->curw, s, offset);
		else
			wl = winlink_previous_by_number(s->curw, s, offset);
	}

	return (wl);
}

/*
 * Find the target session and window index, whether or not it exists in the
 * session. Return -2 on error or -1 if no window index is specified. This is
 * used when parsing an argument for a window target that may not exist (for
 * example if it is going to be created).
 */
int
cmd_find_index(struct cmd_ctx *ctx, const char *arg, struct session **sp)
{
	struct session	*s;
	struct winlink	*wl;
	const char	*winptr;
	char		*sessptr = NULL;
	int		 idx, ambiguous = 0;

	/*
	 * Find the current session. There must always be a current session, if
	 * it can't be found, report an error.
	 */
	if ((s = cmd_current_session(ctx)) == NULL) {
		ctx->error(ctx, "can't establish current session");
		return (-2);
	}

	/* A NULL argument means the current session and "no window" (-1). */
	if (arg == NULL) {
		if (sp != NULL)
			*sp = s;
		return (-1);
	}

	/* Time to look at the argument. If it is empty, that is an error. */
	if (*arg == '\0')
		goto not_found;

	/* Find the separating colon. If none, assume the current session. */
	winptr = strchr(arg, ':');
	if (winptr == NULL)
		goto no_colon;
	winptr++;	/* skip : */
	sessptr = xstrdup(arg);
	*strchr(sessptr, ':') = '\0';

	/* Try to lookup the session if present. */
	if (sessptr != NULL && *sessptr != '\0') {
		if ((s = cmd_lookup_session(sessptr, &ambiguous)) == NULL)
			goto no_session;
	}
	if (sp != NULL)
		*sp = s;

	/*
	 * Then work out the window. An empty string is a new window otherwise
	 * try to look it up in the session.
	 */
	if (*winptr == '\0')
		idx = -1;
	else if (winptr[0] == '!' && winptr[1] == '\0') {
		if ((wl = TAILQ_FIRST(&s->lastw)) == NULL)
			goto not_found;
		idx = wl->idx;
	} else if (winptr[0] == '+' || winptr[0] == '-') {
		if ((idx = cmd_find_index_offset(winptr, s, &ambiguous)) < 0)
			goto invalid_index;
	} else if ((idx = cmd_lookup_index(s, winptr, &ambiguous)) == -1)
		goto invalid_index;

	if (sessptr != NULL)
		xfree(sessptr);
	return (idx);

no_colon:
	/*
	 * No colon in the string, first try special cases, then as a window
	 * and lastly as a session.
	 */
	if (arg[0] == '!' && arg[1] == '\0') {
		if ((wl = TAILQ_FIRST(&s->lastw)) == NULL)
			goto not_found;
		idx = wl->idx;
	} else if (arg[0] == '+' || arg[0] == '-') {
		if ((idx = cmd_find_index_offset(arg, s, &ambiguous)) < 0)
			goto lookup_session;
	} else if ((idx = cmd_lookup_index(s, arg, &ambiguous)) == -1)
		goto lookup_session;

	if (sp != NULL)
		*sp = s;

	return (idx);

lookup_session:
	if (ambiguous)
		goto not_found;
	if ((s = cmd_lookup_session(arg, &ambiguous)) == NULL)
		goto no_session;

	if (sp != NULL)
		*sp = s;

	return (-1);

no_session:
	if (ambiguous)
		ctx->error(ctx, "multiple sessions: %s", arg);
	else
		ctx->error(ctx, "session not found: %s", arg);
	if (sessptr != NULL)
		xfree(sessptr);
	return (-2);

invalid_index:
	if (ambiguous)
		goto not_found;
	ctx->error(ctx, "invalid index: %s", arg);

	if (sessptr != NULL)
		xfree(sessptr);
	return (-2);

not_found:
	if (ambiguous)
		ctx->error(ctx, "multiple windows: %s", arg);
	else
		ctx->error(ctx, "window not found: %s", arg);
	if (sessptr != NULL)
		xfree(sessptr);
	return (-2);
}

int
cmd_find_index_offset(const char *winptr, struct session *s, int *ambiguous)
{
	int	idx, offset = 1;

	if (winptr[1] != '\0')
		offset = strtonum(winptr + 1, 1, INT_MAX, NULL);
	if (offset == 0)
		idx = cmd_lookup_index(s, winptr, ambiguous);
	else {
		if (winptr[0] == '+') {
			if (s->curw->idx == INT_MAX)
				idx = cmd_lookup_index(s, winptr, ambiguous);
			else
				idx = s->curw->idx + offset;
		} else {
			if (s->curw->idx == 0)
				idx = cmd_lookup_index(s, winptr, ambiguous);
			else
				idx = s->curw->idx - offset;
		}
	}

	return (idx);
}

/*
 * Find the target session, window and pane number or report an error and
 * return NULL. The pane number is separated from the session:window by a .,
 * such as mysession:mywindow.0.
 */
struct winlink *
cmd_find_pane(struct cmd_ctx *ctx,
    const char *arg, struct session **sp, struct window_pane **wpp)
{
	struct session		*s;
	struct winlink		*wl;
	struct layout_cell	*lc;
	const char		*period, *errstr;
	char			*winptr, *paneptr;
	u_int			 idx;

	/* Get the current session. */
	if ((s = cmd_current_session(ctx)) == NULL) {
		ctx->error(ctx, "can't establish current session");
		return (NULL);
	}
	if (sp != NULL)
		*sp = s;

	/* A NULL argument means the current session, window and pane. */
	if (arg == NULL) {
		*wpp = s->curw->window->active;
		return (s->curw);
	}

	/* Look for a separating period. */
	if ((period = strrchr(arg, '.')) == NULL)
		goto no_period;

	/* Pull out the window part and parse it. */
	winptr = xstrdup(arg);
	winptr[period - arg] = '\0';
	if (*winptr == '\0')
		wl = s->curw;
	else if ((wl = cmd_find_window(ctx, winptr, sp)) == NULL)
		goto error;

	/* Find the pane section and look it up. */
	paneptr = winptr + (period - arg) + 1;
	if (*paneptr == '\0')
		*wpp = wl->window->active;
	else if (paneptr[0] == '+' || paneptr[0] == '-')
		*wpp = cmd_find_pane_offset(paneptr, wl);
	else {
		idx = strtonum(paneptr, 0, INT_MAX, &errstr);
		if (errstr != NULL)
			goto lookup_string;
		*wpp = window_pane_at_index(wl->window, idx);
		if (*wpp == NULL)
			goto lookup_string;
	}

	xfree(winptr);
	return (wl);

lookup_string:
	/* Try pane string description. */
	if ((lc = layout_find_string(wl->window, paneptr)) == NULL) {
		ctx->error(ctx, "can't find pane: %s", paneptr);
		goto error;
	}
	*wpp = lc->wp;

	xfree(winptr);
	return (wl);

no_period:
	/* Try as a pane number alone. */
	idx = strtonum(arg, 0, INT_MAX, &errstr);
	if (errstr != NULL)
		goto lookup_window;

	/* Try index in the current session and window. */
	if ((*wpp = window_pane_at_index(s->curw->window, idx)) == NULL)
		goto lookup_window;

	return (s->curw);

lookup_window:
	/* Try pane string description. */
	if ((lc = layout_find_string(s->curw->window, arg)) != NULL) {
		*wpp = lc->wp;
		return (s->curw);
	}

	/* Try as a window and use the active pane. */
	if ((wl = cmd_find_window(ctx, arg, sp)) != NULL)
		*wpp = wl->window->active;
	return (wl);

error:
	xfree(winptr);
	return (NULL);
}

struct window_pane *
cmd_find_pane_offset(const char *paneptr, struct winlink *wl)
{
	struct window		*w = wl->window;
	struct window_pane	*wp = w->active;
	u_int			 offset = 1;

	if (paneptr[1] != '\0')
		offset = strtonum(paneptr + 1, 1, INT_MAX, NULL);
	if (offset > 0) {
		if (paneptr[0] == '+')
			wp = window_pane_next_by_number(w, wp, offset);
		else
			wp = window_pane_previous_by_number(w, wp, offset);
	}

	return (wp);
}

/* Replace the first %% or %idx in template by s. */
char *
cmd_template_replace(char *template, const char *s, int idx)
{
	char	 ch;
	char	*buf, *ptr;
	int	 replaced;
	size_t	 len;

	if (strstr(template, "%") == NULL)
		return (xstrdup(template));

	buf = xmalloc(1);
	*buf = '\0';
	len = 0;
	replaced = 0;

	ptr = template;
	while (*ptr != '\0') {
		switch (ch = *ptr++) {
		case '%':
			if (*ptr < '1' || *ptr > '9' || *ptr - '0' != idx) {
				if (*ptr != '%' || replaced)
					break;
				replaced = 1;
			}
			ptr++;

			len += strlen(s);
			buf = xrealloc(buf, 1, len + 1);
			strlcat(buf, s, len + 1);
			continue;
		}
		buf = xrealloc(buf, 1, len + 2);
		buf[len++] = ch;
		buf[len] = '\0';
	}

	return (buf);
}