Skip to main content

tmux_client/
window.rs

1//! Window-link snapshots, layouts, and mutations.
2
3use std::collections::BTreeMap;
4use std::ffi::OsString;
5use std::future::Future;
6use std::path::PathBuf;
7
8use crate::{
9    Command, Error, NewPane, ObjectKind, OptionMap, OptionScope, OptionValue, Pane,
10    ResizeDirection, Result, Server, Session, SessionId, SessionTarget, SparseOptionMap, SplitPane,
11    TmuxText, WindowId, WindowLink, WindowSnapshot, WindowTarget,
12};
13
14/// A built-in tmux window layout or a caller-provided layout string.
15#[derive(Clone, Debug, Eq, Hash, PartialEq)]
16pub enum Layout {
17    /// `even-horizontal`.
18    EvenHorizontal,
19    /// `even-vertical`.
20    EvenVertical,
21    /// `main-horizontal`.
22    MainHorizontal,
23    /// `main-vertical`.
24    MainVertical,
25    /// `tiled`.
26    Tiled,
27    /// A serialized or custom layout name.
28    Custom(String),
29}
30
31impl std::fmt::Display for Layout {
32    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        formatter.write_str(match self {
34            Self::EvenHorizontal => "even-horizontal",
35            Self::EvenVertical => "even-vertical",
36            Self::MainHorizontal => "main-horizontal",
37            Self::MainVertical => "main-vertical",
38            Self::Tiled => "tiled",
39            Self::Custom(value) => value,
40        })
41    }
42}
43
44/// Direction used by `rotate-window`.
45#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
46pub enum Rotation {
47    /// Rotate panes upward.
48    Up,
49    /// Rotate panes downward.
50    Down,
51}
52
53/// Placement relative to a target window.
54#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
55pub enum WindowPosition {
56    /// Insert before the target (`-b`).
57    Before,
58    /// Insert after the target (`-a`).
59    After,
60}
61
62/// Typed arguments for the three `resize-window` modes.
63#[derive(Clone, Debug, Default, Eq, PartialEq)]
64pub struct WindowResize {
65    adjustment: Option<(ResizeDirection, u32)>,
66    width: Option<u32>,
67    height: Option<u32>,
68    expand: bool,
69    shrink: bool,
70}
71
72impl WindowResize {
73    /// Creates empty resize arguments.
74    #[must_use]
75    pub fn new() -> Self {
76        Self::default()
77    }
78
79    /// Adjusts one edge by a non-zero number of cells.
80    pub fn adjustment(mut self, direction: ResizeDirection, cells: u32) -> Result<Self> {
81        if cells == 0 {
82            return Err(Error::InvalidArgument {
83                argument: "window resize adjustment",
84                message: "must be non-zero".to_owned(),
85            });
86        }
87        self.adjustment = Some((direction, cells));
88        Ok(self)
89    }
90
91    /// Sets a non-zero absolute width.
92    pub fn width(mut self, width: u32) -> Result<Self> {
93        if width == 0 {
94            return Err(Error::InvalidArgument {
95                argument: "window width",
96                message: "must be non-zero".to_owned(),
97            });
98        }
99        self.width = Some(width);
100        Ok(self)
101    }
102
103    /// Sets a non-zero absolute height.
104    pub fn height(mut self, height: u32) -> Result<Self> {
105        if height == 0 {
106            return Err(Error::InvalidArgument {
107                argument: "window height",
108                message: "must be non-zero".to_owned(),
109            });
110        }
111        self.height = Some(height);
112        Ok(self)
113    }
114
115    /// Expands the window to the available size.
116    #[must_use]
117    pub const fn expand(mut self, enabled: bool) -> Self {
118        self.expand = enabled;
119        self
120    }
121
122    /// Shrinks the window to the smallest size.
123    #[must_use]
124    pub const fn shrink(mut self, enabled: bool) -> Self {
125        self.shrink = enabled;
126        self
127    }
128}
129
130/// Typed arguments for `respawn-window`.
131#[derive(Clone, Debug, Default)]
132pub struct RespawnWindow {
133    command: Option<OsString>,
134    cwd: Option<PathBuf>,
135    environment: BTreeMap<String, OsString>,
136    kill: bool,
137}
138
139impl RespawnWindow {
140    /// Creates default respawn arguments.
141    #[must_use]
142    pub fn new() -> Self {
143        Self::default()
144    }
145
146    /// Sets the replacement command.
147    #[must_use]
148    pub fn command(mut self, command: impl Into<OsString>) -> Self {
149        self.command = Some(command.into());
150        self
151    }
152
153    /// Sets the starting directory.
154    #[must_use]
155    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
156        self.cwd = Some(cwd.into());
157        self
158    }
159
160    /// Adds an environment entry.
161    pub fn environment(
162        mut self,
163        name: impl Into<String>,
164        value: impl Into<OsString>,
165    ) -> Result<Self> {
166        let name = name.into();
167        crate::server::validate_name("environment name", &name)?;
168        self.environment.insert(name, value.into());
169        Ok(self)
170    }
171
172    /// Kills active processes before replacement.
173    #[must_use]
174    pub const fn kill(mut self, enabled: bool) -> Self {
175        self.kill = enabled;
176        self
177    }
178}
179
180/// Typed arguments for creating a window.
181#[derive(Clone, Debug)]
182pub struct NewWindow {
183    name: Option<OsString>,
184    cwd: Option<PathBuf>,
185    index: Option<u32>,
186    detached: bool,
187    kill_existing: bool,
188    shell_command: Option<OsString>,
189    environment: BTreeMap<String, OsString>,
190    relative_to: Option<WindowTarget>,
191    position: Option<WindowPosition>,
192    select_existing: bool,
193}
194
195impl Default for NewWindow {
196    fn default() -> Self {
197        Self {
198            name: None,
199            cwd: None,
200            index: None,
201            detached: true,
202            kill_existing: false,
203            shell_command: None,
204            environment: BTreeMap::new(),
205            relative_to: None,
206            position: None,
207            select_existing: false,
208        }
209    }
210}
211
212impl NewWindow {
213    /// Creates default arguments.
214    #[must_use]
215    pub fn new() -> Self {
216        Self::default()
217    }
218
219    /// Sets the window name.
220    #[must_use]
221    pub fn name(mut self, name: impl Into<OsString>) -> Self {
222        self.name = Some(name.into());
223        self
224    }
225
226    /// Sets the starting directory.
227    #[must_use]
228    pub fn cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
229        self.cwd = Some(cwd.into());
230        self
231    }
232
233    /// Places the new link at a specific index.
234    #[must_use]
235    pub const fn index(mut self, index: u32) -> Self {
236        self.index = Some(index);
237        self
238    }
239
240    /// Chooses whether the new window remains detached.
241    #[must_use]
242    pub const fn detached(mut self, detached: bool) -> Self {
243        self.detached = detached;
244        self
245    }
246
247    /// Replaces an existing link at the requested index.
248    #[must_use]
249    pub const fn kill_existing(mut self, enabled: bool) -> Self {
250        self.kill_existing = enabled;
251        self
252    }
253
254    /// Sets the command for the first pane.
255    #[must_use]
256    pub fn shell_command(mut self, command: impl Into<OsString>) -> Self {
257        self.shell_command = Some(command.into());
258        self
259    }
260
261    /// Adds a window environment entry. The value is redacted in diagnostics.
262    pub fn environment(
263        mut self,
264        name: impl Into<String>,
265        value: impl Into<OsString>,
266    ) -> Result<Self> {
267        let name = name.into();
268        crate::server::validate_name("environment name", &name)?;
269        self.environment.insert(name, value.into());
270        Ok(self)
271    }
272
273    /// Places the new window relative to an existing target.
274    #[must_use]
275    pub fn relative_to(
276        mut self,
277        target: impl Into<WindowTarget>,
278        position: WindowPosition,
279    ) -> Self {
280        self.relative_to = Some(target.into());
281        self.position = Some(position);
282        self
283    }
284
285    /// Selects an existing window with the requested name instead of creating it.
286    #[must_use]
287    pub const fn select_existing(mut self, enabled: bool) -> Self {
288        self.select_existing = enabled;
289        self
290    }
291}
292
293/// A tmux window identity plus one session-specific link and owned snapshot.
294#[derive(Clone, Debug)]
295pub struct Window {
296    server: Server,
297    id: WindowId,
298    session_id: SessionId,
299    link: WindowLink,
300    snapshot: WindowSnapshot,
301}
302
303impl Window {
304    pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
305        let snapshot = WindowSnapshot::new(row);
306        let id = snapshot.id()?.ok_or_else(|| Error::Decode {
307            context: "window row",
308            message: "window_id was empty".to_owned(),
309        })?;
310        let session_id = snapshot
311            .get("session_id")
312            .ok_or_else(|| Error::Decode {
313                context: "window row",
314                message: "session_id was absent".to_owned(),
315            })?
316            .to_str()
317            .map_err(|source| Error::Decode {
318                context: "window session ID",
319                message: source.to_string(),
320            })?
321            .parse()?;
322        let index = snapshot.index()?.ok_or_else(|| Error::Decode {
323            context: "window row",
324            message: "window_index was empty".to_owned(),
325        })?;
326        Ok(Self {
327            server,
328            id,
329            session_id,
330            link: WindowLink::new(session_id, index),
331            snapshot,
332        })
333    }
334
335    /// Resolves the window containing the pane named by `TMUX_PANE`.
336    pub async fn from_environment() -> Result<Self> {
337        Server::from_environment()?
338            .pane_from_environment()
339            .await?
340            .window()
341            .await
342    }
343
344    pub(crate) async fn create(session: &Session, options: NewWindow) -> Result<Self> {
345        let target = options.relative_to.as_ref().map_or_else(
346            || {
347                options.index.map_or_else(
348                    || session.id().to_string(),
349                    |index| format!("{}:{index}", session.id()),
350                )
351            },
352            ToString::to_string,
353        );
354        let mut command = Command::new("new-window")
355            .arg("-P")
356            .arg("-F")
357            .arg("#{window_id}")
358            .arg("-t")
359            .arg(target);
360        if options.detached {
361            command = command.arg("-d");
362        }
363        if options.kill_existing {
364            command = command.arg("-k");
365        }
366        if options.select_existing {
367            command = command.arg("-S");
368        }
369        if let Some(position) = options.position {
370            command = command.arg(match position {
371                WindowPosition::Before => "-b",
372                WindowPosition::After => "-a",
373            });
374        }
375        if let Some(name) = options.name {
376            command = command.arg("-n").arg(name);
377        }
378        if let Some(cwd) = options.cwd {
379            command = command.arg("-c").arg(cwd);
380        }
381        for (name, value) in options.environment {
382            command =
383                command
384                    .arg("-e")
385                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
386        }
387        if let Some(shell_command) = options.shell_command {
388            command = command.sensitive_arg(shell_command);
389        }
390        let result = session.server().checked("create window", command).await?;
391        let id: WindowId =
392            crate::server::single_line(result.stdout(), "new-window window ID")?.parse()?;
393        session.window(id).await
394    }
395
396    /// Returns the immutable window ID.
397    #[must_use]
398    pub const fn id(&self) -> WindowId {
399        self.id
400    }
401
402    /// Returns this session-specific window link.
403    #[must_use]
404    pub const fn link(&self) -> &WindowLink {
405        &self.link
406    }
407
408    /// Returns the owning session ID.
409    #[must_use]
410    pub const fn session_id(&self) -> SessionId {
411        self.session_id
412    }
413
414    /// Returns the owned snapshot.
415    #[must_use]
416    pub const fn snapshot(&self) -> &WindowSnapshot {
417        &self.snapshot
418    }
419
420    /// Returns the server handle.
421    #[must_use]
422    pub const fn server(&self) -> &Server {
423        &self.server
424    }
425
426    /// Refreshes this exact window link. A moved or unlinked row is stale.
427    pub async fn refresh(&mut self) -> Result<()> {
428        let link = self.link.clone();
429        *self = self
430            .server
431            .windows()
432            .await?
433            .into_iter()
434            .find(|window| window.link == link)
435            .ok_or_else(|| Error::ObjectNotFound {
436                kind: ObjectKind::Window,
437                target: link.to_string(),
438            })?;
439        Ok(())
440    }
441
442    /// Resolves the parent session.
443    pub async fn session(&self) -> Result<Session> {
444        self.server.session(self.session_id()).await
445    }
446
447    /// Resolves every session containing a link to this window.
448    pub async fn linked_sessions(&self) -> Result<Vec<Session>> {
449        let mut ids = self
450            .server
451            .windows()
452            .await?
453            .into_iter()
454            .filter(|window| window.id == self.id)
455            .map(|window| window.session_id)
456            .collect::<std::collections::BTreeSet<_>>();
457        let mut sessions = Vec::with_capacity(ids.len());
458        while let Some(id) = ids.pop_first() {
459            sessions.push(self.server.session(id).await?);
460        }
461        Ok(sessions)
462    }
463
464    /// Lists panes in this window.
465    pub async fn panes(&self) -> Result<Vec<Pane>> {
466        Ok(self
467            .server
468            .panes()
469            .await?
470            .into_iter()
471            .filter(|pane| pane.window_id() == self.id && pane.session_id() == self.session_id())
472            .collect())
473    }
474
475    /// Lists panes, returning an empty collection on failure.
476    pub async fn panes_or_empty(&self) -> Vec<Pane> {
477        self.panes().await.unwrap_or_default()
478    }
479
480    /// Returns the active pane.
481    pub async fn active_pane(&self) -> Result<Pane> {
482        for pane in self.panes().await? {
483            if pane.snapshot().active()? == Some(true) {
484                return Ok(pane);
485            }
486        }
487        Err(Error::ObjectNotFound {
488            kind: ObjectKind::Pane,
489            target: format!("active pane in {}", self.link),
490        })
491    }
492
493    /// Runs an arbitrary tmux command targeted at this exact link.
494    pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
495        self.server.cmd(command.target(&self.link)).await
496    }
497
498    /// Splits this window's active pane.
499    pub async fn split(&self, options: SplitPane) -> Result<Pane> {
500        let pane = self.active_pane().await?;
501        pane.split(options).await
502    }
503
504    /// Creates a floating pane in this window. Requires tmux 3.7+.
505    pub async fn new_pane(&self, options: NewPane) -> Result<Pane> {
506        self.active_pane().await?.new_pane(options).await
507    }
508
509    /// Creates a window before or after this link.
510    pub async fn new_window(&self, options: NewWindow, position: WindowPosition) -> Result<Window> {
511        self.session()
512            .await?
513            .new_window(options.relative_to(self.link.clone(), position))
514            .await
515    }
516
517    /// Selects a pane in this window.
518    pub async fn select_pane(&self, pane: crate::PaneId) -> Result<Pane> {
519        self.server
520            .checked(
521                "select window pane",
522                Command::new("select-pane").target(pane),
523            )
524            .await?;
525        self.server.pane(pane).await
526    }
527
528    /// Selects the last active pane.
529    pub async fn last_pane(&self) -> Result<Pane> {
530        self.last_pane_with(None, false).await
531    }
532
533    /// Selects the last active pane with explicit input and zoom behavior.
534    pub async fn last_pane_with(
535        &self,
536        input_enabled: Option<bool>,
537        keep_zoom: bool,
538    ) -> Result<Pane> {
539        let mut command = Command::new("last-pane").target(&self.link);
540        if let Some(enabled) = input_enabled {
541            command = command.arg(if enabled { "-e" } else { "-d" });
542        }
543        if keep_zoom {
544            command = command.arg("-Z");
545        }
546        self.server.checked("last pane", command).await?;
547        self.active_pane().await
548    }
549
550    /// Creates a temporary pane, runs an async operation, and attempts cleanup.
551    pub async fn with_pane<F, Fut, T>(&self, options: SplitPane, operation: F) -> Result<T>
552    where
553        F: FnOnce(Pane) -> Fut,
554        Fut: Future<Output = Result<T>>,
555    {
556        let pane = self.split(options).await?;
557        let cleanup = pane.clone();
558        let outcome = operation(pane).await;
559        let cleanup_result = cleanup.kill().await;
560        match (outcome, cleanup_result) {
561            (Ok(value), Ok(())) => Ok(value),
562            (Ok(_), Err(source)) => Err(Error::Cleanup {
563                operation: "with_pane",
564                source: Box::new(source),
565            }),
566            (Err(source), _) => Err(source),
567        }
568    }
569
570    /// Selects this window link.
571    pub async fn select(&self) -> Result<()> {
572        self.server
573            .checked(
574                "select window",
575                Command::new("select-window").target(&self.link),
576            )
577            .await
578            .map(|_| ())
579    }
580
581    /// Renames the window and refreshes the snapshot.
582    pub async fn rename(&mut self, name: impl Into<OsString>) -> Result<()> {
583        self.server
584            .checked(
585                "rename window",
586                Command::new("rename-window").target(&self.link).arg(name),
587            )
588            .await?;
589        self.refresh().await
590    }
591
592    /// Applies a built-in or serialized layout.
593    pub async fn select_layout(&mut self, layout: &Layout) -> Result<()> {
594        self.server
595            .checked(
596                "select layout",
597                Command::new("select-layout")
598                    .target(&self.link)
599                    .arg(layout.to_string()),
600            )
601            .await?;
602        self.refresh().await
603    }
604
605    /// Advances to the next built-in layout and refreshes the snapshot.
606    pub async fn next_layout(&mut self) -> Result<()> {
607        self.server
608            .checked(
609                "next layout",
610                Command::new("next-layout").target(&self.link),
611            )
612            .await?;
613        self.refresh().await
614    }
615
616    /// Returns to the previous layout and refreshes the snapshot.
617    pub async fn previous_layout(&mut self) -> Result<()> {
618        self.server
619            .checked(
620                "previous layout",
621                Command::new("previous-layout").target(&self.link),
622            )
623            .await?;
624        self.refresh().await
625    }
626
627    /// Spreads panes evenly with `select-layout -E`.
628    pub async fn spread_layout(&mut self) -> Result<()> {
629        self.server
630            .checked(
631                "spread layout",
632                Command::new("select-layout").arg("-E").target(&self.link),
633            )
634            .await?;
635        self.refresh().await
636    }
637
638    /// Resizes the window to an absolute width and/or height.
639    pub async fn resize(&mut self, width: Option<u32>, height: Option<u32>) -> Result<()> {
640        if width.is_none() && height.is_none() {
641            return Err(Error::InvalidArgument {
642                argument: "window size",
643                message: "width or height is required".to_owned(),
644            });
645        }
646        if width == Some(0) || height == Some(0) {
647            return Err(Error::InvalidArgument {
648                argument: "window size",
649                message: "dimensions must be non-zero".to_owned(),
650            });
651        }
652        let mut command = Command::new("resize-window").target(&self.link);
653        if let Some(width) = width {
654            command = command.arg("-x").arg(width.to_string());
655        }
656        if let Some(height) = height {
657            command = command.arg("-y").arg(height.to_string());
658        }
659        self.server.checked("resize window", command).await?;
660        self.refresh().await
661    }
662
663    /// Applies typed adjustment, absolute, expand, or shrink resizing.
664    pub async fn resize_with(&mut self, options: WindowResize) -> Result<()> {
665        let modes = usize::from(options.adjustment.is_some())
666            + usize::from(options.width.is_some() || options.height.is_some())
667            + usize::from(options.expand)
668            + usize::from(options.shrink);
669        if modes != 1 {
670            return Err(Error::InvalidArgument {
671                argument: "window resize mode",
672                message: "choose exactly one of adjustment, absolute size, expand, or shrink"
673                    .to_owned(),
674            });
675        }
676        let mut command = Command::new("resize-window").target(&self.link);
677        if let Some((direction, cells)) = options.adjustment {
678            command = command.arg(direction.flag()).arg(cells.to_string());
679        }
680        if let Some(width) = options.width {
681            command = command.arg("-x").arg(width.to_string());
682        }
683        if let Some(height) = options.height {
684            command = command.arg("-y").arg(height.to_string());
685        }
686        if options.expand {
687            command = command.arg("-A");
688        }
689        if options.shrink {
690            command = command.arg("-a");
691        }
692        self.server.checked("resize window", command).await?;
693        self.refresh().await
694    }
695
696    /// Rotates panes in the window.
697    pub async fn rotate(&self, direction: Rotation) -> Result<()> {
698        let mut command = Command::new("rotate-window");
699        if direction == Rotation::Down {
700            command = command.arg("-D");
701        }
702        self.server
703            .checked("rotate window", command.target(&self.link))
704            .await
705            .map(|_| ())
706    }
707
708    /// Rotates panes without unzooming the window.
709    pub async fn rotate_keep_zoom(&self, direction: Rotation) -> Result<()> {
710        let direction = match direction {
711            Rotation::Up => "-U",
712            Rotation::Down => "-D",
713        };
714        self.server
715            .checked(
716                "rotate window",
717                Command::new("rotate-window")
718                    .arg(direction)
719                    .arg("-Z")
720                    .target(&self.link),
721            )
722            .await
723            .map(|_| ())
724    }
725
726    /// Swaps this window with another target.
727    pub async fn swap_with(
728        &self,
729        destination: impl Into<WindowTarget>,
730        detached: bool,
731    ) -> Result<()> {
732        let mut command = Command::new("swap-window")
733            .arg("-s")
734            .arg(self.link.to_string());
735        if detached {
736            command = command.arg("-d");
737        }
738        command = command.arg("-t").arg(destination.into().to_string());
739        self.server
740            .checked("swap window", command)
741            .await
742            .map(|_| ())
743    }
744
745    /// Links this window into another session and returns the new link snapshot.
746    pub async fn link_to(
747        &self,
748        session: impl Into<SessionTarget>,
749        index: Option<u32>,
750        kill_existing: bool,
751    ) -> Result<Window> {
752        self.link_to_with(session, index, kill_existing, None, true)
753            .await
754    }
755
756    /// Links this window with placement and selection flags.
757    pub async fn link_to_with(
758        &self,
759        session: impl Into<SessionTarget>,
760        index: Option<u32>,
761        kill_existing: bool,
762        position: Option<WindowPosition>,
763        detached: bool,
764    ) -> Result<Window> {
765        let session = session.into();
766        let destination_session_id = match &session {
767            SessionTarget::Id(id) => *id,
768            SessionTarget::Name(name) => self.server.session_by_name(name).await?.id(),
769        };
770        let destination =
771            index.map_or_else(|| session.to_string(), |index| format!("{session}:{index}"));
772        let mut command = Command::new("link-window")
773            .arg("-s")
774            .arg(self.link.to_string())
775            .arg("-t")
776            .arg(&destination);
777        if kill_existing {
778            command = command.arg("-k");
779        }
780        if let Some(position) = position {
781            command = command.arg(match position {
782                WindowPosition::Before => "-b",
783                WindowPosition::After => "-a",
784            });
785        }
786        if detached {
787            command = command.arg("-d");
788        }
789        self.server.checked("link window", command).await?;
790        self.server
791            .windows()
792            .await?
793            .into_iter()
794            .find(|window| {
795                window.id == self.id
796                    && window.session_id == destination_session_id
797                    && index.is_none_or(|index| window.link.index() == index)
798            })
799            .ok_or(Error::ObjectNotFound {
800                kind: ObjectKind::Window,
801                target: destination,
802            })
803    }
804
805    /// Moves this link to another destination.
806    pub async fn move_to(
807        &self,
808        session: impl Into<SessionTarget>,
809        index: Option<u32>,
810        kill_existing: bool,
811    ) -> Result<()> {
812        self.move_to_with(session, index, kill_existing, None, true)
813            .await
814    }
815
816    /// Moves this window with placement and selection flags.
817    pub async fn move_to_with(
818        &self,
819        session: impl Into<SessionTarget>,
820        index: Option<u32>,
821        kill_existing: bool,
822        position: Option<WindowPosition>,
823        detached: bool,
824    ) -> Result<()> {
825        let session = session.into();
826        let destination =
827            index.map_or_else(|| session.to_string(), |index| format!("{session}:{index}"));
828        let mut command = Command::new("move-window")
829            .arg("-s")
830            .arg(self.link.to_string())
831            .arg("-t")
832            .arg(destination);
833        if kill_existing {
834            command = command.arg("-k");
835        }
836        if let Some(position) = position {
837            command = command.arg(match position {
838                WindowPosition::Before => "-b",
839                WindowPosition::After => "-a",
840            });
841        }
842        if detached {
843            command = command.arg("-d");
844        }
845        self.server
846            .checked("move window", command)
847            .await
848            .map(|_| ())
849    }
850
851    /// Unlinks this window from its session.
852    pub async fn unlink(&self, kill_if_last: bool) -> Result<()> {
853        let mut command = Command::new("unlink-window");
854        if kill_if_last {
855            command = command.arg("-k");
856        }
857        self.server
858            .checked("unlink window", command.target(&self.link))
859            .await
860            .map(|_| ())
861    }
862
863    /// Respawns the active pane for this window.
864    pub async fn respawn(
865        &self,
866        command: Option<OsString>,
867        cwd: Option<PathBuf>,
868        kill: bool,
869    ) -> Result<()> {
870        let mut tmux = Command::new("respawn-window").target(&self.link);
871        if kill {
872            tmux = tmux.arg("-k");
873        }
874        if let Some(cwd) = cwd {
875            tmux = tmux.arg("-c").arg(cwd);
876        }
877        if let Some(command) = command {
878            tmux = tmux.sensitive_arg(command);
879        }
880        self.server
881            .checked("respawn window", tmux)
882            .await
883            .map(|_| ())
884    }
885
886    /// Respawns a window with typed environment and process arguments.
887    pub async fn respawn_with(&self, options: RespawnWindow) -> Result<()> {
888        let mut command = Command::new("respawn-window").target(&self.link);
889        if options.kill {
890            command = command.arg("-k");
891        }
892        if let Some(cwd) = options.cwd {
893            command = command.arg("-c").arg(cwd);
894        }
895        for (name, value) in options.environment {
896            command =
897                command
898                    .arg("-e")
899                    .sensitive_arg(format!("{}={}", name, value.to_string_lossy()));
900        }
901        if let Some(shell_command) = options.command {
902            command = command.sensitive_arg(shell_command);
903        }
904        self.server
905            .checked("respawn window", command)
906            .await
907            .map(|_| ())
908    }
909
910    /// Destroys the underlying window and all of its links.
911    pub async fn kill(&self) -> Result<()> {
912        self.server
913            .checked("kill window", Command::new("kill-window").target(self.id))
914            .await
915            .map(|_| ())
916    }
917
918    /// Kills every other window in this session.
919    pub async fn kill_others(&self) -> Result<()> {
920        self.server
921            .checked(
922                "kill other windows",
923                Command::new("kill-window").arg("-a").target(&self.link),
924            )
925            .await
926            .map(|_| ())
927    }
928
929    /// Shows window-scoped options.
930    pub async fn options(&self) -> Result<OptionMap> {
931        self.server
932            .show_options(OptionScope::Window, Some(&self.link.to_string()))
933            .await
934    }
935
936    /// Shows sparse window options and hooks.
937    pub async fn sparse_options(&self) -> Result<SparseOptionMap> {
938        self.server
939            .show_sparse_options(OptionScope::Window, Some(&self.link.to_string()))
940            .await
941    }
942
943    /// Sets a window option.
944    pub async fn set_option(&self, name: &str, value: &OptionValue, append: bool) -> Result<()> {
945        self.server
946            .set_option(
947                OptionScope::Window,
948                Some(&self.link.to_string()),
949                name,
950                value,
951                append,
952            )
953            .await
954    }
955
956    /// Unsets a window option.
957    pub async fn unset_option(&self, name: &str) -> Result<()> {
958        self.server
959            .unset_option(OptionScope::Window, Some(&self.link.to_string()), name)
960            .await
961    }
962}
963
964impl PartialEq for Window {
965    fn eq(&self, other: &Self) -> bool {
966        self.id == other.id
967            && self.link == other.link
968            && self.server.config() == other.server.config()
969    }
970}
971
972impl Eq for Window {}