Skip to main content

tmux_client/
pane.rs

1//! Pane snapshots, capture, input, splitting, resizing, and process operations.
2
3use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::path::PathBuf;
6
7use crate::{
8    BufferName, ClientName, Command, Error, ObjectKind, OptionMap, OptionScope, OptionValue,
9    PaneId, PaneSnapshot, ReleaseVersion, Result, Server, Session, SessionId, SparseOptionMap,
10    TmuxText, Window, WindowId, WindowTarget,
11};
12
13/// Orientation for a new pane.
14#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
15pub enum SplitDirection {
16    /// Stack panes from top to bottom (tmux default).
17    #[default]
18    Vertical,
19    /// Place panes side by side (`-h`).
20    Horizontal,
21}
22
23/// Initial pane size.
24#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
25pub enum PaneSize {
26    /// Exact cells in the split direction.
27    Cells(u32),
28    /// A percentage from 1 through 100.
29    Percent(u8),
30}
31
32/// Typed arguments for `split-window`.
33#[derive(Clone, Debug)]
34pub struct SplitPane {
35    direction: SplitDirection,
36    size: Option<PaneSize>,
37    detached: bool,
38    before: bool,
39    full_window: bool,
40    cwd: Option<PathBuf>,
41    shell_command: Option<OsString>,
42    environment: BTreeMap<String, OsString>,
43}
44
45/// Typed arguments for a tmux 3.7+ floating `new-pane`.
46#[derive(Clone, Debug, Default)]
47pub struct NewPane {
48    cwd: Option<PathBuf>,
49    attach: bool,
50    shell_command: Option<OsString>,
51    environment: BTreeMap<String, OsString>,
52    width: Option<u32>,
53    height: Option<u32>,
54    x: Option<i32>,
55    y: Option<i32>,
56    zoom: bool,
57    empty: bool,
58    style: Option<OsString>,
59    active_border_style: Option<OsString>,
60    inactive_border_style: Option<OsString>,
61    message: Option<OsString>,
62    keep: bool,
63}
64
65impl NewPane {
66    /// Creates default floating-pane arguments.
67    #[must_use]
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// Sets the starting directory.
73    #[must_use]
74    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
75        self.cwd = Some(cwd.into());
76        self
77    }
78
79    /// Activates the new pane instead of detaching.
80    #[must_use]
81    pub const fn attach(mut self, enabled: bool) -> Self {
82        self.attach = enabled;
83        self
84    }
85
86    /// Sets the pane shell command.
87    #[must_use]
88    pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
89        self.shell_command = Some(command.into());
90        self
91    }
92
93    /// Adds an environment entry.
94    pub fn environment(
95        mut self,
96        name: impl Into<String>,
97        value: impl Into<OsString>,
98    ) -> Result<Self> {
99        let name = name.into();
100        crate::server::validate_name("environment name", &name)?;
101        self.environment.insert(name, value.into());
102        Ok(self)
103    }
104
105    /// Sets a non-zero width in cells.
106    pub fn width(mut self, width: u32) -> Result<Self> {
107        if width == 0 {
108            return Err(Error::InvalidArgument {
109                argument: "floating pane width",
110                message: "must be non-zero".to_owned(),
111            });
112        }
113        self.width = Some(width);
114        Ok(self)
115    }
116
117    /// Sets a non-zero height in cells.
118    pub fn height(mut self, height: u32) -> Result<Self> {
119        if height == 0 {
120            return Err(Error::InvalidArgument {
121                argument: "floating pane height",
122                message: "must be non-zero".to_owned(),
123            });
124        }
125        self.height = Some(height);
126        Ok(self)
127    }
128
129    /// Sets the x coordinate.
130    #[must_use]
131    pub const fn x(mut self, x: i32) -> Self {
132        self.x = Some(x);
133        self
134    }
135
136    /// Sets the y coordinate.
137    #[must_use]
138    pub const fn y(mut self, y: i32) -> Self {
139        self.y = Some(y);
140        self
141    }
142
143    /// Zooms the new pane.
144    #[must_use]
145    pub const fn zoom(mut self, enabled: bool) -> Self {
146        self.zoom = enabled;
147        self
148    }
149
150    /// Creates an empty pane without a process.
151    #[must_use]
152    pub const fn empty(mut self, enabled: bool) -> Self {
153        self.empty = enabled;
154        self
155    }
156
157    /// Sets pane style.
158    #[must_use]
159    pub fn style(mut self, value: impl Into<OsString>) -> Self {
160        self.style = Some(value.into());
161        self
162    }
163
164    /// Sets active border style.
165    #[must_use]
166    pub fn active_border_style(mut self, value: impl Into<OsString>) -> Self {
167        self.active_border_style = Some(value.into());
168        self
169    }
170
171    /// Sets inactive border style.
172    #[must_use]
173    pub fn inactive_border_style(mut self, value: impl Into<OsString>) -> Self {
174        self.inactive_border_style = Some(value.into());
175        self
176    }
177
178    /// Sets the remain-on-exit message.
179    #[must_use]
180    pub fn message(mut self, value: impl Into<OsString>) -> Self {
181        self.message = Some(value.into());
182        self
183    }
184
185    /// Keeps the pane after its command exits.
186    #[must_use]
187    pub const fn keep(mut self, enabled: bool) -> Self {
188        self.keep = enabled;
189        self
190    }
191}
192
193impl Default for SplitPane {
194    fn default() -> Self {
195        Self {
196            direction: SplitDirection::Vertical,
197            size: None,
198            detached: true,
199            before: false,
200            full_window: false,
201            cwd: None,
202            shell_command: None,
203            environment: BTreeMap::new(),
204        }
205    }
206}
207
208impl SplitPane {
209    /// Creates detached split arguments.
210    #[must_use]
211    pub fn new() -> Self {
212        Self::default()
213    }
214
215    /// Sets the split orientation.
216    #[must_use]
217    pub const fn direction(mut self, direction: SplitDirection) -> Self {
218        self.direction = direction;
219        self
220    }
221
222    /// Sets an exact cell size.
223    pub fn cells(mut self, cells: u32) -> Result<Self> {
224        if cells == 0 {
225            return Err(Error::InvalidArgument {
226                argument: "pane size",
227                message: "cell count must be non-zero".to_owned(),
228            });
229        }
230        self.size = Some(PaneSize::Cells(cells));
231        Ok(self)
232    }
233
234    /// Sets a percentage size.
235    pub fn percent(mut self, percent: u8) -> Result<Self> {
236        if !(1..=100).contains(&percent) {
237            return Err(Error::InvalidArgument {
238                argument: "pane percentage",
239                message: "must be between 1 and 100".to_owned(),
240            });
241        }
242        self.size = Some(PaneSize::Percent(percent));
243        Ok(self)
244    }
245
246    /// Chooses whether the new pane remains detached.
247    #[must_use]
248    pub const fn detached(mut self, detached: bool) -> Self {
249        self.detached = detached;
250        self
251    }
252
253    /// Inserts the new pane before the target.
254    #[must_use]
255    pub const fn before(mut self, before: bool) -> Self {
256        self.before = before;
257        self
258    }
259
260    /// Splits across the full window instead of only the target pane.
261    #[must_use]
262    pub const fn full_window(mut self, full_window: bool) -> Self {
263        self.full_window = full_window;
264        self
265    }
266
267    /// Sets the starting directory.
268    #[must_use]
269    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
270        self.cwd = Some(cwd.into());
271        self
272    }
273
274    /// Sets the shell command for the new pane.
275    #[must_use]
276    pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
277        self.shell_command = Some(command.into());
278        self
279    }
280
281    /// Adds a pane environment variable. Values are redacted in diagnostics.
282    pub fn environment(
283        mut self,
284        name: impl Into<String>,
285        value: impl Into<OsString>,
286    ) -> Result<Self> {
287        let name = name.into();
288        crate::server::validate_name("environment name", &name)?;
289        self.environment.insert(name, value.into());
290        Ok(self)
291    }
292}
293
294/// Direction for relative pane resizing.
295#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
296pub enum ResizeDirection {
297    /// Resize the left edge.
298    Left,
299    /// Resize the right edge.
300    Right,
301    /// Resize the top edge.
302    Up,
303    /// Resize the bottom edge.
304    Down,
305}
306
307/// A pane or window that can receive a moved or joined pane.
308#[derive(Clone, Debug, Eq, Hash, PartialEq)]
309pub enum PaneDestination {
310    /// Position relative to a target pane.
311    Pane(PaneId),
312    /// Position in a target window.
313    Window(WindowTarget),
314}
315
316impl std::fmt::Display for PaneDestination {
317    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        match self {
319            Self::Pane(id) => id.fmt(formatter),
320            Self::Window(target) => target.fmt(formatter),
321        }
322    }
323}
324
325impl From<PaneId> for PaneDestination {
326    fn from(value: PaneId) -> Self {
327        Self::Pane(value)
328    }
329}
330
331impl From<WindowTarget> for PaneDestination {
332    fn from(value: WindowTarget) -> Self {
333        Self::Window(value)
334    }
335}
336
337impl From<WindowId> for PaneDestination {
338    fn from(value: WindowId) -> Self {
339        Self::Window(value.into())
340    }
341}
342
343/// Typed placement arguments shared by `move-pane` and `join-pane`.
344#[derive(Clone, Debug, Eq, PartialEq)]
345pub struct RelocatePane {
346    destination: PaneDestination,
347    direction: SplitDirection,
348    detached: bool,
349    full_window: bool,
350    size: Option<PaneSize>,
351    before: bool,
352}
353
354/// Relative direction for `swap-pane`.
355#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
356pub enum SwapPaneDirection {
357    /// Swap with the previous pane (`-U`).
358    Up,
359    /// Swap with the next pane (`-D`).
360    Down,
361}
362
363/// Typed arguments for `swap-pane`.
364#[derive(Clone, Debug, Default, Eq, PartialEq)]
365pub struct SwapPane {
366    destination: Option<PaneId>,
367    direction: Option<SwapPaneDirection>,
368    detached: bool,
369    keep_zoom: bool,
370}
371
372impl SwapPane {
373    /// Creates a default swap request.
374    #[must_use]
375    pub fn new() -> Self {
376        Self::default()
377    }
378
379    /// Selects an explicit destination pane.
380    #[must_use]
381    pub const fn destination(mut self, pane: PaneId) -> Self {
382        self.destination = Some(pane);
383        self
384    }
385
386    /// Selects a relative pane.
387    #[must_use]
388    pub const fn direction(mut self, direction: SwapPaneDirection) -> Self {
389        self.direction = Some(direction);
390        self
391    }
392
393    /// Prevents selection changes.
394    #[must_use]
395    pub const fn detached(mut self, enabled: bool) -> Self {
396        self.detached = enabled;
397        self
398    }
399
400    /// Preserves zoom.
401    #[must_use]
402    pub const fn keep_zoom(mut self, enabled: bool) -> Self {
403        self.keep_zoom = enabled;
404        self
405    }
406}
407
408impl RelocatePane {
409    /// Creates default detached, vertical placement arguments.
410    #[must_use]
411    pub fn new(destination: impl Into<PaneDestination>) -> Self {
412        Self {
413            destination: destination.into(),
414            direction: SplitDirection::Vertical,
415            detached: true,
416            full_window: false,
417            size: None,
418            before: false,
419        }
420    }
421
422    /// Sets the split direction.
423    #[must_use]
424    pub const fn direction(mut self, direction: SplitDirection) -> Self {
425        self.direction = direction;
426        self
427    }
428
429    /// Prevents tmux from selecting the destination window.
430    #[must_use]
431    pub const fn detached(mut self, detached: bool) -> Self {
432        self.detached = detached;
433        self
434    }
435
436    /// Splits across the full destination window.
437    #[must_use]
438    pub const fn full_window(mut self, enabled: bool) -> Self {
439        self.full_window = enabled;
440        self
441    }
442
443    /// Sets an exact cell size.
444    pub fn cells(mut self, cells: u32) -> Result<Self> {
445        if cells == 0 {
446            return Err(Error::InvalidArgument {
447                argument: "relocated pane size",
448                message: "cell count must be non-zero".to_owned(),
449            });
450        }
451        self.size = Some(PaneSize::Cells(cells));
452        Ok(self)
453    }
454
455    /// Sets a percentage size.
456    pub fn percent(mut self, percent: u8) -> Result<Self> {
457        if !(1..=100).contains(&percent) {
458            return Err(Error::InvalidArgument {
459                argument: "relocated pane percentage",
460                message: "must be between 1 and 100".to_owned(),
461            });
462        }
463        self.size = Some(PaneSize::Percent(percent));
464        Ok(self)
465    }
466
467    /// Places this pane before the destination.
468    #[must_use]
469    pub const fn before(mut self, enabled: bool) -> Self {
470        self.before = enabled;
471        self
472    }
473}
474
475impl ResizeDirection {
476    pub(crate) fn flag(self) -> &'static str {
477        match self {
478            Self::Left => "-L",
479            Self::Right => "-R",
480            Self::Up => "-U",
481            Self::Down => "-D",
482        }
483    }
484}
485
486/// Typed arguments for byte-preserving pane capture.
487#[derive(Clone, Debug, Default, Eq, PartialEq)]
488pub struct CapturePane {
489    start: Option<CaptureLine>,
490    end: Option<CaptureLine>,
491    alternate: bool,
492    escape_sequences: bool,
493    escape_non_printable: bool,
494    join_wrapped: bool,
495    preserve_trailing: bool,
496    trim_trailing: bool,
497    quiet: bool,
498    mode_screen: bool,
499    pending: bool,
500    hyperlinks: bool,
501    line_numbers: bool,
502    line_flags: bool,
503}
504
505/// A numbered capture line or tmux's `-` history/screen boundary.
506#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
507pub enum CaptureLine {
508    /// A visible-screen or history line number.
509    Number(i64),
510    /// The beginning of history for `-S`, or end of the visible screen for `-E`.
511    Boundary,
512}
513
514impl std::fmt::Display for CaptureLine {
515    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516        match self {
517            Self::Number(line) => line.fmt(formatter),
518            Self::Boundary => formatter.write_str("-"),
519        }
520    }
521}
522
523impl CapturePane {
524    /// Creates capture arguments for the visible pane.
525    #[must_use]
526    pub fn new() -> Self {
527        Self::default()
528    }
529
530    /// Sets the first history line. Negative values address history.
531    #[must_use]
532    pub const fn start(mut self, line: i64) -> Self {
533        self.start = Some(CaptureLine::Number(line));
534        self
535    }
536
537    /// Starts at the beginning of pane history.
538    #[must_use]
539    pub const fn start_of_history(mut self) -> Self {
540        self.start = Some(CaptureLine::Boundary);
541        self
542    }
543
544    /// Sets the last history line.
545    #[must_use]
546    pub const fn end(mut self, line: i64) -> Self {
547        self.end = Some(CaptureLine::Number(line));
548        self
549    }
550
551    /// Ends at the bottom of the visible pane.
552    #[must_use]
553    pub const fn end_of_screen(mut self) -> Self {
554        self.end = Some(CaptureLine::Boundary);
555        self
556    }
557
558    /// Captures the alternate screen.
559    #[must_use]
560    pub const fn alternate(mut self, enabled: bool) -> Self {
561        self.alternate = enabled;
562        self
563    }
564
565    /// Includes terminal escape sequences.
566    #[must_use]
567    pub const fn escape_sequences(mut self, enabled: bool) -> Self {
568        self.escape_sequences = enabled;
569        self
570    }
571
572    /// Escapes non-printable bytes using tmux's octal representation (`-C`).
573    #[must_use]
574    pub const fn escape_non_printable(mut self, enabled: bool) -> Self {
575        self.escape_non_printable = enabled;
576        self
577    }
578
579    /// Joins wrapped lines.
580    #[must_use]
581    pub const fn join_wrapped(mut self, enabled: bool) -> Self {
582        self.join_wrapped = enabled;
583        self
584    }
585
586    /// Preserves trailing spaces.
587    #[must_use]
588    pub const fn preserve_trailing(mut self, enabled: bool) -> Self {
589        self.preserve_trailing = enabled;
590        self
591    }
592
593    /// Trims unused trailing cells (`-T`). Requires tmux 3.4+.
594    #[must_use]
595    pub const fn trim_trailing(mut self, enabled: bool) -> Self {
596        self.trim_trailing = enabled;
597        self
598    }
599
600    /// Suppresses capture errors (`-q`).
601    #[must_use]
602    pub const fn quiet(mut self, enabled: bool) -> Self {
603        self.quiet = enabled;
604        self
605    }
606
607    /// Captures the active mode screen (`-M`). Requires tmux 3.6+.
608    #[must_use]
609    pub const fn mode_screen(mut self, enabled: bool) -> Self {
610        self.mode_screen = enabled;
611        self
612    }
613
614    /// Includes pending output.
615    #[must_use]
616    pub const fn pending(mut self, enabled: bool) -> Self {
617        self.pending = enabled;
618        self
619    }
620
621    /// Captures hyperlink targets (`-H`). Requires tmux 3.7+.
622    #[must_use]
623    pub const fn hyperlinks(mut self, enabled: bool) -> Self {
624        self.hyperlinks = enabled;
625        self
626    }
627
628    /// Prefixes captured lines with line numbers (`-L`). Requires tmux 3.7+.
629    #[must_use]
630    pub const fn line_numbers(mut self, enabled: bool) -> Self {
631        self.line_numbers = enabled;
632        self
633    }
634
635    /// Prefixes captured lines with line flags (`-F`). Requires tmux 3.7+.
636    #[must_use]
637    pub const fn line_flags(mut self, enabled: bool) -> Self {
638        self.line_flags = enabled;
639        self
640    }
641}
642
643/// Typed arguments for `send-keys`.
644#[derive(Clone, Debug, Default, Eq, PartialEq)]
645pub struct SendKeys {
646    keys: Vec<OsString>,
647    literal: bool,
648    hexadecimal: bool,
649    reset: bool,
650    repeat: Option<u32>,
651    enter: bool,
652    suppress_history: bool,
653    copy_mode_command: Option<OsString>,
654    expand_formats: bool,
655    target_client: Option<ClientName>,
656    key_name: bool,
657    sensitive: bool,
658}
659
660/// Typed arguments for `select-pane`.
661#[derive(Clone, Debug, Default, Eq, PartialEq)]
662pub struct SelectPane {
663    direction: Option<ResizeDirection>,
664    last: bool,
665    keep_zoom: bool,
666    mark: bool,
667    clear_mark: bool,
668    input: Option<bool>,
669}
670
671impl SelectPane {
672    /// Creates a direct pane-selection request.
673    #[must_use]
674    pub fn new() -> Self {
675        Self::default()
676    }
677
678    /// Selects the neighboring pane in a direction.
679    #[must_use]
680    pub const fn direction(mut self, direction: ResizeDirection) -> Self {
681        self.direction = Some(direction);
682        self
683    }
684
685    /// Selects the previously active pane.
686    #[must_use]
687    pub const fn last(mut self, enabled: bool) -> Self {
688        self.last = enabled;
689        self
690    }
691
692    /// Preserves the window's zoom state.
693    #[must_use]
694    pub const fn keep_zoom(mut self, enabled: bool) -> Self {
695        self.keep_zoom = enabled;
696        self
697    }
698
699    /// Marks the selected pane.
700    #[must_use]
701    pub const fn mark(mut self, enabled: bool) -> Self {
702        self.mark = enabled;
703        self
704    }
705
706    /// Clears the marked pane.
707    #[must_use]
708    pub const fn clear_mark(mut self, enabled: bool) -> Self {
709        self.clear_mark = enabled;
710        self
711    }
712
713    /// Enables (`Some(true)`) or disables (`Some(false)`) pane input.
714    #[must_use]
715    pub const fn input(mut self, enabled: Option<bool>) -> Self {
716        self.input = enabled;
717        self
718    }
719}
720
721/// Typed arguments for `paste-buffer`.
722#[derive(Clone, Debug, Default, Eq, PartialEq)]
723pub struct PasteBuffer {
724    name: Option<BufferName>,
725    delete_after: bool,
726    linefeed_separator: bool,
727    bracketed: bool,
728    separator: Option<OsString>,
729    raw: bool,
730}
731
732impl PasteBuffer {
733    /// Creates arguments for tmux's most recent buffer.
734    #[must_use]
735    pub fn new() -> Self {
736        Self::default()
737    }
738
739    /// Selects a named buffer.
740    #[must_use]
741    pub fn name(mut self, name: BufferName) -> Self {
742        self.name = Some(name);
743        self
744    }
745
746    /// Deletes the buffer after pasting.
747    #[must_use]
748    pub const fn delete_after(mut self, enabled: bool) -> Self {
749        self.delete_after = enabled;
750        self
751    }
752
753    /// Uses line feed rather than carriage return between lines.
754    #[must_use]
755    pub const fn linefeed_separator(mut self, enabled: bool) -> Self {
756        self.linefeed_separator = enabled;
757        self
758    }
759
760    /// Uses bracketed paste mode.
761    #[must_use]
762    pub const fn bracketed(mut self, enabled: bool) -> Self {
763        self.bracketed = enabled;
764        self
765    }
766
767    /// Sets an explicit line separator.
768    #[must_use]
769    pub fn separator(mut self, separator: impl Into<OsString>) -> Self {
770        self.separator = Some(separator.into());
771        self
772    }
773
774    /// Disables tmux `vis(3)` escaping. Requires tmux 3.7+.
775    #[must_use]
776    pub const fn raw(mut self, enabled: bool) -> Self {
777        self.raw = enabled;
778        self
779    }
780}
781
782/// Typed arguments for `pipe-pane`.
783#[derive(Clone, Debug, Default, Eq, PartialEq)]
784pub struct PipePane {
785    command: Option<OsString>,
786    output_only: bool,
787    input_only: bool,
788    toggle: bool,
789}
790
791impl PipePane {
792    /// Creates a request that disables an existing pipe.
793    #[must_use]
794    pub fn new() -> Self {
795        Self::default()
796    }
797
798    /// Sets the shell command. It is redacted in diagnostics.
799    #[must_use]
800    pub fn command(mut self, command: impl Into<OsString>) -> Self {
801        self.command = Some(command.into());
802        self
803    }
804
805    /// Pipes pane output only (`-O`).
806    #[must_use]
807    pub const fn output_only(mut self, enabled: bool) -> Self {
808        self.output_only = enabled;
809        self
810    }
811
812    /// Pipes pane input only (`-I`).
813    #[must_use]
814    pub const fn input_only(mut self, enabled: bool) -> Self {
815        self.input_only = enabled;
816        self
817    }
818
819    /// Toggles the pipe (`-o`).
820    #[must_use]
821    pub const fn toggle(mut self, enabled: bool) -> Self {
822        self.toggle = enabled;
823        self
824    }
825}
826
827/// Typed arguments for `copy-mode`.
828#[derive(Clone, Debug, Default, Eq, PartialEq)]
829pub struct CopyMode {
830    scroll_up: bool,
831    exit_on_bottom: bool,
832    mouse_drag: bool,
833    cancel: bool,
834    page_down: bool,
835    source: Option<PaneId>,
836}
837
838impl CopyMode {
839    /// Creates default copy-mode arguments.
840    #[must_use]
841    pub fn new() -> Self {
842        Self::default()
843    }
844
845    /// Starts one page up.
846    #[must_use]
847    pub const fn scroll_up(mut self, enabled: bool) -> Self {
848        self.scroll_up = enabled;
849        self
850    }
851
852    /// Exits when scrolling reaches the bottom.
853    #[must_use]
854    pub const fn exit_on_bottom(mut self, enabled: bool) -> Self {
855        self.exit_on_bottom = enabled;
856        self
857    }
858
859    /// Starts mouse drag.
860    #[must_use]
861    pub const fn mouse_drag(mut self, enabled: bool) -> Self {
862        self.mouse_drag = enabled;
863        self
864    }
865
866    /// Cancels active modes.
867    #[must_use]
868    pub const fn cancel(mut self, enabled: bool) -> Self {
869        self.cancel = enabled;
870        self
871    }
872
873    /// Scrolls a page down. Requires tmux 3.5+.
874    #[must_use]
875    pub const fn page_down(mut self, enabled: bool) -> Self {
876        self.page_down = enabled;
877        self
878    }
879
880    /// Displays another pane's history.
881    #[must_use]
882    pub const fn source(mut self, source: PaneId) -> Self {
883        self.source = Some(source);
884        self
885    }
886}
887
888/// Sort field used by the tree chooser.
889#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
890pub enum TreeSort {
891    /// Window/session index.
892    Index,
893    /// Name.
894    Name,
895    /// Activity time.
896    Time,
897    /// Size.
898    Size,
899}
900
901impl TreeSort {
902    fn as_str(self) -> &'static str {
903        match self {
904            Self::Index => "index",
905            Self::Name => "name",
906            Self::Time => "time",
907            Self::Size => "size",
908        }
909    }
910}
911
912/// Typed arguments for `choose-tree`.
913#[derive(Clone, Debug, Default, Eq, PartialEq)]
914pub struct ChooseTree {
915    sessions_collapsed: bool,
916    windows_collapsed: bool,
917    format: Option<OsString>,
918    native_filter: Option<OsString>,
919    sort: Option<TreeSort>,
920    reverse: bool,
921    zoom: bool,
922}
923
924impl ChooseTree {
925    /// Creates default chooser arguments.
926    #[must_use]
927    pub fn new() -> Self {
928        Self::default()
929    }
930
931    /// Starts with sessions collapsed.
932    #[must_use]
933    pub const fn sessions_collapsed(mut self, enabled: bool) -> Self {
934        self.sessions_collapsed = enabled;
935        self
936    }
937
938    /// Starts with windows collapsed.
939    #[must_use]
940    pub const fn windows_collapsed(mut self, enabled: bool) -> Self {
941        self.windows_collapsed = enabled;
942        self
943    }
944
945    /// Sets the row format.
946    #[must_use]
947    pub fn format(mut self, value: impl Into<OsString>) -> Self {
948        self.format = Some(value.into());
949        self
950    }
951
952    /// Sets a raw tmux item filter.
953    #[must_use]
954    pub fn native_filter(mut self, value: impl Into<OsString>) -> Self {
955        self.native_filter = Some(value.into());
956        self
957    }
958
959    /// Sets the sort field.
960    #[must_use]
961    pub const fn sort(mut self, sort: TreeSort) -> Self {
962        self.sort = Some(sort);
963        self
964    }
965
966    /// Reverses sorting.
967    #[must_use]
968    pub const fn reverse(mut self, enabled: bool) -> Self {
969        self.reverse = enabled;
970        self
971    }
972
973    /// Zooms the pane while choosing.
974    #[must_use]
975    pub const fn zoom(mut self, enabled: bool) -> Self {
976        self.zoom = enabled;
977        self
978    }
979}
980
981/// Typed arguments for `find-window`.
982#[derive(Clone, Debug, Eq, PartialEq)]
983pub struct FindWindow {
984    pattern: OsString,
985    content: bool,
986    case_insensitive: bool,
987    name_only: bool,
988    regex: bool,
989    title: bool,
990}
991
992impl FindWindow {
993    /// Creates a search request.
994    #[must_use]
995    pub fn new(pattern: impl Into<OsString>) -> Self {
996        Self {
997            pattern: pattern.into(),
998            content: false,
999            case_insensitive: false,
1000            name_only: false,
1001            regex: false,
1002            title: false,
1003        }
1004    }
1005
1006    /// Searches visible pane content.
1007    #[must_use]
1008    pub const fn content(mut self, enabled: bool) -> Self {
1009        self.content = enabled;
1010        self
1011    }
1012
1013    /// Uses case-insensitive matching.
1014    #[must_use]
1015    pub const fn case_insensitive(mut self, enabled: bool) -> Self {
1016        self.case_insensitive = enabled;
1017        self
1018    }
1019
1020    /// Matches window names only.
1021    #[must_use]
1022    pub const fn name_only(mut self, enabled: bool) -> Self {
1023        self.name_only = enabled;
1024        self
1025    }
1026
1027    /// Treats the pattern as a regular expression.
1028    #[must_use]
1029    pub const fn regex(mut self, enabled: bool) -> Self {
1030        self.regex = enabled;
1031        self
1032    }
1033
1034    /// Matches pane titles.
1035    #[must_use]
1036    pub const fn title(mut self, enabled: bool) -> Self {
1037        self.title = enabled;
1038        self
1039    }
1040}
1041
1042/// Typed arguments for `respawn-pane`.
1043#[derive(Clone, Debug, Default)]
1044pub struct RespawnPane {
1045    shell_command: Option<OsString>,
1046    cwd: Option<PathBuf>,
1047    environment: BTreeMap<String, OsString>,
1048    kill: bool,
1049}
1050
1051impl RespawnPane {
1052    /// Creates default respawn arguments.
1053    #[must_use]
1054    pub fn new() -> Self {
1055        Self::default()
1056    }
1057
1058    /// Sets the replacement shell command.
1059    #[must_use]
1060    pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
1061        self.shell_command = Some(command.into());
1062        self
1063    }
1064
1065    /// Sets the replacement working directory.
1066    #[must_use]
1067    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
1068        self.cwd = Some(cwd.into());
1069        self
1070    }
1071
1072    /// Adds an environment entry.
1073    pub fn environment(
1074        mut self,
1075        name: impl Into<String>,
1076        value: impl Into<OsString>,
1077    ) -> Result<Self> {
1078        let name = name.into();
1079        crate::server::validate_name("environment name", &name)?;
1080        self.environment.insert(name, value.into());
1081        Ok(self)
1082    }
1083
1084    /// Kills a still-running process before replacement.
1085    #[must_use]
1086    pub const fn kill(mut self, enabled: bool) -> Self {
1087        self.kill = enabled;
1088        self
1089    }
1090}
1091
1092impl SendKeys {
1093    /// Creates an empty key sequence.
1094    #[must_use]
1095    pub const fn new() -> Self {
1096        Self {
1097            keys: Vec::new(),
1098            literal: false,
1099            hexadecimal: false,
1100            reset: false,
1101            repeat: None,
1102            enter: false,
1103            suppress_history: false,
1104            copy_mode_command: None,
1105            expand_formats: false,
1106            target_client: None,
1107            key_name: false,
1108            sensitive: false,
1109        }
1110    }
1111
1112    /// Adds one key name or literal string.
1113    #[must_use]
1114    pub fn key(mut self, key: impl Into<OsString>) -> Self {
1115        self.keys.push(key.into());
1116        self
1117    }
1118
1119    /// Adds multiple key names.
1120    #[must_use]
1121    pub fn keys<I, S>(mut self, keys: I) -> Self
1122    where
1123        I: IntoIterator<Item = S>,
1124        S: Into<OsString>,
1125    {
1126        self.keys.extend(keys.into_iter().map(Into::into));
1127        self
1128    }
1129
1130    /// Sends input literally (`-l`).
1131    #[must_use]
1132    pub const fn literal(mut self, enabled: bool) -> Self {
1133        self.literal = enabled;
1134        self
1135    }
1136
1137    /// Treats each key as hexadecimal (`-H`).
1138    #[must_use]
1139    pub const fn hexadecimal(mut self, enabled: bool) -> Self {
1140        self.hexadecimal = enabled;
1141        self
1142    }
1143
1144    /// Resets terminal state before sending input (`-R`).
1145    #[must_use]
1146    pub const fn reset(mut self, enabled: bool) -> Self {
1147        self.reset = enabled;
1148        self
1149    }
1150
1151    /// Repeats the sequence a non-zero number of times.
1152    pub fn repeat(mut self, count: u32) -> Result<Self> {
1153        if count == 0 {
1154            return Err(Error::InvalidArgument {
1155                argument: "send-keys repeat",
1156                message: "must be non-zero".to_owned(),
1157            });
1158        }
1159        self.repeat = Some(count);
1160        Ok(self)
1161    }
1162
1163    /// Appends an Enter key after the input sequence.
1164    #[must_use]
1165    pub const fn enter(mut self, enabled: bool) -> Self {
1166        self.enter = enabled;
1167        self
1168    }
1169
1170    /// Sends a leading space before input so shells configured accordingly omit it from history.
1171    #[must_use]
1172    pub const fn suppress_history(mut self, enabled: bool) -> Self {
1173        self.suppress_history = enabled;
1174        self
1175    }
1176
1177    /// Sends a command to copy mode (`-X`) instead of ordinary keys.
1178    #[must_use]
1179    pub fn copy_mode_command(mut self, command: impl Into<OsString>) -> Self {
1180        self.copy_mode_command = Some(command.into());
1181        self
1182    }
1183
1184    /// Expands tmux formats in the supplied keys (`-F`).
1185    #[must_use]
1186    pub const fn expand_formats(mut self, enabled: bool) -> Self {
1187        self.expand_formats = enabled;
1188        self
1189    }
1190
1191    /// Targets an attached client (`-c`). Requires tmux 3.4+.
1192    #[must_use]
1193    pub fn target_client(mut self, client: ClientName) -> Self {
1194        self.target_client = Some(client);
1195        self
1196    }
1197
1198    /// Interprets input as key names for a target client (`-K`). Requires tmux 3.4+.
1199    #[must_use]
1200    pub const fn key_name(mut self, enabled: bool) -> Self {
1201        self.key_name = enabled;
1202        self
1203    }
1204
1205    /// Redacts input keys or the copy-mode command from command diagnostics.
1206    #[must_use]
1207    pub const fn sensitive(mut self, enabled: bool) -> Self {
1208        self.sensitive = enabled;
1209        self
1210    }
1211}
1212
1213/// A tmux pane handle with its parent identities and owned snapshot.
1214#[derive(Clone, Debug)]
1215pub struct Pane {
1216    server: Server,
1217    id: PaneId,
1218    session_id: SessionId,
1219    window_id: WindowId,
1220    snapshot: PaneSnapshot,
1221}
1222
1223impl Pane {
1224    pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
1225        let snapshot = PaneSnapshot::new(row);
1226        let id = snapshot.id()?.ok_or_else(|| Error::Decode {
1227            context: "pane row",
1228            message: "pane_id was empty".to_owned(),
1229        })?;
1230        let session_id = parse_parent_id(&snapshot, "session_id", "pane session ID")?;
1231        let window_id = parse_parent_id(&snapshot, "window_id", "pane window ID")?;
1232        Ok(Self {
1233            server,
1234            id,
1235            session_id,
1236            window_id,
1237            snapshot,
1238        })
1239    }
1240
1241    /// Resolves the pane named by `TMUX_PANE` and the socket in `TMUX`.
1242    pub async fn from_environment() -> Result<Self> {
1243        Server::from_environment()?.pane_from_environment().await
1244    }
1245
1246    /// Returns the immutable pane ID.
1247    #[must_use]
1248    pub const fn id(&self) -> PaneId {
1249        self.id
1250    }
1251
1252    /// Returns the parent session ID captured with this row.
1253    #[must_use]
1254    pub const fn session_id(&self) -> SessionId {
1255        self.session_id
1256    }
1257
1258    /// Returns the parent window ID captured with this row.
1259    #[must_use]
1260    pub const fn window_id(&self) -> WindowId {
1261        self.window_id
1262    }
1263
1264    /// Returns the owned snapshot.
1265    #[must_use]
1266    pub const fn snapshot(&self) -> &PaneSnapshot {
1267        &self.snapshot
1268    }
1269
1270    /// Returns the server handle.
1271    #[must_use]
1272    pub const fn server(&self) -> &Server {
1273        &self.server
1274    }
1275
1276    /// Replaces this object with a fresh snapshot.
1277    pub async fn refresh(&mut self) -> Result<()> {
1278        *self = self.server.pane(self.id).await?;
1279        Ok(())
1280    }
1281
1282    /// Resolves the parent session.
1283    pub async fn session(&self) -> Result<Session> {
1284        self.server.session(self.session_id).await
1285    }
1286
1287    /// Resolves the parent window link.
1288    pub async fn window(&self) -> Result<Window> {
1289        self.server
1290            .windows()
1291            .await?
1292            .into_iter()
1293            .find(|window| window.id() == self.window_id && window.session_id() == self.session_id)
1294            .ok_or_else(|| Error::ObjectNotFound {
1295                kind: ObjectKind::Window,
1296                target: format!("{} in {}", self.window_id, self.session_id),
1297            })
1298    }
1299
1300    /// Runs an arbitrary tmux command targeted at this pane.
1301    pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
1302        self.server.cmd(command.target(self.id)).await
1303    }
1304
1305    /// Creates another pane by splitting this pane.
1306    pub async fn split(&self, options: SplitPane) -> Result<Self> {
1307        let mut command = Command::new("split-window")
1308            .arg("-P")
1309            .arg("-F")
1310            .arg("#{pane_id}")
1311            .target(self.id);
1312        if options.direction == SplitDirection::Horizontal {
1313            command = command.arg("-h");
1314        }
1315        if options.detached {
1316            command = command.arg("-d");
1317        }
1318        if options.before {
1319            command = command.arg("-b");
1320        }
1321        if options.full_window {
1322            command = command.arg("-f");
1323        }
1324        if let Some(size) = options.size {
1325            match size {
1326                PaneSize::Cells(cells) => {
1327                    command = command.arg("-l").arg(cells.to_string());
1328                }
1329                PaneSize::Percent(percent) => {
1330                    command = command.arg("-p").arg(percent.to_string());
1331                }
1332            }
1333        }
1334        if let Some(cwd) = options.cwd {
1335            command = command.arg("-c").arg(cwd);
1336        }
1337        for (name, value) in options.environment {
1338            command =
1339                command
1340                    .arg("-e")
1341                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
1342        }
1343        if let Some(shell_command) = options.shell_command {
1344            command = command.sensitive_arg(shell_command);
1345        }
1346        let result = self.server.checked("split pane", command).await?;
1347        let id: PaneId =
1348            crate::server::single_line(result.stdout(), "split-window pane ID")?.parse()?;
1349        self.server.pane(id).await
1350    }
1351
1352    /// Creates a floating pane. Requires tmux 3.7+.
1353    pub async fn new_pane(&self, options: NewPane) -> Result<Self> {
1354        self.server
1355            .version()
1356            .await?
1357            .require("floating panes", ReleaseVersion::new(3, 7, None))?;
1358        let mut command = Command::new("new-pane")
1359            .arg("-P")
1360            .arg("-F")
1361            .arg("#{pane_id}")
1362            .target(self.id);
1363        if let Some(width) = options.width {
1364            command = command.arg("-x").arg(width.to_string());
1365        }
1366        if let Some(height) = options.height {
1367            command = command.arg("-y").arg(height.to_string());
1368        }
1369        if let Some(x) = options.x {
1370            command = command.arg("-X").arg(x.to_string());
1371        }
1372        if let Some(y) = options.y {
1373            command = command.arg("-Y").arg(y.to_string());
1374        }
1375        if options.zoom {
1376            command = command.arg("-Z");
1377        }
1378        if let Some(style) = options.style {
1379            command = command.arg("-s").arg(style);
1380        }
1381        if let Some(style) = options.active_border_style {
1382            command = command.arg("-S").arg(style);
1383        }
1384        if let Some(style) = options.inactive_border_style {
1385            command = command.arg("-R").arg(style);
1386        }
1387        if let Some(message) = options.message {
1388            command = command.arg("-m").arg(message);
1389        }
1390        if options.keep {
1391            command = command.arg("-k");
1392        }
1393        if let Some(cwd) = options.cwd {
1394            command = command.arg("-c").arg(cwd);
1395        }
1396        if !options.attach {
1397            command = command.arg("-d");
1398        }
1399        for (name, value) in options.environment {
1400            command =
1401                command
1402                    .arg("-e")
1403                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
1404        }
1405        if options.empty {
1406            command = command.arg("-E");
1407        }
1408        if let Some(shell_command) = options.shell_command {
1409            command = command.sensitive_arg(shell_command);
1410        }
1411        let result = self.server.checked("create floating pane", command).await?;
1412        let id: PaneId =
1413            crate::server::single_line(result.stdout(), "new-pane pane ID")?.parse()?;
1414        self.server.pane(id).await
1415    }
1416
1417    /// Selects this pane.
1418    pub async fn select(&self, enable_input: bool) -> Result<()> {
1419        self.select_with(SelectPane::new().input(enable_input.then_some(true)))
1420            .await
1421    }
1422
1423    /// Selects or marks a pane with explicit directional, zoom, and input flags.
1424    pub async fn select_with(&self, options: SelectPane) -> Result<()> {
1425        if options.direction.is_some() && options.last {
1426            return Err(Error::InvalidArgument {
1427                argument: "pane selection",
1428                message: "direction and last are mutually exclusive".to_owned(),
1429            });
1430        }
1431        if options.mark && options.clear_mark {
1432            return Err(Error::InvalidArgument {
1433                argument: "pane selection",
1434                message: "mark and clear_mark are mutually exclusive".to_owned(),
1435            });
1436        }
1437        let mut command = Command::new("select-pane");
1438        if let Some(direction) = options.direction {
1439            command = command.arg(direction.flag());
1440        }
1441        for (enabled, flag) in [
1442            (options.last, "-l"),
1443            (options.keep_zoom, "-Z"),
1444            (options.mark, "-m"),
1445            (options.clear_mark, "-M"),
1446        ] {
1447            if enabled {
1448                command = command.arg(flag);
1449            }
1450        }
1451        if let Some(input) = options.input {
1452            command = command.arg(if input { "-e" } else { "-d" });
1453        }
1454        self.server
1455            .checked("select pane", command.target(self.id))
1456            .await
1457            .map(|_| ())
1458    }
1459
1460    /// Sets the pane title.
1461    pub async fn set_title(&self, title: impl Into<OsString>) -> Result<()> {
1462        self.server
1463            .checked(
1464                "set pane title",
1465                Command::new("select-pane")
1466                    .arg("-T")
1467                    .arg(title)
1468                    .target(self.id),
1469            )
1470            .await
1471            .map(|_| ())
1472    }
1473
1474    /// Resizes one edge by a non-zero cell count.
1475    pub async fn resize(&self, direction: ResizeDirection, cells: u32) -> Result<()> {
1476        if cells == 0 {
1477            return Err(Error::InvalidArgument {
1478                argument: "resize cells",
1479                message: "must be non-zero".to_owned(),
1480            });
1481        }
1482        self.server
1483            .checked(
1484                "resize pane",
1485                Command::new("resize-pane")
1486                    .arg(direction.flag())
1487                    .arg(cells.to_string())
1488                    .target(self.id),
1489            )
1490            .await
1491            .map(|_| ())
1492    }
1493
1494    /// Sets an absolute pane width and/or height.
1495    pub async fn resize_to(&self, width: Option<u32>, height: Option<u32>) -> Result<()> {
1496        if width.is_none() && height.is_none() {
1497            return Err(Error::InvalidArgument {
1498                argument: "absolute pane size",
1499                message: "width or height is required".to_owned(),
1500            });
1501        }
1502        if width == Some(0) || height == Some(0) {
1503            return Err(Error::InvalidArgument {
1504                argument: "absolute pane size",
1505                message: "dimensions must be non-zero".to_owned(),
1506            });
1507        }
1508        let mut command = Command::new("resize-pane");
1509        if let Some(width) = width {
1510            command = command.arg("-x").arg(width.to_string());
1511        }
1512        if let Some(height) = height {
1513            command = command.arg("-y").arg(height.to_string());
1514        }
1515        self.server
1516            .checked("resize pane", command.target(self.id))
1517            .await
1518            .map(|_| ())
1519    }
1520
1521    /// Sets pane width to a percentage of the window.
1522    pub async fn resize_width_percent(&self, percent: u8) -> Result<()> {
1523        self.resize_percent("-x", percent).await
1524    }
1525
1526    /// Sets pane height to a percentage of the window.
1527    pub async fn resize_height_percent(&self, percent: u8) -> Result<()> {
1528        self.resize_percent("-y", percent).await
1529    }
1530
1531    async fn resize_percent(&self, flag: &'static str, percent: u8) -> Result<()> {
1532        if !(1..=100).contains(&percent) {
1533            return Err(Error::InvalidArgument {
1534                argument: "pane size percentage",
1535                message: "must be between 1 and 100".to_owned(),
1536            });
1537        }
1538        self.server
1539            .checked(
1540                "resize pane",
1541                Command::new("resize-pane")
1542                    .arg(flag)
1543                    .arg(format!("{percent}%"))
1544                    .target(self.id),
1545            )
1546            .await
1547            .map(|_| ())
1548    }
1549
1550    /// Resizes using tmux's current mouse event (`-M`).
1551    pub async fn resize_from_mouse(&self) -> Result<()> {
1552        self.server
1553            .checked(
1554                "resize pane from mouse",
1555                Command::new("resize-pane").arg("-M").target(self.id),
1556            )
1557            .await
1558            .map(|_| ())
1559    }
1560
1561    /// Trims lines below the current cursor (`resize-pane -T`).
1562    pub async fn trim_below(&self) -> Result<()> {
1563        self.server
1564            .checked(
1565                "trim pane below cursor",
1566                Command::new("resize-pane").arg("-T").target(self.id),
1567            )
1568            .await
1569            .map(|_| ())
1570    }
1571
1572    /// Toggles zoom for this pane's window.
1573    pub async fn toggle_zoom(&self) -> Result<()> {
1574        self.server
1575            .checked(
1576                "toggle pane zoom",
1577                Command::new("resize-pane").arg("-Z").target(self.id),
1578            )
1579            .await
1580            .map(|_| ())
1581    }
1582
1583    /// Captures pane contents without forcing UTF-8.
1584    pub async fn capture(&self, options: &CapturePane) -> Result<TmuxText> {
1585        self.validate_capture(options).await?;
1586        let command = self.capture_command(options).arg("-p");
1587        self.server
1588            .checked("capture pane", command)
1589            .await
1590            .map(|result| result.stdout().clone())
1591    }
1592
1593    /// Captures pane contents directly into a named tmux buffer.
1594    pub async fn capture_to_buffer(
1595        &self,
1596        options: &CapturePane,
1597        buffer: &BufferName,
1598    ) -> Result<()> {
1599        self.validate_capture(options).await?;
1600        self.server
1601            .checked(
1602                "capture pane to buffer",
1603                self.capture_command(options)
1604                    .arg("-b")
1605                    .arg(buffer.to_os_string()),
1606            )
1607            .await
1608            .map(|_| ())
1609    }
1610
1611    fn capture_command(&self, options: &CapturePane) -> Command {
1612        let mut command = Command::new("capture-pane").target(self.id);
1613        if let Some(start) = options.start {
1614            command = command.arg("-S").arg(start.to_string());
1615        }
1616        if let Some(end) = options.end {
1617            command = command.arg("-E").arg(end.to_string());
1618        }
1619        if options.alternate {
1620            command = command.arg("-a");
1621        }
1622        if options.escape_sequences {
1623            command = command.arg("-e");
1624        }
1625        if options.escape_non_printable {
1626            command = command.arg("-C");
1627        }
1628        if options.join_wrapped {
1629            command = command.arg("-J");
1630        }
1631        if options.preserve_trailing {
1632            command = command.arg("-N");
1633        }
1634        if options.pending {
1635            command = command.arg("-P");
1636        }
1637        if options.trim_trailing {
1638            command = command.arg("-T");
1639        }
1640        if options.quiet {
1641            command = command.arg("-q");
1642        }
1643        if options.mode_screen {
1644            command = command.arg("-M");
1645        }
1646        if options.hyperlinks {
1647            command = command.arg("-H");
1648        }
1649        if options.line_numbers {
1650            command = command.arg("-L");
1651        }
1652        if options.line_flags {
1653            command = command.arg("-F");
1654        }
1655        command
1656    }
1657
1658    async fn validate_capture(&self, options: &CapturePane) -> Result<()> {
1659        if options.trim_trailing {
1660            self.server.version().await?.require(
1661                "trim trailing capture cells",
1662                ReleaseVersion::new(3, 4, None),
1663            )?;
1664        }
1665        if options.mode_screen {
1666            self.server
1667                .version()
1668                .await?
1669                .require("capture mode screen", ReleaseVersion::new(3, 6, None))?;
1670        }
1671        if options.hyperlinks || options.line_numbers || options.line_flags {
1672            self.server
1673                .version()
1674                .await?
1675                .require("extended pane capture", ReleaseVersion::new(3, 7, None))?;
1676        }
1677        Ok(())
1678    }
1679
1680    /// Sends named keys or literal text.
1681    pub async fn send_keys(&self, options: SendKeys) -> Result<()> {
1682        let send_enter = options.enter && options.copy_mode_command.is_none();
1683        if options.keys.is_empty()
1684            && !options.reset
1685            && options.repeat.is_none()
1686            && options.copy_mode_command.is_none()
1687        {
1688            return Err(Error::InvalidArgument {
1689                argument: "send keys",
1690                message: "keys, reset, repeat, or a copy-mode command is required".to_owned(),
1691            });
1692        }
1693        if options.literal && options.hexadecimal {
1694            return Err(Error::InvalidArgument {
1695                argument: "send keys",
1696                message: "literal and hexadecimal modes are mutually exclusive".to_owned(),
1697            });
1698        }
1699        if options.copy_mode_command.is_some() && !options.keys.is_empty() {
1700            return Err(Error::InvalidArgument {
1701                argument: "send keys",
1702                message: "ordinary keys and a copy-mode command are mutually exclusive".to_owned(),
1703            });
1704        }
1705        if options.target_client.is_some() || options.key_name {
1706            self.server
1707                .version()
1708                .await?
1709                .require("client-targeted keys", ReleaseVersion::new(3, 4, None))?;
1710        }
1711        let mut command = Command::new("send-keys").target(self.id);
1712        if options.literal {
1713            command = command.arg("-l");
1714        }
1715        if options.hexadecimal {
1716            command = command.arg("-H");
1717        }
1718        if options.reset {
1719            command = command.arg("-R");
1720        }
1721        if options.expand_formats {
1722            command = command.arg("-F");
1723        }
1724        if options.key_name {
1725            command = command.arg("-K");
1726        }
1727        if let Some(client) = options.target_client {
1728            command = command.arg("-c").arg(client.to_string());
1729        }
1730        if let Some(repeat) = options.repeat {
1731            command = command.arg("-N").arg(repeat.to_string());
1732        }
1733        if let Some(copy_mode_command) = options.copy_mode_command {
1734            command = command.arg("-X");
1735            command = if options.sensitive {
1736                command.sensitive_arg(copy_mode_command)
1737            } else {
1738                command.arg(copy_mode_command)
1739            };
1740        } else {
1741            if options.suppress_history {
1742                command = command.arg(" ");
1743            }
1744            for key in options.keys {
1745                command = if options.sensitive {
1746                    command.sensitive_arg(key)
1747                } else {
1748                    command.arg(key)
1749                };
1750            }
1751        }
1752        self.server.checked("send keys", command).await?;
1753        if send_enter {
1754            self.server
1755                .checked(
1756                    "send Enter key",
1757                    Command::new("send-keys").target(self.id).arg("Enter"),
1758                )
1759                .await?;
1760        }
1761        Ok(())
1762    }
1763
1764    /// Clears pane history.
1765    pub async fn clear_history(&self) -> Result<()> {
1766        self.server
1767            .checked(
1768                "clear pane history",
1769                Command::new("clear-history").target(self.id),
1770            )
1771            .await
1772            .map(|_| ())
1773    }
1774
1775    /// Clears history and optionally resets hyperlinks (tmux 3.4+).
1776    pub async fn clear_history_with(&self, reset_hyperlinks: bool) -> Result<()> {
1777        if reset_hyperlinks {
1778            self.server
1779                .version()
1780                .await?
1781                .require("reset pane hyperlinks", ReleaseVersion::new(3, 4, None))?;
1782        }
1783        let mut command = Command::new("clear-history").target(self.id);
1784        if reset_hyperlinks {
1785            command = command.arg("-H");
1786        }
1787        self.server
1788            .checked("clear pane history", command)
1789            .await
1790            .map(|_| ())
1791    }
1792
1793    /// Sends the shell `reset` command followed by Enter, matching Python `Pane.clear()`.
1794    pub async fn clear(&self) -> Result<()> {
1795        self.send_keys(SendKeys::new().key("reset").enter(true))
1796            .await
1797    }
1798
1799    /// Resets the pane terminal state.
1800    pub async fn reset(&self, clear_history: bool) -> Result<()> {
1801        let mut command = Command::new("send-keys").target(self.id).arg("-R");
1802        if clear_history {
1803            command = command
1804                .arg(";")
1805                .arg("clear-history")
1806                .arg("-t")
1807                .arg(self.id.to_string());
1808        }
1809        self.server.checked("reset pane", command).await.map(|_| ())
1810    }
1811
1812    /// Enters or manipulates copy mode.
1813    pub async fn copy_mode(&self, options: CopyMode) -> Result<()> {
1814        if options.page_down {
1815            self.server
1816                .version()
1817                .await?
1818                .require("copy-mode page down", ReleaseVersion::new(3, 5, None))?;
1819        }
1820        let mut command = Command::new("copy-mode");
1821        if options.scroll_up {
1822            command = command.arg("-u");
1823        }
1824        if options.exit_on_bottom {
1825            command = command.arg("-e");
1826        }
1827        if options.mouse_drag {
1828            command = command.arg("-M");
1829        }
1830        if options.page_down {
1831            command = command.arg("-d");
1832        }
1833        if let Some(source) = options.source {
1834            command = command.arg("-s").arg(source.to_string());
1835        }
1836        if options.cancel {
1837            command = command.arg("-q");
1838        }
1839        self.server
1840            .checked("enter copy mode", command.target(self.id))
1841            .await
1842            .map(|_| ())
1843    }
1844
1845    /// Pastes a tmux buffer into the pane.
1846    pub async fn paste_buffer(&self, options: PasteBuffer) -> Result<()> {
1847        if options.raw {
1848            self.server
1849                .version()
1850                .await?
1851                .require("raw paste-buffer mode", ReleaseVersion::new(3, 7, None))?;
1852        }
1853        let mut command = Command::new("paste-buffer").target(self.id);
1854        if options.delete_after {
1855            command = command.arg("-d");
1856        }
1857        if options.linefeed_separator {
1858            command = command.arg("-r");
1859        }
1860        if options.bracketed {
1861            command = command.arg("-p");
1862        }
1863        if let Some(name) = options.name {
1864            command = command.arg("-b").arg(name.to_os_string());
1865        }
1866        if let Some(separator) = options.separator {
1867            command = command.arg("-s").arg(separator);
1868        }
1869        if options.raw {
1870            command = command.arg("-S");
1871        }
1872        self.server
1873            .checked("paste buffer", command)
1874            .await
1875            .map(|_| ())
1876    }
1877
1878    /// Configures or disables a pane pipe.
1879    pub async fn pipe(&self, options: PipePane) -> Result<()> {
1880        if options.output_only && options.input_only {
1881            return Err(Error::InvalidArgument {
1882                argument: "pane pipe direction",
1883                message: "output_only and input_only are mutually exclusive".to_owned(),
1884            });
1885        }
1886        let mut command = Command::new("pipe-pane").target(self.id);
1887        if options.output_only {
1888            command = command.arg("-O");
1889        }
1890        if options.input_only {
1891            command = command.arg("-I");
1892        }
1893        if options.toggle {
1894            command = command.arg("-o");
1895        }
1896        if let Some(shell_command) = options.command {
1897            command = command.sensitive_arg(shell_command);
1898        }
1899        self.server.checked("pipe pane", command).await.map(|_| ())
1900    }
1901
1902    /// Enters clock mode.
1903    pub async fn clock_mode(&self) -> Result<()> {
1904        self.server
1905            .checked("clock mode", Command::new("clock-mode").target(self.id))
1906            .await
1907            .map(|_| ())
1908    }
1909
1910    /// Displays pane numbers for an attached client.
1911    pub async fn display_panes(&self, duration_millis: Option<u32>, no_select: bool) -> Result<()> {
1912        let mut command = Command::new("display-panes");
1913        if let Some(duration) = duration_millis {
1914            command = command.arg("-d").arg(duration.to_string());
1915        }
1916        if no_select {
1917            command = command.arg("-N");
1918        }
1919        self.server
1920            .checked("display panes", command)
1921            .await
1922            .map(|_| ())
1923    }
1924
1925    /// Enters buffer chooser mode.
1926    pub async fn choose_buffer(&self) -> Result<()> {
1927        self.server
1928            .checked(
1929                "choose buffer",
1930                Command::new("choose-buffer").target(self.id),
1931            )
1932            .await
1933            .map(|_| ())
1934    }
1935
1936    /// Enters client chooser mode.
1937    pub async fn choose_client(&self) -> Result<()> {
1938        self.server
1939            .checked(
1940                "choose client",
1941                Command::new("choose-client").target(self.id),
1942            )
1943            .await
1944            .map(|_| ())
1945    }
1946
1947    /// Enters tree chooser mode.
1948    pub async fn choose_tree(&self, options: ChooseTree) -> Result<()> {
1949        let mut command = Command::new("choose-tree").target(self.id);
1950        for (enabled, flag) in [
1951            (options.sessions_collapsed, "-s"),
1952            (options.windows_collapsed, "-w"),
1953            (options.zoom, "-Z"),
1954            (options.reverse, "-r"),
1955        ] {
1956            if enabled {
1957                command = command.arg(flag);
1958            }
1959        }
1960        if let Some(format) = options.format {
1961            command = command.arg("-F").arg(format);
1962        }
1963        if let Some(filter) = options.native_filter {
1964            command = command.arg("-f").arg(filter);
1965        }
1966        if let Some(sort) = options.sort {
1967            command = command.arg("-O").arg(sort.as_str());
1968        }
1969        self.server
1970            .checked("choose tree", command)
1971            .await
1972            .map(|_| ())
1973    }
1974
1975    /// Enters customize mode.
1976    pub async fn customize_mode(&self) -> Result<()> {
1977        self.server
1978            .checked(
1979                "customize mode",
1980                Command::new("customize-mode").target(self.id),
1981            )
1982            .await
1983            .map(|_| ())
1984    }
1985
1986    /// Opens a window search chooser.
1987    pub async fn find_window(&self, options: FindWindow) -> Result<()> {
1988        let mut command = Command::new("find-window").target(self.id);
1989        for (enabled, flag) in [
1990            (options.content, "-C"),
1991            (options.case_insensitive, "-i"),
1992            (options.name_only, "-N"),
1993            (options.regex, "-r"),
1994            (options.title, "-T"),
1995        ] {
1996            if enabled {
1997                command = command.arg(flag);
1998            }
1999        }
2000        self.server
2001            .checked("find window", command.arg(options.pattern))
2002            .await
2003            .map(|_| ())
2004    }
2005
2006    /// Sends the primary or secondary prefix key.
2007    pub async fn send_prefix(&self, secondary: bool) -> Result<()> {
2008        let mut command = Command::new("send-prefix").target(self.id);
2009        if secondary {
2010            command = command.arg("-2");
2011        }
2012        self.server
2013            .checked("send prefix", command)
2014            .await
2015            .map(|_| ())
2016    }
2017
2018    /// Swaps this pane with another pane.
2019    pub async fn swap_with(&self, destination: PaneId, detached: bool) -> Result<()> {
2020        let mut command = Command::new("swap-pane").arg("-s").arg(self.id.to_string());
2021        if detached {
2022            command = command.arg("-d");
2023        }
2024        self.server
2025            .checked("swap pane", command.arg("-t").arg(destination.to_string()))
2026            .await
2027            .map(|_| ())
2028    }
2029
2030    /// Swaps this pane using explicit or relative typed arguments.
2031    pub async fn swap(&self, options: SwapPane) -> Result<()> {
2032        if options.destination.is_some() && options.direction.is_some() {
2033            return Err(Error::InvalidArgument {
2034                argument: "pane swap",
2035                message: "destination and relative direction are mutually exclusive".to_owned(),
2036            });
2037        }
2038        let mut command = Command::new("swap-pane").arg("-s").arg(self.id.to_string());
2039        if let Some(destination) = options.destination {
2040            command = command.arg("-t").arg(destination.to_string());
2041        }
2042        if let Some(direction) = options.direction {
2043            command = command.arg(match direction {
2044                SwapPaneDirection::Up => "-U",
2045                SwapPaneDirection::Down => "-D",
2046            });
2047        }
2048        if options.detached {
2049            command = command.arg("-d");
2050        }
2051        if options.keep_zoom {
2052            command = command.arg("-Z");
2053        }
2054        self.server.checked("swap pane", command).await.map(|_| ())
2055    }
2056
2057    /// Moves this pane into another pane or window.
2058    pub async fn move_to(&self, options: RelocatePane) -> Result<()> {
2059        self.relocate("move-pane", "move pane", options).await
2060    }
2061
2062    /// Joins this pane into another pane or window.
2063    pub async fn join(&self, options: RelocatePane) -> Result<()> {
2064        self.relocate("join-pane", "join pane", options).await
2065    }
2066
2067    async fn relocate(
2068        &self,
2069        subcommand: &'static str,
2070        operation: &'static str,
2071        options: RelocatePane,
2072    ) -> Result<()> {
2073        let mut command = Command::new(subcommand)
2074            .arg(match options.direction {
2075                SplitDirection::Vertical => "-v",
2076                SplitDirection::Horizontal => "-h",
2077            })
2078            .arg("-s")
2079            .arg(self.id.to_string())
2080            .arg("-t")
2081            .arg(options.destination.to_string());
2082        if options.detached {
2083            command = command.arg("-d");
2084        }
2085        if options.full_window {
2086            command = command.arg("-f");
2087        }
2088        if let Some(size) = options.size {
2089            let size = match size {
2090                PaneSize::Cells(cells) => cells.to_string(),
2091                PaneSize::Percent(percent) => format!("{percent}%"),
2092            };
2093            command = command.arg("-l").arg(size);
2094        }
2095        if options.before {
2096            command = command.arg("-b");
2097        }
2098        self.server.checked(operation, command).await.map(|_| ())
2099    }
2100
2101    /// Joins this pane into another window.
2102    pub async fn join_to(
2103        &self,
2104        destination: impl Into<WindowTarget>,
2105        horizontal: bool,
2106        before: bool,
2107        percent: Option<u8>,
2108    ) -> Result<()> {
2109        if percent.is_some_and(|value| !(1..=100).contains(&value)) {
2110            return Err(Error::InvalidArgument {
2111                argument: "join pane percentage",
2112                message: "must be between 1 and 100".to_owned(),
2113            });
2114        }
2115        let mut command = Command::new("join-pane")
2116            .arg("-s")
2117            .arg(self.id.to_string())
2118            .arg("-t")
2119            .arg(destination.into().to_string());
2120        if horizontal {
2121            command = command.arg("-h");
2122        }
2123        if before {
2124            command = command.arg("-b");
2125        }
2126        if let Some(percent) = percent {
2127            command = command.arg("-l").arg(format!("{percent}%"));
2128        }
2129        self.server.checked("join pane", command).await.map(|_| ())
2130    }
2131
2132    /// Breaks this pane into a new window and returns the new link.
2133    pub async fn break_to_window(&self, detached: bool, name: Option<&str>) -> Result<Window> {
2134        let mut command = Command::new("break-pane")
2135            .arg("-P")
2136            .arg("-F")
2137            .arg("#{window_id}")
2138            .target(self.id);
2139        if detached {
2140            command = command.arg("-d");
2141        }
2142        if let Some(name) = name {
2143            command = command.arg("-n").arg(name);
2144        }
2145        let result = self.server.checked("break pane", command).await?;
2146        let id: WindowId =
2147            crate::server::single_line(result.stdout(), "break-pane window ID")?.parse()?;
2148        self.server
2149            .windows()
2150            .await?
2151            .into_iter()
2152            .find(|window| window.id() == id && window.session_id() == self.session_id)
2153            .ok_or_else(|| Error::ObjectNotFound {
2154                kind: ObjectKind::Window,
2155                target: id.to_string(),
2156            })
2157    }
2158
2159    /// Respawns the pane process.
2160    pub async fn respawn(&self, options: RespawnPane) -> Result<()> {
2161        let mut command = Command::new("respawn-pane").target(self.id);
2162        if options.kill {
2163            command = command.arg("-k");
2164        }
2165        if let Some(cwd) = options.cwd {
2166            command = command.arg("-c").arg(cwd);
2167        }
2168        for (name, value) in options.environment {
2169            command =
2170                command
2171                    .arg("-e")
2172                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
2173        }
2174        if let Some(shell_command) = options.shell_command {
2175            command = command.sensitive_arg(shell_command);
2176        }
2177        self.server
2178            .checked("respawn pane", command)
2179            .await
2180            .map(|_| ())
2181    }
2182
2183    /// Destroys the pane. Dropping the handle is non-destructive.
2184    pub async fn kill(&self) -> Result<()> {
2185        self.kill_with(false).await
2186    }
2187
2188    /// Destroys this pane, or every other pane in the window when requested.
2189    pub async fn kill_with(&self, all_except: bool) -> Result<()> {
2190        let mut command = Command::new("kill-pane").target(self.id);
2191        if all_except {
2192            command = command.arg("-a");
2193        }
2194        self.server.checked("kill pane", command).await.map(|_| ())
2195    }
2196
2197    /// Shows pane-scoped options.
2198    pub async fn options(&self) -> Result<OptionMap> {
2199        self.server
2200            .show_options(OptionScope::Pane, Some(&self.id.to_string()))
2201            .await
2202    }
2203
2204    /// Shows sparse pane options and hooks.
2205    pub async fn sparse_options(&self) -> Result<SparseOptionMap> {
2206        self.server
2207            .show_sparse_options(OptionScope::Pane, Some(&self.id.to_string()))
2208            .await
2209    }
2210
2211    /// Sets a pane option.
2212    pub async fn set_option(&self, name: &str, value: &OptionValue, append: bool) -> Result<()> {
2213        self.server
2214            .set_option(
2215                OptionScope::Pane,
2216                Some(&self.id.to_string()),
2217                name,
2218                value,
2219                append,
2220            )
2221            .await
2222    }
2223
2224    /// Unsets a pane option.
2225    pub async fn unset_option(&self, name: &str) -> Result<()> {
2226        self.server
2227            .unset_option(OptionScope::Pane, Some(&self.id.to_string()), name)
2228            .await
2229    }
2230}
2231
2232impl PartialEq for Pane {
2233    fn eq(&self, other: &Self) -> bool {
2234        self.id == other.id && self.server.config() == other.server.config()
2235    }
2236}
2237
2238impl Eq for Pane {}
2239
2240fn parse_parent_id<T>(
2241    snapshot: &PaneSnapshot,
2242    token: &'static str,
2243    context: &'static str,
2244) -> Result<T>
2245where
2246    T: std::str::FromStr,
2247    T::Err: std::fmt::Display,
2248{
2249    let value = snapshot.get(token).ok_or_else(|| Error::Decode {
2250        context,
2251        message: format!("{token} was absent"),
2252    })?;
2253    let value = value.to_str().map_err(|source| Error::Decode {
2254        context,
2255        message: source.to_string(),
2256    })?;
2257    value.parse::<T>().map_err(|source| Error::Decode {
2258        context,
2259        message: source.to_string(),
2260    })
2261}