libtmux 0.1.0-alpha.3

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
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
//! Pane handles and their snapshot getters.

use std::ffi::{OsStr, 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;
use crate::internal::options;
#[cfg(feature = "query")]
use crate::query::Filterable;
use crate::snapshot::PaneProjection;
#[cfg(feature = "query")]
use crate::snapshot::{PaneFields, PaneInfo};
use crate::target::{PaneId, ServerIdentity, SessionId, WindowId};
use crate::window::Window;
use crate::{Command, Error, ObjectKind, OptionValue};

/// One tmux pane, as reached through one window link.
///
/// A pane belongs to exactly one window, but that window can be linked into
/// several sessions. The handle retains the link it was discovered through so
/// traversal back up the hierarchy lands where the caller came from.
#[derive(Clone)]
pub struct Pane {
    core: Arc<Core>,
    projection: PaneProjection,
}

impl Pane {
    /// Build a handle from a hydrated projection.
    pub(crate) const fn new(core: Arc<Core>, projection: PaneProjection) -> Self {
        Self { core, projection }
    }

    /// Find the pane this process is running in.
    ///
    /// tmux sets `TMUX_PANE` in every process it starts, so a program running
    /// inside a pane can locate itself without being told which one it is.
    /// Pair it with [`crate::Server::from_env`], which reads the server from
    /// the same place.
    ///
    /// `Ok(None)` means tmux no longer has that pane, which is possible when
    /// the value came from an environment that outlived it.
    ///
    /// # Errors
    ///
    /// Returns an error when `TMUX_PANE` is absent or is not a pane ID, or
    /// when the pane listing fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::Pane;
    ///
    /// let session = server.new_session("locating").await?;
    /// let expected = session.try_panes().await?.remove(0);
    ///
    /// // Standing in for the environment tmux gives a process it starts.
    /// let found = Pane::from_env_value(server, Some(expected.id().as_ref())).await?;
    ///
    /// assert_eq!(found.expect("the pane exists").id(), expected.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 pane from an explicit `TMUX_PANE` value.
    ///
    /// # Errors
    ///
    /// Returns an error when the value is absent or is not a pane ID, or when
    /// the pane listing fails.
    pub async fn from_env_value(
        server: &crate::Server,
        value: Option<impl AsRef<OsStr>>,
    ) -> Result<Option<Self>, Error> {
        server
            .pane_by_id(&parse_env_id(value.as_ref().map(AsRef::as_ref))?)
            .await
    }

    /// Return the tmux pane identity.
    #[must_use]
    pub const fn id(&self) -> &PaneId {
        self.projection.pane().pane_id()
    }

    /// Return the window that contains this pane.
    #[must_use]
    pub const fn window_id(&self) -> &WindowId {
        self.projection.link_identity().window_id()
    }

    /// Return the session this handle reached the pane through.
    ///
    /// A pane reached through a linked window can report a different session
    /// depending on which link discovery followed.
    #[must_use]
    pub const fn session_id(&self) -> &SessionId {
        self.projection.link_identity().session_id()
    }

    /// Return the pane's index within its window.
    #[must_use]
    pub fn index(&self) -> u32 {
        *self.projection.pane().pane_index()
    }

    /// Return the command currently running in the pane.
    #[must_use]
    pub fn current_command(&self) -> Option<&TmuxText> {
        self.projection.pane().pane_current_command().available()
    }

    /// Return the pane's working directory.
    #[must_use]
    pub fn current_path(&self) -> Option<&TmuxText> {
        self.projection.pane().pane_current_path().available()
    }

    /// Return the pane title.
    #[must_use]
    pub fn title(&self) -> &TmuxText {
        self.projection.pane().pane_title()
    }

    /// Return the pane's controlling terminal.
    #[must_use]
    pub fn tty(&self) -> &TmuxText {
        self.projection.pane().pane_tty()
    }

    /// Return the process id of the pane's foreground process.
    #[must_use]
    pub fn pid(&self) -> u32 {
        *self.projection.pane().pane_pid()
    }

    /// Return the pane width in cells.
    #[must_use]
    pub fn width(&self) -> u32 {
        *self.projection.pane().pane_width()
    }

    /// Return the pane height in cells.
    #[must_use]
    pub fn height(&self) -> u32 {
        *self.projection.pane().pane_height()
    }

    /// Report whether this pane is the active one in its window.
    #[must_use]
    pub fn is_active(&self) -> bool {
        *self.projection.pane().pane_active()
    }

    /// Report whether the pane's process has exited while the pane remains.
    ///
    /// This is only observable when `remain-on-exit` keeps the pane open.
    #[must_use]
    pub fn is_dead(&self) -> bool {
        *self.projection.pane().pane_dead()
    }

    /// Report whether the pane is in copy mode or another pane mode.
    ///
    /// tmux reports this as a count rather than a flag, so any nonzero value
    /// means the pane has a mode open.
    #[must_use]
    pub fn is_in_mode(&self) -> bool {
        *self.projection.pane().pane_in_mode() > 0
    }

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

    /// Replace this handle's snapshot with the pane's current state.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when the pane no longer exists, or a
    /// listing error when tmux could not be read.
    pub async fn refresh(&mut self) -> Result<&mut Self, Error> {
        let target = self.id().to_string();
        let projection = listing::panes(&self.core, listing::Scope::Target(&target), None)
            .await?
            .into_iter()
            .find(|projection| projection.pane().pane_id() == self.id())
            .ok_or_else(|| Error::ObjectGone {
                kind: ObjectKind::Pane,
                id: self.id().to_string(),
            })?;

        self.projection = projection;
        Ok(self)
    }

    /// Return a new handle holding the pane's current state.
    ///
    /// # Errors
    ///
    /// Returns [`Error::ObjectGone`] when the pane 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)
    }

    /// Return the window that contains this pane.
    ///
    /// This re-reads tmux, so a window renamed or moved since discovery is
    /// reported as it is now. `Ok(None)` means the window no longer exists.
    ///
    /// # Errors
    ///
    /// Returns an error when the window listing fails.
    pub async fn window(&self) -> Result<Option<Window>, Error> {
        let session = self.session_id().to_string();

        Ok(
            listing::windows(&self.core, listing::Scope::Target(&session), None)
                .await?
                .into_iter()
                .find(|projection| projection.window().window_id() == self.window_id())
                .map(|projection| Window::new(Arc::clone(&self.core), projection)),
        )
    }

    /// Watch what this pane writes, as it writes it.
    ///
    /// [`Pane::capture`] reads what is on screen now; this reports every byte
    /// the pane produces from here on, including what scrolls away. It opens a
    /// control-mode connection to the pane's session and keeps it, so there is
    /// no polling and no sampling interval to get wrong.
    ///
    /// The bytes are the pane's own, terminal escapes included. tmux reports
    /// them in whatever sized chunks it has, so a caller wanting lines has to
    /// buffer.
    ///
    /// tmux discards what a pane has buffered when the pane exits, so a
    /// command that writes and returns immediately may be reported as nothing
    /// at all.
    ///
    /// # Errors
    ///
    /// Returns an error when the control-mode connection cannot be opened.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn watch(pane: &libtmux::Pane) -> Result<(), libtmux::Error> {
    /// let mut output = pane.stream_output().await?;
    ///
    /// while let Some(chunk) = output.next_chunk().await {
    ///     println!("{} bytes", chunk.len());
    /// }
    ///
    /// output.shutdown().await
    /// # }
    /// ```
    #[cfg(feature = "control-mode")]
    pub async fn stream_output(&self) -> Result<crate::control::PaneOutput, Error> {
        let server = crate::Server::from_core(Arc::clone(&self.core));
        let (_, events) = crate::control::ControlMode::attach(&server, self.session_id())
            .await?
            .split();

        Ok(crate::control::PaneOutput::new(self.id().clone(), events))
    }

    /// Split this pane, putting a new one beside it.
    ///
    /// [`Window::split`] divides whichever pane is active; this divides the
    /// one you name, which is what building a layout needs.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the split, which includes a pane
    /// too small to divide.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::{PaneSize, SplitDirection, SplitOptions};
    ///
    /// let session = server.new_session("split-from-pane").await?;
    /// let pane = session.try_panes().await?.remove(0);
    ///
    /// let above = pane
    ///     .split(
    ///         SplitOptions::new(SplitDirection::Above)
    ///             .size(PaneSize::Percent(30))
    ///             .command("sleep 300"),
    ///     )
    ///     .await?;
    ///
    /// assert_ne!(above.id(), pane.id());
    /// assert_eq!(above.window_id(), pane.window_id());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn split(&self, options: impl Into<crate::SplitOptions>) -> Result<Self, Error> {
        let options = options.into();
        let pane = self.id().to_string();
        let projection =
            listing::create_pane(&self.core, |format| options.into_command(&pane, format)).await?;

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

    /// Move one edge of the pane by a number of cells.
    ///
    /// This is the form a keybinding uses: "two rows taller" rather than a
    /// size computed from the current one. A pane that is alone in its window
    /// has no edge to move, and tmux accepts the request without doing
    /// anything.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the resize.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::{ResizeDirection, SplitDirection, SplitOptions};
    ///
    /// let session = server.new_session("resized-pane").await?;
    /// let pane = session.try_panes().await?.remove(0);
    /// pane.split(SplitOptions::new(SplitDirection::Below).command("sleep 300")).await?;
    ///
    /// let mut pane = pane.refreshed().await?;
    /// let before = pane.height();
    /// pane.resize_by(ResizeDirection::Down, 2).await?;
    ///
    /// assert_eq!(pane.height(), before + 2);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resize_by(
        &mut self,
        direction: crate::ResizeDirection,
        cells: u32,
    ) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "resize-pane",
            Command::new("resize-pane")
                .arg("-t")
                .arg(self.id().to_string())
                .arg(direction.flag())
                .arg(cells.to_string()),
        )
        .await?;

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

    /// Zoom the pane to fill its window, or restore it if it already fills it.
    ///
    /// tmux models this as one toggle rather than two operations, and
    /// [`Window::is_zoomed`] reports which way it went.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the request.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::{SplitDirection, SplitOptions};
    ///
    /// let session = server.new_session("zoomed").await?;
    /// let pane = session.try_panes().await?.remove(0);
    /// pane.split(SplitOptions::new(SplitDirection::Below).command("sleep 300")).await?;
    ///
    /// let mut pane = pane.refreshed().await?;
    /// pane.toggle_zoom().await?;
    /// assert!(pane.window().await?.expect("the window").is_zoomed());
    ///
    /// pane.toggle_zoom().await?;
    /// assert!(!pane.window().await?.expect("the window").is_zoomed());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn toggle_zoom(&mut self) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "resize-pane",
            Command::new("resize-pane")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-Z"),
        )
        .await?;

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

    /// Send keys to the pane as if typed.
    ///
    /// The text is sent literally with tmux's `-l` flag, so key names such as
    /// `C-c` are typed rather than interpreted. Use [`Pane::send_key_names`]
    /// for tmux's key vocabulary.
    ///
    /// The text is marked sensitive, so it never reaches `Debug`, an error, or
    /// a tracing span: a pane is where passwords get typed.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn send_keys(&self, keys: impl Into<OsString>) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "send-keys",
            Command::new("send-keys")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-l")
                .sensitive_arg(keys.into()),
        )
        .await
    }

    /// Send tmux key names, such as `C-c` or `Enter`.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux does not recognize a key name.
    pub async fn send_key_names<I, K>(&self, keys: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = K>,
        K: Into<OsString>,
    {
        let mut command = Command::new("send-keys")
            .arg("-t")
            .arg(self.id().to_string());
        for key in keys {
            command = command.arg(key.into());
        }

        listing::mutate(&self.core, "send-keys", command).await
    }

    /// Capture the pane's visible contents, one entry per line.
    ///
    /// Lines are [`TmuxText`] because a terminal's contents are arbitrary
    /// bytes, not guaranteed UTF-8.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn capture(&self) -> Result<Vec<TmuxText>, Error> {
        self.capture_with(CaptureOptions::visible()).await
    }

    /// Read the pane's contents, choosing how much and in what form.
    ///
    /// [`Pane::capture`] reads the visible screen. This reaches into
    /// scrollback, which is where the output a caller is looking for has
    /// usually gone by the time anyone asks.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the capture, which includes a pane
    /// that has been closed.
    ///
    /// # Examples
    ///
    /// ```
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::CaptureOptions;
    ///
    /// let session = server.new_session("captured").await?;
    /// let pane = session.try_panes().await?.remove(0);
    ///
    /// let visible = pane.capture_with(CaptureOptions::visible()).await?;
    /// let everything = pane.capture_with(CaptureOptions::history()).await?;
    /// assert!(everything.len() >= visible.len());
    ///
    /// let last_ten = pane.capture_with(CaptureOptions::visible().start(-10)).await?;
    /// assert!(last_ten.len() >= visible.len());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn capture_with(&self, options: CaptureOptions) -> Result<Vec<TmuxText>, Error> {
        let command = options.into_command(self.id().as_ref());
        let target = command.target().map(OsStr::to_os_string);
        let result = self.core.execute(command).await?;
        if !result.success() {
            return Err(Error::refused(
                "capture-pane",
                result.exit_code(),
                result.stderr_lossy().into_owned(),
                target.as_deref(),
            ));
        }

        // tmux terminates every line, including the last, so a trailing empty
        // element after the final newline is framing rather than content.
        let stdout = result.stdout();
        let stdout = stdout.strip_suffix(b"\n").unwrap_or(stdout);
        if stdout.is_empty() {
            return Ok(Vec::new());
        }

        Ok(stdout
            .split(|byte| *byte == b'\n')
            .map(|line| TmuxText::from(line.to_vec()))
            .collect())
    }

    /// Make this pane active in its window.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn select(&mut self) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "select-pane",
            Command::new("select-pane")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await?;

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

    /// Resize the pane to an exact size in cells.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the size.
    pub async fn resize(&mut self, width: u32, height: u32) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "resize-pane",
            Command::new("resize-pane")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-x")
                .arg(width.to_string())
                .arg("-y")
                .arg(height.to_string()),
        )
        .await?;

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

    /// Kill the pane.
    ///
    /// This consumes the handle. Killing a window's last pane closes the
    /// window.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn kill(self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "kill-pane",
            Command::new("kill-pane")
                .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::Pane(&target), name).await
    }

    /// List the option names set at this pane'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::Pane(&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::Pane(&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::Pane(&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::Pane(&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::Pane(&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::Pane(&target), name).await
    }

    /// Set the pane's title.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the title.
    pub async fn set_title(&mut self, title: impl Into<OsString>) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "select-pane",
            Command::new("select-pane")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-T")
                .sensitive_arg(title.into()),
        )
        .await?;

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

    /// Clear the pane's scrollback history.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn clear_history(&self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "clear-history",
            Command::new("clear-history")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Paste a buffer's contents into the pane.
    ///
    /// Passing `None` pastes the most recent buffer.
    ///
    /// # Errors
    ///
    /// Returns an error when no such buffer exists.
    pub async fn paste_buffer(&self, name: Option<&str>) -> Result<(), Error> {
        let mut command = Command::new("paste-buffer")
            .arg("-t")
            .arg(self.id().to_string());
        if let Some(name) = name {
            command = command.arg("-b").arg(OsString::from(name));
        }

        listing::mutate(&self.core, "paste-buffer", command).await
    }

    /// Pipe the pane's output to a shell command.
    ///
    /// Passing `None` stops any pipe already running for this pane.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn pipe(&self, command: Option<impl Into<OsString>>) -> Result<(), Error> {
        let mut pipe = Command::new("pipe-pane")
            .arg("-t")
            .arg(self.id().to_string());
        if let Some(command) = command {
            pipe = pipe.sensitive_arg(command.into());
        }

        listing::mutate(&self.core, "pipe-pane", pipe).await
    }

    /// Restart the pane's command in place.
    ///
    /// Passing `None` reruns whatever the pane started with.
    ///
    /// # Errors
    ///
    /// Returns an error when the pane is still running and `kill` is not set.
    pub async fn respawn(
        &mut self,
        command: Option<impl Into<OsString>>,
        kill: bool,
    ) -> Result<&mut Self, Error> {
        let mut respawn = Command::new("respawn-pane")
            .arg("-t")
            .arg(self.id().to_string());
        if kill {
            respawn = respawn.arg("-k");
        }
        if let Some(command) = command {
            respawn = respawn.arg(command.into());
        }

        listing::mutate(&self.core, "respawn-pane", respawn).await?;
        self.refresh().await?;
        Ok(self)
    }

    /// Swap this pane's position with another.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the swap.
    pub async fn swap_with(&mut self, other: &Self) -> Result<&mut Self, Error> {
        listing::mutate(
            &self.core,
            "swap-pane",
            Command::new("swap-pane")
                .arg("-s")
                .arg(self.id().to_string())
                .arg("-t")
                .arg(other.id().to_string()),
        )
        .await?;

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

    /// Move this pane out into a window of its own.
    ///
    /// This consumes the handle, because the pane's window changes and any
    /// snapshot of its old position is now wrong.
    ///
    /// # Errors
    ///
    /// Returns an error when the pane is its window's only one, since tmux
    /// has nothing to break it out of.
    pub async fn break_out(self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "break-pane",
            Command::new("break-pane")
                .arg("-d")
                .arg("-s")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Enter copy mode.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn copy_mode(&self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "copy-mode",
            Command::new("copy-mode")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Leave copy mode or any other pane mode.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn exit_mode(&self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "send-keys",
            Command::new("send-keys")
                .arg("-t")
                .arg(self.id().to_string())
                .arg("-X")
                .arg("cancel"),
        )
        .await
    }

    /// Show the clock in this pane.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn clock_mode(&self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "clock-mode",
            Command::new("clock-mode")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .await
    }

    /// Send the configured prefix key to the pane.
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command.
    pub async fn send_prefix(&self) -> Result<(), Error> {
        listing::mutate(
            &self.core,
            "send-prefix",
            Command::new("send-prefix")
                .arg("-t")
                .arg(self.id().to_string()),
        )
        .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::Pane(&target), name)
                .await?
                .map(|value| OptionValue::decode(name, value)),
        )
    }
}

/// Panes compare by server endpoint and pane id.
///
/// Unlike [`Window`](crate::Window), the discovery link is not part of pane
/// identity: a pane exists in exactly one window, so two handles with the same
/// pane id name the same pane however they were reached.
impl PartialEq for Pane {
    fn eq(&self, other: &Self) -> bool {
        self.server_identity() == other.server_identity() && self.id() == other.id()
    }
}

impl Eq for Pane {}

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

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

/// Filtering a pane 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
/// [`Pane`] so the type a listing returns is the type an expression
/// filters.
#[cfg(feature = "query")]
impl Filterable for Pane {
    type Fields = PaneFields<Self>;

    const FILTER_TARGET: &'static str = <PaneInfo 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.projection.pane().__filter_matches(predicate)
    }

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

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

/// How far back a capture reaches, and in what form.
///
/// Line numbers follow tmux: zero is the top of the visible screen, negative
/// numbers are scrollback, and positive numbers run down the screen.
#[must_use = "options describe a capture but do not perform one"]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct CaptureOptions {
    start: Option<CaptureBound>,
    end: Option<CaptureBound>,
    escape_sequences: bool,
    join_wrapped: bool,
}

impl CaptureOptions {
    /// Capture the visible screen, which is what tmux does by default.
    pub const fn visible() -> Self {
        Self {
            start: None,
            end: None,
            escape_sequences: false,
            join_wrapped: false,
        }
    }

    /// Capture everything tmux still holds, scrollback included.
    pub const fn history() -> Self {
        Self {
            start: Some(CaptureBound::Limit),
            ..Self::visible()
        }
    }

    /// Start the capture at a line.
    pub const fn start(mut self, line: i32) -> Self {
        self.start = Some(CaptureBound::Line(line));
        self
    }

    /// End the capture at a line.
    pub const fn end(mut self, line: i32) -> Self {
        self.end = Some(CaptureBound::Line(line));
        self
    }

    /// Keep the terminal escape sequences rather than the text alone.
    pub const fn escape_sequences(mut self) -> Self {
        self.escape_sequences = true;
        self
    }

    /// Return a wrapped line as one line rather than as the rows it occupies.
    pub const fn join_wrapped(mut self) -> Self {
        self.join_wrapped = true;
        self
    }

    /// Lower these options into a `capture-pane` command for one pane.
    fn into_command(self, pane: &str) -> Command {
        let mut command = Command::new("capture-pane").arg("-p").arg("-t").arg(pane);
        if let Some(start) = self.start {
            command = command.arg("-S").arg(start.to_string());
        }
        if let Some(end) = self.end {
            command = command.arg("-E").arg(end.to_string());
        }
        if self.escape_sequences {
            command = command.arg("-e");
        }
        if self.join_wrapped {
            command = command.arg("-J");
        }
        command
    }
}

/// One end of a capture range.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
enum CaptureBound {
    /// tmux's `-`: as far as the history goes in that direction.
    Limit,
    /// A line number.
    Line(i32),
}

impl fmt::Display for CaptureBound {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Limit => formatter.write_str("-"),
            Self::Line(line) => write!(formatter, "{line}"),
        }
    }
}

/// Read a pane ID out of an environment value tmux set.
///
/// An absent or malformed value is the same failure a caller cares about:
/// this process was not started by tmux, or not by this tmux.
fn parse_env_id(value: Option<&OsStr>) -> Result<PaneId, Error> {
    value
        .and_then(|value| value.to_str())
        .and_then(|value| value.parse().ok())
        .ok_or_else(|| {
            Error::invalid_server_configuration(crate::ServerConfigurationErrorKind::NotInsideTmux)
        })
}