libtmux 0.1.0-alpha.1

Async typed tmux client and object model
Documentation
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
//! Session handles and their snapshot getters.

use std::ffi::OsString;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use crate::formats::TmuxText;
use crate::internal::core::Core;
use crate::internal::listing::{self, Pushdown as _};
use crate::internal::options;
use crate::pane::Pane;
use crate::query::Filterable;
use crate::snapshot::{SessionFields, SessionInfo};
use crate::target::{ServerIdentity, SessionId};
use crate::window::Window;
use crate::{Command, Error, ObjectKind, OptionValue};

/// One tmux session, together with the snapshot it was discovered with.
///
/// A `Session` is cheap to clone and shares its connection with the [`Server`]
/// that produced it, but owns its snapshot outright. Cloning therefore does
/// not share observed state: refreshing one clone leaves the others as they
/// were.
///
/// Getters are synchronous because they read the owned snapshot. Anything that
/// consults tmux is `async`.
///
/// [`Server`]: crate::Server
#[derive(Clone)]
pub struct Session {
    core: Arc<Core>,
    info: SessionInfo,
}

impl Session {
    /// Build a handle from a hydrated snapshot.
    pub(crate) const fn new(core: Arc<Core>, info: SessionInfo) -> Self {
        Self { core, info }
    }

    /// Find the session this process is running in.
    ///
    /// Resolved through the pane, because `TMUX_PANE` names exactly one pane
    /// while a server's `TMUX` value names the session that was current when
    /// the client attached, which may since have changed.
    ///
    /// `Ok(None)` means tmux no longer has that pane.
    ///
    /// # Errors
    ///
    /// Returns an error when `TMUX_PANE` is absent or is not a pane ID, or
    /// when the listing fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::{Pane, Session};
    ///
    /// let session = server.new_session("locating-session").await?;
    /// let pane = session.try_panes().await?.remove(0);
    ///
    /// // Standing in for the environment tmux gives a process it starts.
    /// let found = Session::from_env_value(server, Some(pane.id().as_ref())).await?;
    ///
    /// assert_eq!(found.expect("the session exists").id(), session.id());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_env(server: &crate::Server) -> Result<Option<Self>, Error> {
        Self::from_env_value(server, std::env::var_os("TMUX_PANE")).await
    }

    /// Find a session from an explicit `TMUX_PANE` value.
    ///
    /// # Errors
    ///
    /// Returns an error when the value is absent or is not a pane ID, or when
    /// the listing fails.
    pub async fn from_env_value(
        server: &crate::Server,
        value: Option<impl AsRef<std::ffi::OsStr>>,
    ) -> Result<Option<Self>, Error> {
        let Some(pane) = Pane::from_env_value(server, value).await? else {
            return Ok(None);
        };

        server.session_by_id(pane.session_id()).await
    }

    /// Return the tmux session identity.
    ///
    /// This is the `$`-prefixed id tmux assigns, which is stable across
    /// renames. It is always present.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
    /// # runtime.block_on(async {
    /// # use libtmux::Command;
    /// # let socket = std::env::temp_dir().join("libtmux-doc-session-id.sock");
    /// let server = libtmux::Server::builder().socket_path(&socket).build()?;
    /// # let _ = server.cmd(Command::new("kill-server")).await;
    /// # server.cmd(Command::new("new-session").arg("-d").arg("sleep 60")).await?;
    /// let session = server.sessions().await.into_iter().next().expect("one session");
    /// assert!(session.id().to_string().starts_with('$'));
    /// # let _ = server.cmd(Command::new("kill-server")).await;
    /// # server.shutdown().await?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// # })?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn id(&self) -> &SessionId {
        self.info.session_id()
    }

    /// Return the session name.
    ///
    /// Names are byte-preserving: tmux permits bytes that are not valid UTF-8,
    /// so this is [`TmuxText`] rather than `str`.
    #[must_use]
    pub fn name(&self) -> &TmuxText {
        self.info.session_name()
    }

    /// Return the session's working directory.
    #[must_use]
    pub fn path(&self) -> &TmuxText {
        self.info.session_path()
    }

    /// Return how many windows the session contains.
    #[must_use]
    pub fn window_count(&self) -> u32 {
        *self.info.session_windows()
    }

    /// Return how many clients are attached to the session.
    #[must_use]
    pub fn attached_client_count(&self) -> u32 {
        *self.info.session_attached()
    }

    /// Report whether any client is attached.
    ///
    /// A session tmux has never reported on is treated as unattached.
    #[must_use]
    pub fn is_attached(&self) -> bool {
        self.attached_client_count() > 0
    }

    /// Return when the session was created, as a Unix timestamp.
    #[must_use]
    pub fn created(&self) -> i64 {
        *self.info.session_created()
    }

    /// Return when a client last attached, as a Unix timestamp.
    ///
    /// This is `None` for a session that has never been attached, which is the
    /// ordinary state for one started with `new-session -d`.
    #[must_use]
    pub fn last_attached(&self) -> Option<i64> {
        self.info.session_last_attached().copied().available()
    }

    /// Return the identity of the server this session belongs to.
    #[must_use]
    pub(crate) fn server_identity(&self) -> &ServerIdentity {
        self.core.configuration().identity()
    }

    /// List the windows linked into this session, in tmux's own order.
    ///
    /// This is the lenient form; use [`Session::try_windows`] when the reason
    /// for an empty result matters.
    pub async fn windows(&self) -> Vec<Window> {
        self.try_windows().await.unwrap_or_default()
    }

    /// List the windows linked into this session, preserving any failure.
    ///
    /// A window linked into other sessions appears here once, under this
    /// session's own index for it.
    ///
    /// # Errors
    ///
    /// Returns an error when the list command cannot run, or when its output
    /// cannot be decoded into snapshots.
    pub async fn try_windows(&self) -> Result<Vec<Window>, Error> {
        let target = self.id().to_string();
        let projections =
            listing::windows(&self.core, listing::Scope::Target(&target), None).await?;

        Ok(projections
            .into_iter()
            .map(|projection| Window::new(Arc::clone(&self.core), projection))
            .collect())
    }

    /// Return the session's active window.
    ///
    /// # Errors
    ///
    /// Returns an error when the window listing fails. A session always has an
    /// active window, so `Ok(None)` means the session disappeared between the
    /// snapshot and this call.
    pub async fn active_window(&self) -> Result<Option<Window>, Error> {
        Ok(self
            .try_windows()
            .await?
            .into_iter()
            .find(Window::is_active))
    }

    /// List every pane in this session, in tmux's own order.
    ///
    /// This is the lenient form; use [`Session::try_panes`] when the reason
    /// for an empty result matters.
    pub async fn panes(&self) -> Vec<Pane> {
        self.try_panes().await.unwrap_or_default()
    }

    /// List every pane in this session, preserving any failure.
    ///
    /// # Errors
    ///
    /// Returns an error when the list command cannot run, or when its output
    /// cannot be decoded into snapshots.
    pub async fn try_panes(&self) -> Result<Vec<Pane>, Error> {
        let target = self.id().to_string();
        let projections =
            listing::panes(&self.core, listing::Scope::SessionTarget(&target), None).await?;

        Ok(projections
            .into_iter()
            .map(|projection| Pane::new(Arc::clone(&self.core), projection))
            .collect())
    }
    /// Replace this handle's snapshot with the session's current state.
    ///
    /// Only the receiver changes. Clones keep the snapshot they were taken
    /// with, because each handle owns its own.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when the session no longer exists, or a
    /// listing error when tmux could not be read.
    pub async fn refresh(&mut self) -> Result<&mut Self, Error> {
        let info = listing::sessions(&self.core, None)
            .await?
            .into_iter()
            .find(|info| info.session_id() == self.id())
            .ok_or_else(|| Error::ObjectGone {
                kind: ObjectKind::Session,
                id: self.id().to_string(),
            })?;

        self.info = info;
        Ok(self)
    }

    /// Return a new handle holding the session's current state.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when the session no longer exists, or a
    /// listing error when tmux could not be read.
    pub async fn refreshed(&self) -> Result<Self, Error> {
        let mut refreshed = self.clone();
        refreshed.refresh().await?;
        Ok(refreshed)
    }

    /// Create a window in this session and return it.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command or its output cannot be
    /// decoded.
    pub async fn new_window(&self, options: impl Into<NewWindowOptions>) -> Result<Window, Error> {
        let options = options.into();
        let session = self.id().to_string();
        let projection =
            listing::create_window(&self.core, |format| options.into_command(&session, format))
                .await?;

        Ok(Window::new(Arc::clone(&self.core), projection))
    }

    /// Rename the session and update this handle.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the name, which includes one that
    /// is empty or already taken.
    pub async fn rename(&mut self, name: impl Into<OsString>) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "rename-session",
            Command::new("rename-session")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(name.into()),
        )
        .await?;

        self.refresh().await?;
        Ok(self)
    }

    /// Kill the session.
    ///
    /// This consumes the handle: every other handle to the same session is now
    /// stale, and refreshing one reports [`Error::ObjectGone`].
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn kill(self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "kill-session",
            Command::new("kill-session")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Read one option's exact stored value.
    ///
    /// A user option, whose name begins with `@`, exists only while it is
    /// set, so an unset one reports `None`. A built-in option always exists,
    /// so an unset one also reports `None`. An unrecognized built-in name is
    /// an error.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux does not recognize the option name.
    pub async fn get_option(&self, name: &str) -> Result<Option<TmuxText>, Error> {
        let target = self.id().to_string();
        options::get(&self.core, options::Scope::Session(&target), name).await
    }

    /// List the option names set at this session's scope.
    ///
    /// Values are not included: tmux renders them for display with three
    /// different quoting styles, so re-parsing them would be guesswork. Read
    /// each value with [`Self::get_option`], which returns exact bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the listing.
    pub async fn option_names(&self) -> Result<Vec<String>, Error> {
        let target = self.id().to_string();
        options::names(&self.core, options::Scope::Session(&target)).await
    }

    /// Set one option.
    ///
    /// The value is marked sensitive, so it never reaches `Debug`, an error,
    /// or a tracing span.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name or value.
    pub async fn set_option(&self, name: &str, value: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set(
            &self.core,
            options::Scope::Session(&target),
            name,
            value,
            false,
        )
        .await
    }

    /// Append to one option rather than replacing it.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name or value.
    pub async fn append_option(&self, name: &str, value: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set(
            &self.core,
            options::Scope::Session(&target),
            name,
            value,
            true,
        )
        .await
    }

    /// Remove one option, restoring whatever it inherits.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name.
    pub async fn unset_option(&self, name: &str) -> Result<(), Error> {
        let target = self.id().to_string();
        options::unset(&self.core, options::Scope::Session(&target), name).await
    }

    /// Set one hook to a tmux command.
    ///
    /// Hooks live in the same option tables, so a hook is an array option and
    /// [`Self::get_option`] reads it under an indexed name such as
    /// `after-new-window[0]`.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the hook name or command.
    pub async fn set_hook(&self, name: &str, command: impl Into<OsString>) -> Result<(), Error> {
        let target = self.id().to_string();
        options::set_hook(&self.core, options::Scope::Session(&target), name, command).await
    }

    /// Remove one hook.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the hook name.
    pub async fn unset_hook(&self, name: &str) -> Result<(), Error> {
        let target = self.id().to_string();
        options::unset_hook(&self.core, options::Scope::Session(&target), name).await
    }

    /// Create a window, run an operation with it, then kill it.
    ///
    /// The window is killed whether the operation succeeded or failed, so a
    /// short-lived task does not leave one behind. A panic still skips
    /// cleanup: `Drop` on these handles is deliberately not destructive.
    ///
    /// Setup and teardown failures convert into the operation's own error
    /// type, so a caller writes one `?` rather than unwrapping twice. When
    /// both the operation and the cleanup fail, the operation's error is
    /// returned, because that is the work the caller was doing; the discarded
    /// cleanup failure is recorded through `tracing` when that feature is on.
    ///
    /// # Errors
    ///
    /// Returns the operation's error, or a converted [`Error`] when the
    /// window could not be created, or could not be killed after the
    /// operation succeeded.
    pub async fn with_window<T, E>(
        &self,
        options: impl Into<NewWindowOptions>,
        operation: impl AsyncFnOnce(&Window) -> Result<T, E>,
    ) -> Result<T, E>
    where
        E: From<Error>,
    {
        let created = self.new_window(options).await?;
        let outcome = operation(&created).await;

        match (outcome, created.kill().await) {
            (outcome, Ok(())) => outcome,
            (Ok(_), Err(error)) => Err(error.into()),
            (Err(outcome), Err(cleanup)) => {
                listing::trace_discarded_cleanup(&cleanup);
                Err(outcome)
            }
        }
    }

    /// Set an environment variable for processes this session starts.
    ///
    /// Existing panes keep the environment they were started with; this
    /// affects what new panes inherit.
    ///
    /// The value is marked sensitive, since an environment carries tokens.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name or value.
    pub async fn set_environment(
        &self,
        name: &str,
        value: impl Into<OsString>,
    ) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "set-environment",
            Command::new("set-environment")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(OsString::from(name))
                .sensitive_arg(value.into()),
        )
        .await
    }

    /// Read one environment variable from the session.
    ///
    /// Returns `None` when the variable is unset, and `Some` holding the exact
    /// bytes otherwise. tmux marks a variable removed rather than absent, so a
    /// removed one also reports `None`.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux cannot be reached.
    pub async fn environment(&self, name: &str) -> Result<Option<TmuxText>, Error> {
        let result = self
            .core
            .execute(
                Command::new("show-environment")
                    .arg("-t")
                    .arg(self.id().to_string())
                    .arg(OsString::from(name)),
            )
            .await?;
        if !result.success() {
            return Ok(None);
        }

        // tmux prints `NAME=value`, or `-NAME` for one it has removed.
        let stdout = result.stdout();
        let line = stdout.strip_suffix(b"\n").unwrap_or(stdout);
        let Some(position) = line.iter().position(|byte| *byte == b'=') else {
            return Ok(None);
        };

        Ok(Some(TmuxText::from(line[position + 1..].to_vec())))
    }

    /// Remove an environment variable from the session.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux rejects the name.
    pub async fn unset_environment(&self, name: &str) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "set-environment",
            Command::new("set-environment")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-u")
                .arg(OsString::from(name)),
        )
        .await
    }

    /// Read one option, decoded according to what tmux declares about it.
    ///
    /// A flag comes back as [`OptionValue::Flag`] and a number as
    /// [`OptionValue::Number`], so a caller does not decide for itself that
    /// `on` means one. Everything else, including user options, stays text.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux does not recognize the option name.
    pub async fn typed_option(&self, name: &str) -> Result<Option<OptionValue>, Error> {
        let target = self.id().to_string();
        Ok(
            options::get(&self.core, options::Scope::Session(&target), name)
                .await?
                .map(|value| OptionValue::decode(name, value)),
        )
    }

    /// Find this session's window with the given name.
    ///
    /// Names are compared as bytes. A session can hold several windows with
    /// one name, in which case the first in tmux's order is returned.
    ///
    /// # Errors
    ///
    /// Returns an error when the window listing fails.
    pub async fn window(&self, name: impl AsRef<[u8]>) -> Result<Option<Window>, Error> {
        let name = name.as_ref();

        Ok(self
            .try_windows()
            .await?
            .into_iter()
            .find(|window| window.name() == name))
    }

    /// Find this session's window at the given index.
    ///
    /// # Errors
    ///
    /// Returns an error when the window listing fails.
    pub async fn window_at(&self, index: i32) -> Result<Option<Window>, Error> {
        // An index is an integer, so tmux can match it and return one row.
        let target = self.id().to_string();
        let projections = listing::windows(
            &self.core,
            listing::Scope::Target(&target),
            Some(&index.predicate("window_index")),
        )
        .await?;

        Ok(projections
            .into_iter()
            .next()
            .map(|projection| Window::new(Arc::clone(&self.core), projection)))
    }
}

/// Sessions compare by server endpoint and session id.
///
/// Equal-looking ids on different servers are different sessions, and two
/// handles for the same session remain equal even when their snapshots were
/// taken at different times.
impl PartialEq for Session {
    fn eq(&self, other: &Self) -> bool {
        self.server_identity() == other.server_identity() && self.id() == other.id()
    }
}

impl Eq for Session {}

impl Hash for Session {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.server_identity().hash(state);
        self.id().hash(state);
    }
}

/// Renders identity only, never snapshot text.
///
/// Session names can carry arbitrary bytes from the user's environment, so
/// they stay out of diagnostics.
impl fmt::Debug for Session {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Session")
            .field("id", &self.id())
            .finish_non_exhaustive()
    }
}

/// Filtering a session uses the same handles as the snapshot beneath it.
///
/// Matching and validation delegate to that snapshot, so an expression can
/// only name fields the catalog knows. The companion is re-parameterized to
/// [`Session`] so the type a listing returns is the type an expression
/// filters.
impl Filterable for Session {
    type Fields = SessionFields<Self>;

    const FILTER_TARGET: &'static str = <SessionInfo as Filterable>::FILTER_TARGET;

    fn filter_fields() -> Self::Fields {
        Self::Fields::for_target(Self::FILTER_TARGET)
    }

    fn __filter_matches(&self, predicate: &crate::query::__private::Predicate) -> bool {
        self.info.__filter_matches(predicate)
    }

    fn __filter_validate(
        predicate: &crate::query::__private::Predicate,
    ) -> Result<(), crate::query::FilterExpressionError> {
        <SessionInfo as Filterable>::__filter_validate(predicate)
    }
}

/// Options for creating a window in a session.
///
/// A bare name is accepted wherever this is: `session.new_window("editor")`.
#[must_use = "options describe a window but do not create one"]
#[derive(Clone, Debug)]
pub struct NewWindowOptions {
    name: Option<OsString>,
    start_directory: Option<std::path::PathBuf>,
    command: Option<OsString>,
    index: Option<i32>,
    placement: Option<WindowPlacement>,
    environment: Vec<(OsString, OsString)>,
    replace_existing: bool,
    select: bool,
}

/// Where a new window goes, relative to the index it is given.
///
/// Without one, tmux takes the first free index.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum WindowPlacement {
    /// Insert before the target index, shifting later windows along.
    Before,
    /// Insert after it.
    After,
}

impl NewWindowOptions {
    /// Describe a window with no name, letting tmux choose one.
    pub const fn unnamed() -> Self {
        Self {
            name: None,
            start_directory: None,
            command: None,
            index: None,
            placement: None,
            environment: Vec::new(),
            replace_existing: false,
            select: false,
        }
    }

    /// Describe a window with the given name.
    pub fn new(name: impl Into<OsString>) -> Self {
        Self {
            name: Some(name.into()),
            ..Self::unnamed()
        }
    }

    /// Set the window's working directory.
    pub fn start_directory(mut self, directory: impl Into<std::path::PathBuf>) -> Self {
        self.start_directory = Some(directory.into());
        self
    }

    /// Run a command instead of the default shell.
    pub fn command(mut self, command: impl Into<OsString>) -> Self {
        self.command = Some(command.into());
        self
    }

    /// Place the window at a window index rather than the first free one.
    pub const fn index(mut self, index: i32) -> Self {
        self.index = Some(index);
        self
    }

    /// Insert relative to the index rather than at it.
    ///
    /// Without an index this is relative to the session's current window,
    /// which is what tmux does.
    pub const fn placement(mut self, placement: WindowPlacement) -> Self {
        self.placement = Some(placement);
        self
    }

    /// Set an environment variable for the process the new window starts.
    ///
    /// Call this more than once for more than one variable. tmux applies
    /// these to the new process only, not to the session.
    pub fn environment(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
        self.environment.push((name.into(), value.into()));
        self
    }

    /// Replace whatever already occupies the target index.
    ///
    /// Without this, an index that is taken is an error rather than a silent
    /// overwrite.
    pub const fn replace_existing(mut self) -> Self {
        self.replace_existing = true;
        self
    }

    /// Make the new window active in its session.
    ///
    /// Creation does not select by default, so building a workspace does not
    /// leave the session pointing at whichever window happened to be last.
    pub const fn select(mut self) -> Self {
        self.select = true;
        self
    }

    /// Lower these options into a `new-window` command for one session.
    ///
    /// `print_format` is placed with the other flags because tmux stops
    /// parsing flags at the first positional, and the shell command is one.
    fn into_command(self, session: &str, print_format: &str) -> Command {
        let target = self
            .index
            .map_or_else(|| session.to_owned(), |index| format!("{session}:{index}"));
        let mut command = Command::new("new-window")
            .arg("-P")
            .arg("-F")
            .arg(print_format)
            .arg("-t")
            .arg(target);
        if !self.select {
            command = command.arg("-d");
        }
        match self.placement {
            Some(WindowPlacement::Before) => command = command.arg("-b"),
            Some(WindowPlacement::After) => command = command.arg("-a"),
            None => {}
        }
        if self.replace_existing {
            command = command.arg("-k");
        }
        if let Some(name) = self.name {
            command = command.arg("-n").arg(name);
        }
        if let Some(directory) = self.start_directory {
            command = command.arg("-c").arg(directory.into_os_string());
        }
        for (name, value) in self.environment {
            command = command
                .arg("-e")
                .arg(crate::window::assignment(&name, &value));
        }
        if let Some(shell_command) = self.command {
            command = command.arg(shell_command);
        }
        command
    }
}

impl<T: Into<OsString>> From<T> for NewWindowOptions {
    fn from(name: T) -> Self {
        Self::new(name)
    }
}

/// Renders the session id, which is what a tmux target wants.
impl fmt::Display for Session {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", self.id())
    }
}