libtmux 0.1.0-alpha.16

Async typed tmux client and object model (alpha)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Operations that make or address a pane.
//!
//! `split-window` lives here rather than with the windows: it is addressed at
//! a window but the object it produces, and everything that follows it in a
//! plan, is a pane.

use crate::escape_format;
use std::ffi::OsString;
use std::fmt;

use super::{
    Chainable, Effects, Op, Operation, PaneSlot, PaneTarget, Safety, Scope, Slot, WindowTarget,
};
use super::{PANE_FORMAT, Resolver};
#[cfg(feature = "serde")]
use crate::plan::ProducerIdentity;
use crate::plan::SlotUse;
use crate::window::assignment;
use crate::{Command, SplitDirection};

/// `split-window`'s `-t`: a window (its active pane divides) or an exact
/// pane. `-t <window>` always resolves to the active pane, which a
/// detached split never changes, so a chain of splits needs the pane
/// form (`SplitWindow::from_pane`) after the first.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum SplitTarget {
    /// Divides whichever pane in the window is currently active.
    Window(
        /// The window whose active pane will be split.
        WindowTarget,
    ),
    /// Divides this exact pane, regardless of which one is active.
    Pane(
        /// The pane to split, independent of the window's active pane.
        PaneTarget,
    ),
}

impl SplitTarget {
    pub(in crate::plan) fn slot(&self) -> Option<SlotUse> {
        match self {
            Self::Window(target) => target.slot(),
            Self::Pane(target) => target.slot(),
        }
    }

    #[cfg(feature = "serde")]
    pub(in crate::plan) fn rebind(&mut self, producers: &[Option<ProducerIdentity>]) {
        match self {
            Self::Window(target) => target.rebind(producers),
            Self::Pane(target) => target.rebind(producers),
        }
    }

    pub(crate) fn token(&self, resolve: Resolver<'_>) -> Option<OsString> {
        match self {
            Self::Window(target) => target.token(resolve),
            Self::Pane(target) => target.token(resolve),
        }
    }
}

/// An older plan stores a bare [`WindowTarget`] here instead of today's
/// tagged `{"Window":...}`/`{"Pane":...}`; the two shapes share no tag
/// name, so falling back to the bare form is unambiguous.
#[cfg(feature = "serde")]
fn deserialize_split_target<'de, D>(deserializer: D) -> Result<SplitTarget, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::Deserialize as _;

    #[derive(serde::Deserialize)]
    #[serde(untagged)]
    enum Wire {
        Current(SplitTarget),
        Legacy(WindowTarget),
    }
    Ok(match Wire::deserialize(deserializer)? {
        Wire::Current(target) => target,
        Wire::Legacy(target) => SplitTarget::Window(target),
    })
}

/// Split a window, making a pane.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SplitWindow {
    #[cfg_attr(
        feature = "serde",
        serde(deserialize_with = "deserialize_split_target")
    )]
    pub(crate) target: SplitTarget,
    vertical: bool,
    /// tmux's `-b`, which puts the new pane before the one being divided.
    ///
    /// Defaulted rather than required, so a plan serialized before this
    /// existed still decodes: `deny_unknown_fields` refuses keys it does not
    /// know, not keys that are absent.
    #[cfg_attr(feature = "serde", serde(default))]
    before: bool,
    #[cfg_attr(
        feature = "serde",
        serde(
            serialize_with = "crate::plan::wire::optional_argument",
            deserialize_with = "crate::plan::wire::parse_optional_argument"
        )
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<crate::plan::wire::Argument>")
    )]
    start_directory: Option<OsString>,
    #[cfg_attr(
        feature = "serde",
        serde(
            serialize_with = "crate::plan::wire::optional_argument",
            deserialize_with = "crate::plan::wire::parse_optional_argument"
        )
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<crate::plan::wire::Argument>")
    )]
    command: Option<OsString>,
    #[cfg_attr(
        feature = "serde",
        serde(
            serialize_with = "crate::plan::wire::pairs",
            deserialize_with = "crate::plan::wire::parse_pairs"
        )
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Vec<(crate::plan::wire::Argument, crate::plan::wire::Argument)>")
    )]
    environment: Vec<(OsString, OsString)>,
    focus: bool,
}

impl SplitWindow {
    /// Split this window, leaving the new pane unfocused.
    ///
    /// Divides whichever pane is active. [`SplitWindow::from_pane`] is for
    /// every split after the first in a chain.
    #[must_use]
    pub fn new(target: impl Into<WindowTarget>) -> Self {
        Self {
            target: SplitTarget::Window(target.into()),
            vertical: true,
            before: false,
            start_directory: None,
            command: None,
            environment: Vec::new(),
            focus: false,
        }
    }

    /// Split this pane, putting a new one beside it.
    ///
    /// Unlike [`SplitWindow::new`], divides the exact pane named -- pass
    /// the [`Slot<PaneSlot>`] the previous split, or [`Slot::pane`], made.
    ///
    /// [`Slot::pane`]: crate::plan::Slot::pane
    #[must_use]
    pub fn from_pane(target: impl Into<PaneTarget>) -> Self {
        Self {
            target: SplitTarget::Pane(target.into()),
            vertical: true,
            before: false,
            start_directory: None,
            command: None,
            environment: Vec::new(),
            focus: false,
        }
    }

    /// Set a variable in the new pane's environment before it starts.
    #[must_use]
    pub fn environment(mut self, name: impl Into<OsString>, value: impl Into<OsString>) -> Self {
        self.environment.push((name.into(), value.into()));
        self
    }

    /// Split side by side rather than one above the other.
    ///
    /// Exactly [`SplitDirection::Right`], and defined as it so the two cannot
    /// disagree. Kept because it is the spelling this operation shipped with.
    ///
    /// It sets the side as well as the axis, so it is the whole position
    /// rather than half of one: `direction(Above).horizontal()` is `Right`,
    /// not `Left`. Either setter, in either order, leaves one of the four
    /// positions and never a mix of two.
    #[must_use]
    pub const fn horizontal(self) -> Self {
        self.direction(SplitDirection::Right)
    }

    /// Put the new pane on this side of the one being divided.
    ///
    /// The default is [`SplitDirection::Below`], which is tmux's. `Above` and
    /// `Left` need tmux's `-b`, so they are reachable only through this: with
    /// [`SplitWindow::horizontal`] alone a plan could ask for two of the four
    /// positions, while the object API's [`crate::SplitOptions`] has always
    /// offered all four.
    ///
    /// # Examples
    ///
    /// ```
    /// use libtmux::SplitDirection;
    /// use libtmux::plan::{NewSession, Plan, SplitWindow};
    ///
    /// let mut plan = Plan::new();
    /// let session = plan.add(NewSession::new("above"));
    /// plan.add(SplitWindow::new(session.window()).direction(SplitDirection::Above));
    ///
    /// assert_eq!(plan.len(), 2);
    /// ```
    #[must_use]
    pub const fn direction(mut self, direction: SplitDirection) -> Self {
        self.vertical = direction.is_vertical();
        self.before = direction.before();
        self
    }

    /// Start the new pane in this directory.
    ///
    /// tmux expands this as a format, so [`crate::escape_format`] belongs
    /// around text a program did not write.
    #[must_use]
    pub fn start_directory(mut self, directory: impl Into<OsString>) -> Self {
        self.start_directory = Some(directory.into());
        self
    }

    /// Run this instead of a shell in the new pane.
    #[must_use]
    pub fn command(mut self, command: impl Into<OsString>) -> Self {
        self.command = Some(command.into());
        self
    }

    /// Leave the new pane focused.
    ///
    /// A focused split is what makes the `{marked}` fold available: the
    /// register the fold marks is the active pane.
    #[must_use]
    pub const fn focus(mut self) -> Self {
        self.focus = true;
        self
    }

    pub(crate) const fn focuses(&self) -> bool {
        self.focus
    }

    pub(crate) fn render(&self, resolve: Resolver<'_>) -> Option<Command> {
        let mut command = Command::new("split-window")
            .arg("-P")
            .arg("-F")
            .arg(PANE_FORMAT)
            .arg("-t")
            .arg(self.target.token(resolve)?)
            .arg(if self.vertical { "-v" } else { "-h" });
        if self.before {
            command = command.arg("-b");
        }
        if !self.focus {
            command = command.arg("-d");
        }
        if let Some(directory) = &self.start_directory {
            command = command.arg("-c").arg(escape_format(directory));
        }
        for (name, value) in &self.environment {
            command = command.arg("-e").sensitive_arg(assignment(name, value));
        }
        if let Some(shell_command) = &self.command {
            command = command.arg("--").sensitive_arg(shell_command.clone());
        }
        Some(command)
    }
}

impl fmt::Debug for SplitWindow {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SplitWindow")
            .field("target", &self.target)
            .field("vertical", &self.vertical)
            .field("before", &self.before)
            .field("has_start_directory", &self.start_directory.is_some())
            .field("has_command", &self.command.is_some())
            .field("environment_count", &self.environment.len())
            .field("focus", &self.focus)
            .finish()
    }
}

operation!(
    SplitWindow,
    creates = Slot<PaneSlot>,
    effects = Effects {
        creates: Some(Scope::Pane),
        ..Effects::MUTATING
    },
    safety = Safety::Mutating
);

/// Send text or named keys to a pane.
///
/// [`SendKeys::text`] and [`SendKeys::keys`] cannot both be set: tmux
/// resolves every `send-keys` argument against its key table unless `-l`
/// literalizes it, and `-l` covers every argument of the `send-keys` it sits
/// on. So literal text and named keys cannot share one `send-keys`, though
/// two of them still share one tmux invocation under a folding planner.
/// [`crate::plan::Plan::validate`] rejects a `SendKeys` that carries both,
/// before a plan runs.
#[derive(Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SendKeys {
    pub(crate) target: PaneTarget,
    #[cfg_attr(
        feature = "serde",
        serde(
            serialize_with = "crate::plan::wire::optional_argument",
            deserialize_with = "crate::plan::wire::parse_optional_argument"
        )
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<crate::plan::wire::Argument>")
    )]
    text: Option<OsString>,
    #[cfg_attr(
        feature = "serde",
        serde(
            serialize_with = "crate::plan::wire::list",
            deserialize_with = "crate::plan::wire::parse_list"
        )
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Vec<crate::plan::wire::Argument>")
    )]
    keys: Vec<OsString>,
    enter: bool,
}

impl SendKeys {
    /// Address this pane.
    #[must_use]
    pub fn new(target: impl Into<PaneTarget>) -> Self {
        Self {
            target: target.into(),
            text: None,
            keys: Vec::new(),
            enter: false,
        }
    }

    /// Send this literal text.
    ///
    /// Rendered with tmux's `-l` flag, so every byte is typed rather than
    /// looked up in the key table first -- text that happens to name a key,
    /// such as `"Space"`, is typed rather than pressed. `-l` literalizes every
    /// argument of the `send-keys` it is on, so this cannot be combined with
    /// [`SendKeys::keys`]: [`crate::plan::Plan::validate`] rejects that
    /// combination before anything runs.
    #[must_use]
    pub fn text(mut self, text: impl Into<OsString>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Send named keys such as `C-c` or `Escape`.
    ///
    /// Resolved against tmux's key table, which is why this cannot be
    /// combined with [`SendKeys::text`]: literal text needs `-l`, and `-l`
    /// would literalize these too. [`crate::plan::Plan::validate`] rejects
    /// the combination before anything runs.
    #[must_use]
    pub fn keys<K: Into<OsString>>(mut self, keys: impl IntoIterator<Item = K>) -> Self {
        self.keys = keys.into_iter().map(Into::into).collect();
        self
    }

    /// Follow the text with Enter.
    ///
    /// When literal text is set, Enter is folded into it as a trailing
    /// carriage return rather than sent as a separate named key -- the same
    /// dispatch [`crate::Pane::send_line`] uses to submit a line in one
    /// command. Without text, Enter renders as the named key after
    /// whatever [`SendKeys::keys`] sends.
    #[must_use]
    pub const fn enter(mut self) -> Self {
        self.enter = true;
        self
    }

    /// Whether this cannot render as one `send-keys`.
    ///
    /// Literal text needs `-l`, and `-l` literalizes every argument of the
    /// same `send-keys`, so a named key cannot survive alongside text. Enter
    /// is not a named key here: [`SendKeys::render`] folds it into the
    /// literal payload instead, so it never conflicts.
    pub(crate) fn text_conflicts_with_keys(&self) -> bool {
        self.text.is_some() && !self.keys.is_empty()
    }

    pub(crate) fn render(&self, resolve: Resolver<'_>) -> Option<Command> {
        let mut command = Command::new("send-keys")
            .arg("-t")
            .arg(self.target.token(resolve)?);
        if let Some(text) = &self.text {
            // `-l` literalizes every argument of this `send-keys`. Enter is
            // folded into the payload as a trailing carriage return instead
            // of the named key `Enter`, matching how `Pane::send_line`
            // dispatches a line for the object API. A plan carrying `keys`
            // here as well is rejected by `Plan::validate` before this runs.
            let mut literal = text.clone();
            if self.enter {
                literal.push("\r");
            }
            command = command.arg("-l").arg("--").sensitive_arg(literal);
        } else if !self.keys.is_empty() || self.enter {
            // Everything after `--` is a value, so a key name that starts
            // with a dash is typed rather than read as a flag.
            command = command.arg("--");
            for key in &self.keys {
                command = command.arg(key.clone());
            }
            if self.enter {
                command = command.arg("Enter");
            }
        }
        Some(command)
    }
}

impl fmt::Debug for SendKeys {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SendKeys")
            .field("target", &self.target)
            .field("has_text", &self.text.is_some())
            .field("key_count", &self.keys.len())
            .field("enter", &self.enter)
            .finish()
    }
}

operation!(
    SendKeys,
    creates = (),
    effects = Effects::MUTATING,
    safety = Safety::Mutating,
    chainable
);

/// Make a pane the active one.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SelectPane {
    pub(crate) target: PaneTarget,
}

impl SelectPane {
    /// Focus this pane.
    #[must_use]
    pub fn new(target: impl Into<PaneTarget>) -> Self {
        Self {
            target: target.into(),
        }
    }

    pub(crate) fn render(&self, resolve: Resolver<'_>) -> Option<Command> {
        Some(
            Command::new("select-pane")
                .arg("-t")
                .arg(self.target.token(resolve)?),
        )
    }
}

operation!(
    SelectPane,
    creates = (),
    effects = Effects {
        idempotent: true,
        ..Effects::MUTATING
    },
    safety = Safety::Mutating,
    chainable
);

/// Read a pane's contents.
///
/// Deliberately not [`Chainable`]: its stdout is the answer, and a folded run
/// returns one merged stdout with no per-command boundary, so folding it would
/// mix its lines with its neighbours'.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CapturePane {
    pub(crate) target: PaneTarget,
    escape_sequences: bool,
}

impl CapturePane {
    /// Capture this pane.
    #[must_use]
    pub fn new(target: impl Into<PaneTarget>) -> Self {
        Self {
            target: target.into(),
            escape_sequences: false,
        }
    }

    /// Keep the escape sequences rather than the plain text.
    #[must_use]
    pub const fn escape_sequences(mut self) -> Self {
        self.escape_sequences = true;
        self
    }

    pub(crate) fn render(&self, resolve: Resolver<'_>) -> Option<Command> {
        let mut command = Command::new("capture-pane")
            .arg("-p")
            .arg("-t")
            .arg(self.target.token(resolve)?);
        if self.escape_sequences {
            command = command.arg("-e");
        }
        Some(command)
    }
}

operation!(
    CapturePane,
    creates = (),
    effects = Effects {
        read_only: true,
        idempotent: true,
        reads_output: true,
        ..Effects::MUTATING
    },
    safety = Safety::ReadOnly
);

/// Destroy a pane.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct KillPane {
    pub(crate) target: PaneTarget,
}

impl KillPane {
    /// Kill this pane.
    #[must_use]
    pub fn new(target: impl Into<PaneTarget>) -> Self {
        Self {
            target: target.into(),
        }
    }

    /// The pane this operation will destroy.
    #[must_use]
    pub const fn target(&self) -> &PaneTarget {
        &self.target
    }

    pub(crate) fn render(&self, resolve: Resolver<'_>) -> Option<Command> {
        Some(
            Command::new("kill-pane")
                .arg("-t")
                .arg(self.target.token(resolve)?),
        )
    }
}

operation!(
    KillPane,
    creates = (),
    effects = Effects {
        destructive: true,
        ..Effects::MUTATING
    },
    safety = Safety::Destructive,
    chainable
);