use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::PathBuf;
use crate::{
BufferName, ClientName, Command, Error, ObjectKind, OptionMap, OptionScope, OptionValue,
PaneId, PaneSnapshot, ReleaseVersion, Result, Server, Session, SessionId, SparseOptionMap,
TmuxText, Window, WindowId, WindowTarget,
};
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub enum SplitDirection {
#[default]
Vertical,
Horizontal,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PaneSize {
Cells(u32),
Percent(u8),
}
#[derive(Clone, Debug)]
pub struct SplitPane {
direction: SplitDirection,
size: Option<PaneSize>,
detached: bool,
before: bool,
full_window: bool,
cwd: Option<PathBuf>,
shell_command: Option<OsString>,
environment: BTreeMap<String, OsString>,
}
#[derive(Clone, Debug, Default)]
pub struct NewPane {
cwd: Option<PathBuf>,
attach: bool,
shell_command: Option<OsString>,
environment: BTreeMap<String, OsString>,
width: Option<u32>,
height: Option<u32>,
x: Option<i32>,
y: Option<i32>,
zoom: bool,
empty: bool,
style: Option<OsString>,
active_border_style: Option<OsString>,
inactive_border_style: Option<OsString>,
message: Option<OsString>,
keep: bool,
}
impl NewPane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
#[must_use]
pub const fn attach(mut self, enabled: bool) -> Self {
self.attach = enabled;
self
}
#[must_use]
pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
self.shell_command = Some(command.into());
self
}
pub fn environment(
mut self,
name: impl Into<String>,
value: impl Into<OsString>,
) -> Result<Self> {
let name = name.into();
crate::server::validate_name("environment name", &name)?;
self.environment.insert(name, value.into());
Ok(self)
}
pub fn width(mut self, width: u32) -> Result<Self> {
if width == 0 {
return Err(Error::InvalidArgument {
argument: "floating pane width",
message: "must be non-zero".to_owned(),
});
}
self.width = Some(width);
Ok(self)
}
pub fn height(mut self, height: u32) -> Result<Self> {
if height == 0 {
return Err(Error::InvalidArgument {
argument: "floating pane height",
message: "must be non-zero".to_owned(),
});
}
self.height = Some(height);
Ok(self)
}
#[must_use]
pub const fn x(mut self, x: i32) -> Self {
self.x = Some(x);
self
}
#[must_use]
pub const fn y(mut self, y: i32) -> Self {
self.y = Some(y);
self
}
#[must_use]
pub const fn zoom(mut self, enabled: bool) -> Self {
self.zoom = enabled;
self
}
#[must_use]
pub const fn empty(mut self, enabled: bool) -> Self {
self.empty = enabled;
self
}
#[must_use]
pub fn style(mut self, value: impl Into<OsString>) -> Self {
self.style = Some(value.into());
self
}
#[must_use]
pub fn active_border_style(mut self, value: impl Into<OsString>) -> Self {
self.active_border_style = Some(value.into());
self
}
#[must_use]
pub fn inactive_border_style(mut self, value: impl Into<OsString>) -> Self {
self.inactive_border_style = Some(value.into());
self
}
#[must_use]
pub fn message(mut self, value: impl Into<OsString>) -> Self {
self.message = Some(value.into());
self
}
#[must_use]
pub const fn keep(mut self, enabled: bool) -> Self {
self.keep = enabled;
self
}
}
impl Default for SplitPane {
fn default() -> Self {
Self {
direction: SplitDirection::Vertical,
size: None,
detached: true,
before: false,
full_window: false,
cwd: None,
shell_command: None,
environment: BTreeMap::new(),
}
}
}
impl SplitPane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn direction(mut self, direction: SplitDirection) -> Self {
self.direction = direction;
self
}
pub fn cells(mut self, cells: u32) -> Result<Self> {
if cells == 0 {
return Err(Error::InvalidArgument {
argument: "pane size",
message: "cell count must be non-zero".to_owned(),
});
}
self.size = Some(PaneSize::Cells(cells));
Ok(self)
}
pub fn percent(mut self, percent: u8) -> Result<Self> {
if !(1..=100).contains(&percent) {
return Err(Error::InvalidArgument {
argument: "pane percentage",
message: "must be between 1 and 100".to_owned(),
});
}
self.size = Some(PaneSize::Percent(percent));
Ok(self)
}
#[must_use]
pub const fn detached(mut self, detached: bool) -> Self {
self.detached = detached;
self
}
#[must_use]
pub const fn before(mut self, before: bool) -> Self {
self.before = before;
self
}
#[must_use]
pub const fn full_window(mut self, full_window: bool) -> Self {
self.full_window = full_window;
self
}
#[must_use]
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
#[must_use]
pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
self.shell_command = Some(command.into());
self
}
pub fn environment(
mut self,
name: impl Into<String>,
value: impl Into<OsString>,
) -> Result<Self> {
let name = name.into();
crate::server::validate_name("environment name", &name)?;
self.environment.insert(name, value.into());
Ok(self)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ResizeDirection {
Left,
Right,
Up,
Down,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PaneDestination {
Pane(PaneId),
Window(WindowTarget),
}
impl std::fmt::Display for PaneDestination {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Pane(id) => id.fmt(formatter),
Self::Window(target) => target.fmt(formatter),
}
}
}
impl From<PaneId> for PaneDestination {
fn from(value: PaneId) -> Self {
Self::Pane(value)
}
}
impl From<WindowTarget> for PaneDestination {
fn from(value: WindowTarget) -> Self {
Self::Window(value)
}
}
impl From<WindowId> for PaneDestination {
fn from(value: WindowId) -> Self {
Self::Window(value.into())
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RelocatePane {
destination: PaneDestination,
direction: SplitDirection,
detached: bool,
full_window: bool,
size: Option<PaneSize>,
before: bool,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SwapPaneDirection {
Up,
Down,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SwapPane {
destination: Option<PaneId>,
direction: Option<SwapPaneDirection>,
detached: bool,
keep_zoom: bool,
}
impl SwapPane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn destination(mut self, pane: PaneId) -> Self {
self.destination = Some(pane);
self
}
#[must_use]
pub const fn direction(mut self, direction: SwapPaneDirection) -> Self {
self.direction = Some(direction);
self
}
#[must_use]
pub const fn detached(mut self, enabled: bool) -> Self {
self.detached = enabled;
self
}
#[must_use]
pub const fn keep_zoom(mut self, enabled: bool) -> Self {
self.keep_zoom = enabled;
self
}
}
impl RelocatePane {
#[must_use]
pub fn new(destination: impl Into<PaneDestination>) -> Self {
Self {
destination: destination.into(),
direction: SplitDirection::Vertical,
detached: true,
full_window: false,
size: None,
before: false,
}
}
#[must_use]
pub const fn direction(mut self, direction: SplitDirection) -> Self {
self.direction = direction;
self
}
#[must_use]
pub const fn detached(mut self, detached: bool) -> Self {
self.detached = detached;
self
}
#[must_use]
pub const fn full_window(mut self, enabled: bool) -> Self {
self.full_window = enabled;
self
}
pub fn cells(mut self, cells: u32) -> Result<Self> {
if cells == 0 {
return Err(Error::InvalidArgument {
argument: "relocated pane size",
message: "cell count must be non-zero".to_owned(),
});
}
self.size = Some(PaneSize::Cells(cells));
Ok(self)
}
pub fn percent(mut self, percent: u8) -> Result<Self> {
if !(1..=100).contains(&percent) {
return Err(Error::InvalidArgument {
argument: "relocated pane percentage",
message: "must be between 1 and 100".to_owned(),
});
}
self.size = Some(PaneSize::Percent(percent));
Ok(self)
}
#[must_use]
pub const fn before(mut self, enabled: bool) -> Self {
self.before = enabled;
self
}
}
impl ResizeDirection {
pub(crate) fn flag(self) -> &'static str {
match self {
Self::Left => "-L",
Self::Right => "-R",
Self::Up => "-U",
Self::Down => "-D",
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CapturePane {
start: Option<CaptureLine>,
end: Option<CaptureLine>,
alternate: bool,
escape_sequences: bool,
escape_non_printable: bool,
join_wrapped: bool,
preserve_trailing: bool,
trim_trailing: bool,
quiet: bool,
mode_screen: bool,
pending: bool,
hyperlinks: bool,
line_numbers: bool,
line_flags: bool,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum CaptureLine {
Number(i64),
Boundary,
}
impl std::fmt::Display for CaptureLine {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Number(line) => line.fmt(formatter),
Self::Boundary => formatter.write_str("-"),
}
}
}
impl CapturePane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn start(mut self, line: i64) -> Self {
self.start = Some(CaptureLine::Number(line));
self
}
#[must_use]
pub const fn start_of_history(mut self) -> Self {
self.start = Some(CaptureLine::Boundary);
self
}
#[must_use]
pub const fn end(mut self, line: i64) -> Self {
self.end = Some(CaptureLine::Number(line));
self
}
#[must_use]
pub const fn end_of_screen(mut self) -> Self {
self.end = Some(CaptureLine::Boundary);
self
}
#[must_use]
pub const fn alternate(mut self, enabled: bool) -> Self {
self.alternate = enabled;
self
}
#[must_use]
pub const fn escape_sequences(mut self, enabled: bool) -> Self {
self.escape_sequences = enabled;
self
}
#[must_use]
pub const fn escape_non_printable(mut self, enabled: bool) -> Self {
self.escape_non_printable = enabled;
self
}
#[must_use]
pub const fn join_wrapped(mut self, enabled: bool) -> Self {
self.join_wrapped = enabled;
self
}
#[must_use]
pub const fn preserve_trailing(mut self, enabled: bool) -> Self {
self.preserve_trailing = enabled;
self
}
#[must_use]
pub const fn trim_trailing(mut self, enabled: bool) -> Self {
self.trim_trailing = enabled;
self
}
#[must_use]
pub const fn quiet(mut self, enabled: bool) -> Self {
self.quiet = enabled;
self
}
#[must_use]
pub const fn mode_screen(mut self, enabled: bool) -> Self {
self.mode_screen = enabled;
self
}
#[must_use]
pub const fn pending(mut self, enabled: bool) -> Self {
self.pending = enabled;
self
}
#[must_use]
pub const fn hyperlinks(mut self, enabled: bool) -> Self {
self.hyperlinks = enabled;
self
}
#[must_use]
pub const fn line_numbers(mut self, enabled: bool) -> Self {
self.line_numbers = enabled;
self
}
#[must_use]
pub const fn line_flags(mut self, enabled: bool) -> Self {
self.line_flags = enabled;
self
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SendKeys {
keys: Vec<OsString>,
literal: bool,
hexadecimal: bool,
reset: bool,
repeat: Option<u32>,
enter: bool,
suppress_history: bool,
copy_mode_command: Option<OsString>,
expand_formats: bool,
target_client: Option<ClientName>,
key_name: bool,
sensitive: bool,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct SelectPane {
direction: Option<ResizeDirection>,
last: bool,
keep_zoom: bool,
mark: bool,
clear_mark: bool,
input: Option<bool>,
}
impl SelectPane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn direction(mut self, direction: ResizeDirection) -> Self {
self.direction = Some(direction);
self
}
#[must_use]
pub const fn last(mut self, enabled: bool) -> Self {
self.last = enabled;
self
}
#[must_use]
pub const fn keep_zoom(mut self, enabled: bool) -> Self {
self.keep_zoom = enabled;
self
}
#[must_use]
pub const fn mark(mut self, enabled: bool) -> Self {
self.mark = enabled;
self
}
#[must_use]
pub const fn clear_mark(mut self, enabled: bool) -> Self {
self.clear_mark = enabled;
self
}
#[must_use]
pub const fn input(mut self, enabled: Option<bool>) -> Self {
self.input = enabled;
self
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PasteBuffer {
name: Option<BufferName>,
delete_after: bool,
linefeed_separator: bool,
bracketed: bool,
separator: Option<OsString>,
raw: bool,
}
impl PasteBuffer {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn name(mut self, name: BufferName) -> Self {
self.name = Some(name);
self
}
#[must_use]
pub const fn delete_after(mut self, enabled: bool) -> Self {
self.delete_after = enabled;
self
}
#[must_use]
pub const fn linefeed_separator(mut self, enabled: bool) -> Self {
self.linefeed_separator = enabled;
self
}
#[must_use]
pub const fn bracketed(mut self, enabled: bool) -> Self {
self.bracketed = enabled;
self
}
#[must_use]
pub fn separator(mut self, separator: impl Into<OsString>) -> Self {
self.separator = Some(separator.into());
self
}
#[must_use]
pub const fn raw(mut self, enabled: bool) -> Self {
self.raw = enabled;
self
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PipePane {
command: Option<OsString>,
output_only: bool,
input_only: bool,
toggle: bool,
}
impl PipePane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn command(mut self, command: impl Into<OsString>) -> Self {
self.command = Some(command.into());
self
}
#[must_use]
pub const fn output_only(mut self, enabled: bool) -> Self {
self.output_only = enabled;
self
}
#[must_use]
pub const fn input_only(mut self, enabled: bool) -> Self {
self.input_only = enabled;
self
}
#[must_use]
pub const fn toggle(mut self, enabled: bool) -> Self {
self.toggle = enabled;
self
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct CopyMode {
scroll_up: bool,
exit_on_bottom: bool,
mouse_drag: bool,
cancel: bool,
page_down: bool,
source: Option<PaneId>,
}
impl CopyMode {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn scroll_up(mut self, enabled: bool) -> Self {
self.scroll_up = enabled;
self
}
#[must_use]
pub const fn exit_on_bottom(mut self, enabled: bool) -> Self {
self.exit_on_bottom = enabled;
self
}
#[must_use]
pub const fn mouse_drag(mut self, enabled: bool) -> Self {
self.mouse_drag = enabled;
self
}
#[must_use]
pub const fn cancel(mut self, enabled: bool) -> Self {
self.cancel = enabled;
self
}
#[must_use]
pub const fn page_down(mut self, enabled: bool) -> Self {
self.page_down = enabled;
self
}
#[must_use]
pub const fn source(mut self, source: PaneId) -> Self {
self.source = Some(source);
self
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum TreeSort {
Index,
Name,
Time,
Size,
}
impl TreeSort {
fn as_str(self) -> &'static str {
match self {
Self::Index => "index",
Self::Name => "name",
Self::Time => "time",
Self::Size => "size",
}
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct ChooseTree {
sessions_collapsed: bool,
windows_collapsed: bool,
format: Option<OsString>,
native_filter: Option<OsString>,
sort: Option<TreeSort>,
reverse: bool,
zoom: bool,
}
impl ChooseTree {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn sessions_collapsed(mut self, enabled: bool) -> Self {
self.sessions_collapsed = enabled;
self
}
#[must_use]
pub const fn windows_collapsed(mut self, enabled: bool) -> Self {
self.windows_collapsed = enabled;
self
}
#[must_use]
pub fn format(mut self, value: impl Into<OsString>) -> Self {
self.format = Some(value.into());
self
}
#[must_use]
pub fn native_filter(mut self, value: impl Into<OsString>) -> Self {
self.native_filter = Some(value.into());
self
}
#[must_use]
pub const fn sort(mut self, sort: TreeSort) -> Self {
self.sort = Some(sort);
self
}
#[must_use]
pub const fn reverse(mut self, enabled: bool) -> Self {
self.reverse = enabled;
self
}
#[must_use]
pub const fn zoom(mut self, enabled: bool) -> Self {
self.zoom = enabled;
self
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FindWindow {
pattern: OsString,
content: bool,
case_insensitive: bool,
name_only: bool,
regex: bool,
title: bool,
}
impl FindWindow {
#[must_use]
pub fn new(pattern: impl Into<OsString>) -> Self {
Self {
pattern: pattern.into(),
content: false,
case_insensitive: false,
name_only: false,
regex: false,
title: false,
}
}
#[must_use]
pub const fn content(mut self, enabled: bool) -> Self {
self.content = enabled;
self
}
#[must_use]
pub const fn case_insensitive(mut self, enabled: bool) -> Self {
self.case_insensitive = enabled;
self
}
#[must_use]
pub const fn name_only(mut self, enabled: bool) -> Self {
self.name_only = enabled;
self
}
#[must_use]
pub const fn regex(mut self, enabled: bool) -> Self {
self.regex = enabled;
self
}
#[must_use]
pub const fn title(mut self, enabled: bool) -> Self {
self.title = enabled;
self
}
}
#[derive(Clone, Debug, Default)]
pub struct RespawnPane {
shell_command: Option<OsString>,
cwd: Option<PathBuf>,
environment: BTreeMap<String, OsString>,
kill: bool,
}
impl RespawnPane {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
self.shell_command = Some(command.into());
self
}
#[must_use]
pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
pub fn environment(
mut self,
name: impl Into<String>,
value: impl Into<OsString>,
) -> Result<Self> {
let name = name.into();
crate::server::validate_name("environment name", &name)?;
self.environment.insert(name, value.into());
Ok(self)
}
#[must_use]
pub const fn kill(mut self, enabled: bool) -> Self {
self.kill = enabled;
self
}
}
impl SendKeys {
#[must_use]
pub const fn new() -> Self {
Self {
keys: Vec::new(),
literal: false,
hexadecimal: false,
reset: false,
repeat: None,
enter: false,
suppress_history: false,
copy_mode_command: None,
expand_formats: false,
target_client: None,
key_name: false,
sensitive: false,
}
}
#[must_use]
pub fn key(mut self, key: impl Into<OsString>) -> Self {
self.keys.push(key.into());
self
}
#[must_use]
pub fn keys<I, S>(mut self, keys: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<OsString>,
{
self.keys.extend(keys.into_iter().map(Into::into));
self
}
#[must_use]
pub const fn literal(mut self, enabled: bool) -> Self {
self.literal = enabled;
self
}
#[must_use]
pub const fn hexadecimal(mut self, enabled: bool) -> Self {
self.hexadecimal = enabled;
self
}
#[must_use]
pub const fn reset(mut self, enabled: bool) -> Self {
self.reset = enabled;
self
}
pub fn repeat(mut self, count: u32) -> Result<Self> {
if count == 0 {
return Err(Error::InvalidArgument {
argument: "send-keys repeat",
message: "must be non-zero".to_owned(),
});
}
self.repeat = Some(count);
Ok(self)
}
#[must_use]
pub const fn enter(mut self, enabled: bool) -> Self {
self.enter = enabled;
self
}
#[must_use]
pub const fn suppress_history(mut self, enabled: bool) -> Self {
self.suppress_history = enabled;
self
}
#[must_use]
pub fn copy_mode_command(mut self, command: impl Into<OsString>) -> Self {
self.copy_mode_command = Some(command.into());
self
}
#[must_use]
pub const fn expand_formats(mut self, enabled: bool) -> Self {
self.expand_formats = enabled;
self
}
#[must_use]
pub fn target_client(mut self, client: ClientName) -> Self {
self.target_client = Some(client);
self
}
#[must_use]
pub const fn key_name(mut self, enabled: bool) -> Self {
self.key_name = enabled;
self
}
#[must_use]
pub const fn sensitive(mut self, enabled: bool) -> Self {
self.sensitive = enabled;
self
}
}
#[derive(Clone, Debug)]
pub struct Pane {
server: Server,
id: PaneId,
session_id: SessionId,
window_id: WindowId,
snapshot: PaneSnapshot,
}
impl Pane {
pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
let snapshot = PaneSnapshot::new(row);
let id = snapshot.id()?.ok_or_else(|| Error::Decode {
context: "pane row",
message: "pane_id was empty".to_owned(),
})?;
let session_id = parse_parent_id(&snapshot, "session_id", "pane session ID")?;
let window_id = parse_parent_id(&snapshot, "window_id", "pane window ID")?;
Ok(Self {
server,
id,
session_id,
window_id,
snapshot,
})
}
pub async fn from_environment() -> Result<Self> {
Server::from_environment()?.pane_from_environment().await
}
#[must_use]
pub const fn id(&self) -> PaneId {
self.id
}
#[must_use]
pub const fn session_id(&self) -> SessionId {
self.session_id
}
#[must_use]
pub const fn window_id(&self) -> WindowId {
self.window_id
}
#[must_use]
pub const fn snapshot(&self) -> &PaneSnapshot {
&self.snapshot
}
#[must_use]
pub const fn server(&self) -> &Server {
&self.server
}
pub async fn refresh(&mut self) -> Result<()> {
*self = self.server.pane(self.id).await?;
Ok(())
}
pub async fn session(&self) -> Result<Session> {
self.server.session(self.session_id).await
}
pub async fn window(&self) -> Result<Window> {
self.server
.windows()
.await?
.into_iter()
.find(|window| window.id() == self.window_id && window.session_id() == self.session_id)
.ok_or_else(|| Error::ObjectNotFound {
kind: ObjectKind::Window,
target: format!("{} in {}", self.window_id, self.session_id),
})
}
pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
self.server.cmd(command.target(self.id)).await
}
pub async fn split(&self, options: SplitPane) -> Result<Self> {
let mut command = Command::new("split-window")
.arg("-P")
.arg("-F")
.arg("#{pane_id}")
.target(self.id);
if options.direction == SplitDirection::Horizontal {
command = command.arg("-h");
}
if options.detached {
command = command.arg("-d");
}
if options.before {
command = command.arg("-b");
}
if options.full_window {
command = command.arg("-f");
}
if let Some(size) = options.size {
match size {
PaneSize::Cells(cells) => {
command = command.arg("-l").arg(cells.to_string());
}
PaneSize::Percent(percent) => {
command = command.arg("-p").arg(percent.to_string());
}
}
}
if let Some(cwd) = options.cwd {
command = command.arg("-c").arg(cwd);
}
for (name, value) in options.environment {
command =
command
.arg("-e")
.sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
}
if let Some(shell_command) = options.shell_command {
command = command.sensitive_arg(shell_command);
}
let result = self.server.checked("split pane", command).await?;
let id: PaneId =
crate::server::single_line(result.stdout(), "split-window pane ID")?.parse()?;
self.server.pane(id).await
}
pub async fn new_pane(&self, options: NewPane) -> Result<Self> {
self.server
.version()
.await?
.require("floating panes", ReleaseVersion::new(3, 7, None))?;
let mut command = Command::new("new-pane")
.arg("-P")
.arg("-F")
.arg("#{pane_id}")
.target(self.id);
if let Some(width) = options.width {
command = command.arg("-x").arg(width.to_string());
}
if let Some(height) = options.height {
command = command.arg("-y").arg(height.to_string());
}
if let Some(x) = options.x {
command = command.arg("-X").arg(x.to_string());
}
if let Some(y) = options.y {
command = command.arg("-Y").arg(y.to_string());
}
if options.zoom {
command = command.arg("-Z");
}
if let Some(style) = options.style {
command = command.arg("-s").arg(style);
}
if let Some(style) = options.active_border_style {
command = command.arg("-S").arg(style);
}
if let Some(style) = options.inactive_border_style {
command = command.arg("-R").arg(style);
}
if let Some(message) = options.message {
command = command.arg("-m").arg(message);
}
if options.keep {
command = command.arg("-k");
}
if let Some(cwd) = options.cwd {
command = command.arg("-c").arg(cwd);
}
if !options.attach {
command = command.arg("-d");
}
for (name, value) in options.environment {
command =
command
.arg("-e")
.sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
}
if options.empty {
command = command.arg("-E");
}
if let Some(shell_command) = options.shell_command {
command = command.sensitive_arg(shell_command);
}
let result = self.server.checked("create floating pane", command).await?;
let id: PaneId =
crate::server::single_line(result.stdout(), "new-pane pane ID")?.parse()?;
self.server.pane(id).await
}
pub async fn select(&self, enable_input: bool) -> Result<()> {
self.select_with(SelectPane::new().input(enable_input.then_some(true)))
.await
}
pub async fn select_with(&self, options: SelectPane) -> Result<()> {
if options.direction.is_some() && options.last {
return Err(Error::InvalidArgument {
argument: "pane selection",
message: "direction and last are mutually exclusive".to_owned(),
});
}
if options.mark && options.clear_mark {
return Err(Error::InvalidArgument {
argument: "pane selection",
message: "mark and clear_mark are mutually exclusive".to_owned(),
});
}
let mut command = Command::new("select-pane");
if let Some(direction) = options.direction {
command = command.arg(direction.flag());
}
for (enabled, flag) in [
(options.last, "-l"),
(options.keep_zoom, "-Z"),
(options.mark, "-m"),
(options.clear_mark, "-M"),
] {
if enabled {
command = command.arg(flag);
}
}
if let Some(input) = options.input {
command = command.arg(if input { "-e" } else { "-d" });
}
self.server
.checked("select pane", command.target(self.id))
.await
.map(|_| ())
}
pub async fn set_title(&self, title: impl Into<OsString>) -> Result<()> {
self.server
.checked(
"set pane title",
Command::new("select-pane")
.arg("-T")
.arg(title)
.target(self.id),
)
.await
.map(|_| ())
}
pub async fn resize(&self, direction: ResizeDirection, cells: u32) -> Result<()> {
if cells == 0 {
return Err(Error::InvalidArgument {
argument: "resize cells",
message: "must be non-zero".to_owned(),
});
}
self.server
.checked(
"resize pane",
Command::new("resize-pane")
.arg(direction.flag())
.arg(cells.to_string())
.target(self.id),
)
.await
.map(|_| ())
}
pub async fn resize_to(&self, width: Option<u32>, height: Option<u32>) -> Result<()> {
if width.is_none() && height.is_none() {
return Err(Error::InvalidArgument {
argument: "absolute pane size",
message: "width or height is required".to_owned(),
});
}
if width == Some(0) || height == Some(0) {
return Err(Error::InvalidArgument {
argument: "absolute pane size",
message: "dimensions must be non-zero".to_owned(),
});
}
let mut command = Command::new("resize-pane");
if let Some(width) = width {
command = command.arg("-x").arg(width.to_string());
}
if let Some(height) = height {
command = command.arg("-y").arg(height.to_string());
}
self.server
.checked("resize pane", command.target(self.id))
.await
.map(|_| ())
}
pub async fn resize_width_percent(&self, percent: u8) -> Result<()> {
self.resize_percent("-x", percent).await
}
pub async fn resize_height_percent(&self, percent: u8) -> Result<()> {
self.resize_percent("-y", percent).await
}
async fn resize_percent(&self, flag: &'static str, percent: u8) -> Result<()> {
if !(1..=100).contains(&percent) {
return Err(Error::InvalidArgument {
argument: "pane size percentage",
message: "must be between 1 and 100".to_owned(),
});
}
self.server
.checked(
"resize pane",
Command::new("resize-pane")
.arg(flag)
.arg(format!("{percent}%"))
.target(self.id),
)
.await
.map(|_| ())
}
pub async fn resize_from_mouse(&self) -> Result<()> {
self.server
.checked(
"resize pane from mouse",
Command::new("resize-pane").arg("-M").target(self.id),
)
.await
.map(|_| ())
}
pub async fn trim_below(&self) -> Result<()> {
self.server
.checked(
"trim pane below cursor",
Command::new("resize-pane").arg("-T").target(self.id),
)
.await
.map(|_| ())
}
pub async fn toggle_zoom(&self) -> Result<()> {
self.server
.checked(
"toggle pane zoom",
Command::new("resize-pane").arg("-Z").target(self.id),
)
.await
.map(|_| ())
}
pub async fn capture(&self, options: &CapturePane) -> Result<TmuxText> {
self.validate_capture(options).await?;
let command = self.capture_command(options).arg("-p");
self.server
.checked("capture pane", command)
.await
.map(|result| result.stdout().clone())
}
pub async fn capture_to_buffer(
&self,
options: &CapturePane,
buffer: &BufferName,
) -> Result<()> {
self.validate_capture(options).await?;
self.server
.checked(
"capture pane to buffer",
self.capture_command(options)
.arg("-b")
.arg(buffer.to_os_string()),
)
.await
.map(|_| ())
}
fn capture_command(&self, options: &CapturePane) -> Command {
let mut command = Command::new("capture-pane").target(self.id);
if let Some(start) = options.start {
command = command.arg("-S").arg(start.to_string());
}
if let Some(end) = options.end {
command = command.arg("-E").arg(end.to_string());
}
if options.alternate {
command = command.arg("-a");
}
if options.escape_sequences {
command = command.arg("-e");
}
if options.escape_non_printable {
command = command.arg("-C");
}
if options.join_wrapped {
command = command.arg("-J");
}
if options.preserve_trailing {
command = command.arg("-N");
}
if options.pending {
command = command.arg("-P");
}
if options.trim_trailing {
command = command.arg("-T");
}
if options.quiet {
command = command.arg("-q");
}
if options.mode_screen {
command = command.arg("-M");
}
if options.hyperlinks {
command = command.arg("-H");
}
if options.line_numbers {
command = command.arg("-L");
}
if options.line_flags {
command = command.arg("-F");
}
command
}
async fn validate_capture(&self, options: &CapturePane) -> Result<()> {
if options.trim_trailing {
self.server.version().await?.require(
"trim trailing capture cells",
ReleaseVersion::new(3, 4, None),
)?;
}
if options.mode_screen {
self.server
.version()
.await?
.require("capture mode screen", ReleaseVersion::new(3, 6, None))?;
}
if options.hyperlinks || options.line_numbers || options.line_flags {
self.server
.version()
.await?
.require("extended pane capture", ReleaseVersion::new(3, 7, None))?;
}
Ok(())
}
pub async fn send_keys(&self, options: SendKeys) -> Result<()> {
let send_enter = options.enter && options.copy_mode_command.is_none();
if options.keys.is_empty()
&& !options.reset
&& options.repeat.is_none()
&& options.copy_mode_command.is_none()
{
return Err(Error::InvalidArgument {
argument: "send keys",
message: "keys, reset, repeat, or a copy-mode command is required".to_owned(),
});
}
if options.literal && options.hexadecimal {
return Err(Error::InvalidArgument {
argument: "send keys",
message: "literal and hexadecimal modes are mutually exclusive".to_owned(),
});
}
if options.copy_mode_command.is_some() && !options.keys.is_empty() {
return Err(Error::InvalidArgument {
argument: "send keys",
message: "ordinary keys and a copy-mode command are mutually exclusive".to_owned(),
});
}
if options.target_client.is_some() || options.key_name {
self.server
.version()
.await?
.require("client-targeted keys", ReleaseVersion::new(3, 4, None))?;
}
let mut command = Command::new("send-keys").target(self.id);
if options.literal {
command = command.arg("-l");
}
if options.hexadecimal {
command = command.arg("-H");
}
if options.reset {
command = command.arg("-R");
}
if options.expand_formats {
command = command.arg("-F");
}
if options.key_name {
command = command.arg("-K");
}
if let Some(client) = options.target_client {
command = command.arg("-c").arg(client.to_string());
}
if let Some(repeat) = options.repeat {
command = command.arg("-N").arg(repeat.to_string());
}
if let Some(copy_mode_command) = options.copy_mode_command {
command = command.arg("-X");
command = if options.sensitive {
command.sensitive_arg(copy_mode_command)
} else {
command.arg(copy_mode_command)
};
} else {
if options.suppress_history {
command = command.arg(" ");
}
for key in options.keys {
command = if options.sensitive {
command.sensitive_arg(key)
} else {
command.arg(key)
};
}
}
self.server.checked("send keys", command).await?;
if send_enter {
self.server
.checked(
"send Enter key",
Command::new("send-keys").target(self.id).arg("Enter"),
)
.await?;
}
Ok(())
}
pub async fn clear_history(&self) -> Result<()> {
self.server
.checked(
"clear pane history",
Command::new("clear-history").target(self.id),
)
.await
.map(|_| ())
}
pub async fn clear_history_with(&self, reset_hyperlinks: bool) -> Result<()> {
if reset_hyperlinks {
self.server
.version()
.await?
.require("reset pane hyperlinks", ReleaseVersion::new(3, 4, None))?;
}
let mut command = Command::new("clear-history").target(self.id);
if reset_hyperlinks {
command = command.arg("-H");
}
self.server
.checked("clear pane history", command)
.await
.map(|_| ())
}
pub async fn clear(&self) -> Result<()> {
self.send_keys(SendKeys::new().key("reset").enter(true))
.await
}
pub async fn reset(&self, clear_history: bool) -> Result<()> {
let mut command = Command::new("send-keys").target(self.id).arg("-R");
if clear_history {
command = command
.arg(";")
.arg("clear-history")
.arg("-t")
.arg(self.id.to_string());
}
self.server.checked("reset pane", command).await.map(|_| ())
}
pub async fn copy_mode(&self, options: CopyMode) -> Result<()> {
if options.page_down {
self.server
.version()
.await?
.require("copy-mode page down", ReleaseVersion::new(3, 5, None))?;
}
let mut command = Command::new("copy-mode");
if options.scroll_up {
command = command.arg("-u");
}
if options.exit_on_bottom {
command = command.arg("-e");
}
if options.mouse_drag {
command = command.arg("-M");
}
if options.page_down {
command = command.arg("-d");
}
if let Some(source) = options.source {
command = command.arg("-s").arg(source.to_string());
}
if options.cancel {
command = command.arg("-q");
}
self.server
.checked("enter copy mode", command.target(self.id))
.await
.map(|_| ())
}
pub async fn paste_buffer(&self, options: PasteBuffer) -> Result<()> {
if options.raw {
self.server
.version()
.await?
.require("raw paste-buffer mode", ReleaseVersion::new(3, 7, None))?;
}
let mut command = Command::new("paste-buffer").target(self.id);
if options.delete_after {
command = command.arg("-d");
}
if options.linefeed_separator {
command = command.arg("-r");
}
if options.bracketed {
command = command.arg("-p");
}
if let Some(name) = options.name {
command = command.arg("-b").arg(name.to_os_string());
}
if let Some(separator) = options.separator {
command = command.arg("-s").arg(separator);
}
if options.raw {
command = command.arg("-S");
}
self.server
.checked("paste buffer", command)
.await
.map(|_| ())
}
pub async fn pipe(&self, options: PipePane) -> Result<()> {
if options.output_only && options.input_only {
return Err(Error::InvalidArgument {
argument: "pane pipe direction",
message: "output_only and input_only are mutually exclusive".to_owned(),
});
}
let mut command = Command::new("pipe-pane").target(self.id);
if options.output_only {
command = command.arg("-O");
}
if options.input_only {
command = command.arg("-I");
}
if options.toggle {
command = command.arg("-o");
}
if let Some(shell_command) = options.command {
command = command.sensitive_arg(shell_command);
}
self.server.checked("pipe pane", command).await.map(|_| ())
}
pub async fn clock_mode(&self) -> Result<()> {
self.server
.checked("clock mode", Command::new("clock-mode").target(self.id))
.await
.map(|_| ())
}
pub async fn display_panes(&self, duration_millis: Option<u32>, no_select: bool) -> Result<()> {
let mut command = Command::new("display-panes");
if let Some(duration) = duration_millis {
command = command.arg("-d").arg(duration.to_string());
}
if no_select {
command = command.arg("-N");
}
self.server
.checked("display panes", command)
.await
.map(|_| ())
}
pub async fn choose_buffer(&self) -> Result<()> {
self.server
.checked(
"choose buffer",
Command::new("choose-buffer").target(self.id),
)
.await
.map(|_| ())
}
pub async fn choose_client(&self) -> Result<()> {
self.server
.checked(
"choose client",
Command::new("choose-client").target(self.id),
)
.await
.map(|_| ())
}
pub async fn choose_tree(&self, options: ChooseTree) -> Result<()> {
let mut command = Command::new("choose-tree").target(self.id);
for (enabled, flag) in [
(options.sessions_collapsed, "-s"),
(options.windows_collapsed, "-w"),
(options.zoom, "-Z"),
(options.reverse, "-r"),
] {
if enabled {
command = command.arg(flag);
}
}
if let Some(format) = options.format {
command = command.arg("-F").arg(format);
}
if let Some(filter) = options.native_filter {
command = command.arg("-f").arg(filter);
}
if let Some(sort) = options.sort {
command = command.arg("-O").arg(sort.as_str());
}
self.server
.checked("choose tree", command)
.await
.map(|_| ())
}
pub async fn customize_mode(&self) -> Result<()> {
self.server
.checked(
"customize mode",
Command::new("customize-mode").target(self.id),
)
.await
.map(|_| ())
}
pub async fn find_window(&self, options: FindWindow) -> Result<()> {
let mut command = Command::new("find-window").target(self.id);
for (enabled, flag) in [
(options.content, "-C"),
(options.case_insensitive, "-i"),
(options.name_only, "-N"),
(options.regex, "-r"),
(options.title, "-T"),
] {
if enabled {
command = command.arg(flag);
}
}
self.server
.checked("find window", command.arg(options.pattern))
.await
.map(|_| ())
}
pub async fn send_prefix(&self, secondary: bool) -> Result<()> {
let mut command = Command::new("send-prefix").target(self.id);
if secondary {
command = command.arg("-2");
}
self.server
.checked("send prefix", command)
.await
.map(|_| ())
}
pub async fn swap_with(&self, destination: PaneId, detached: bool) -> Result<()> {
let mut command = Command::new("swap-pane").arg("-s").arg(self.id.to_string());
if detached {
command = command.arg("-d");
}
self.server
.checked("swap pane", command.arg("-t").arg(destination.to_string()))
.await
.map(|_| ())
}
pub async fn swap(&self, options: SwapPane) -> Result<()> {
if options.destination.is_some() && options.direction.is_some() {
return Err(Error::InvalidArgument {
argument: "pane swap",
message: "destination and relative direction are mutually exclusive".to_owned(),
});
}
let mut command = Command::new("swap-pane").arg("-s").arg(self.id.to_string());
if let Some(destination) = options.destination {
command = command.arg("-t").arg(destination.to_string());
}
if let Some(direction) = options.direction {
command = command.arg(match direction {
SwapPaneDirection::Up => "-U",
SwapPaneDirection::Down => "-D",
});
}
if options.detached {
command = command.arg("-d");
}
if options.keep_zoom {
command = command.arg("-Z");
}
self.server.checked("swap pane", command).await.map(|_| ())
}
pub async fn move_to(&self, options: RelocatePane) -> Result<()> {
self.relocate("move-pane", "move pane", options).await
}
pub async fn join(&self, options: RelocatePane) -> Result<()> {
self.relocate("join-pane", "join pane", options).await
}
async fn relocate(
&self,
subcommand: &'static str,
operation: &'static str,
options: RelocatePane,
) -> Result<()> {
let mut command = Command::new(subcommand)
.arg(match options.direction {
SplitDirection::Vertical => "-v",
SplitDirection::Horizontal => "-h",
})
.arg("-s")
.arg(self.id.to_string())
.arg("-t")
.arg(options.destination.to_string());
if options.detached {
command = command.arg("-d");
}
if options.full_window {
command = command.arg("-f");
}
if let Some(size) = options.size {
let size = match size {
PaneSize::Cells(cells) => cells.to_string(),
PaneSize::Percent(percent) => format!("{percent}%"),
};
command = command.arg("-l").arg(size);
}
if options.before {
command = command.arg("-b");
}
self.server.checked(operation, command).await.map(|_| ())
}
pub async fn join_to(
&self,
destination: impl Into<WindowTarget>,
horizontal: bool,
before: bool,
percent: Option<u8>,
) -> Result<()> {
if percent.is_some_and(|value| !(1..=100).contains(&value)) {
return Err(Error::InvalidArgument {
argument: "join pane percentage",
message: "must be between 1 and 100".to_owned(),
});
}
let mut command = Command::new("join-pane")
.arg("-s")
.arg(self.id.to_string())
.arg("-t")
.arg(destination.into().to_string());
if horizontal {
command = command.arg("-h");
}
if before {
command = command.arg("-b");
}
if let Some(percent) = percent {
command = command.arg("-l").arg(format!("{percent}%"));
}
self.server.checked("join pane", command).await.map(|_| ())
}
pub async fn break_to_window(&self, detached: bool, name: Option<&str>) -> Result<Window> {
let mut command = Command::new("break-pane")
.arg("-P")
.arg("-F")
.arg("#{window_id}")
.target(self.id);
if detached {
command = command.arg("-d");
}
if let Some(name) = name {
command = command.arg("-n").arg(name);
}
let result = self.server.checked("break pane", command).await?;
let id: WindowId =
crate::server::single_line(result.stdout(), "break-pane window ID")?.parse()?;
self.server
.windows()
.await?
.into_iter()
.find(|window| window.id() == id && window.session_id() == self.session_id)
.ok_or_else(|| Error::ObjectNotFound {
kind: ObjectKind::Window,
target: id.to_string(),
})
}
pub async fn respawn(&self, options: RespawnPane) -> Result<()> {
let mut command = Command::new("respawn-pane").target(self.id);
if options.kill {
command = command.arg("-k");
}
if let Some(cwd) = options.cwd {
command = command.arg("-c").arg(cwd);
}
for (name, value) in options.environment {
command =
command
.arg("-e")
.sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
}
if let Some(shell_command) = options.shell_command {
command = command.sensitive_arg(shell_command);
}
self.server
.checked("respawn pane", command)
.await
.map(|_| ())
}
pub async fn kill(&self) -> Result<()> {
self.kill_with(false).await
}
pub async fn kill_with(&self, all_except: bool) -> Result<()> {
let mut command = Command::new("kill-pane").target(self.id);
if all_except {
command = command.arg("-a");
}
self.server.checked("kill pane", command).await.map(|_| ())
}
pub async fn options(&self) -> Result<OptionMap> {
self.server
.show_options(OptionScope::Pane, Some(&self.id.to_string()))
.await
}
pub async fn sparse_options(&self) -> Result<SparseOptionMap> {
self.server
.show_sparse_options(OptionScope::Pane, Some(&self.id.to_string()))
.await
}
pub async fn set_option(&self, name: &str, value: &OptionValue, append: bool) -> Result<()> {
self.server
.set_option(
OptionScope::Pane,
Some(&self.id.to_string()),
name,
value,
append,
)
.await
}
pub async fn unset_option(&self, name: &str) -> Result<()> {
self.server
.unset_option(OptionScope::Pane, Some(&self.id.to_string()), name)
.await
}
}
impl PartialEq for Pane {
fn eq(&self, other: &Self) -> bool {
self.id == other.id && self.server.config() == other.server.config()
}
}
impl Eq for Pane {}
fn parse_parent_id<T>(
snapshot: &PaneSnapshot,
token: &'static str,
context: &'static str,
) -> Result<T>
where
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
let value = snapshot.get(token).ok_or_else(|| Error::Decode {
context,
message: format!("{token} was absent"),
})?;
let value = value.to_str().map_err(|source| Error::Decode {
context,
message: source.to_string(),
})?;
value.parse::<T>().map_err(|source| Error::Decode {
context,
message: source.to_string(),
})
}