1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use std::collections::BTreeMap;
use std::ffi::OsString;
use super::Server;
use crate::formats::TmuxText;
use crate::internal::{environment, options};
use crate::{EnvironmentEntry, Error, IndexedHooks, OptionValue, ReplaceMode, SparseValues};
/// The table tmux keeps an array option in, reached from a `Server` handle.
///
/// tmux's eight array options span three tables: `command-alias` and the
/// terminal ones are server options, `status-format` and `update-environment`
/// session ones, and `pane-colours` belongs to a window and a pane both. This
/// handle offers one family of methods for all of them, so the name has to
/// pick the table. Sending one scope for every name reached the right table
/// only because tmux resolves an option by its name and ignored the flag.
///
/// For an option that is not the server's, the global table is the
/// server-wide default this handle can address; a particular session's or
/// window's copy is reached through that object's own handle.
fn array_scope(name: &str) -> options::Scope<'static> {
match crate::option_schema(name).map(crate::OptionSchema::scopes) {
Some(scopes) if scopes.contains(&crate::OptionScope::Server) => options::Scope::Server,
Some(scopes) if scopes.contains(&crate::OptionScope::Window) => {
options::Scope::GlobalWindow
}
_ => options::Scope::GlobalSession,
}
}
impl Server {
/// List the server option names.
///
/// Values are not included: tmux renders them for display with three
/// different quoting styles, so re-parsing them would be guesswork. Read
/// each value with [`Self::typed_option`], which decodes the exact bytes.
///
/// Names are `String`, not [`TmuxText`](crate::TmuxText), because tmux's
/// own are ASCII and every option method takes one as `&str`; a user
/// option (`@name`) lists cut at any whitespace in its name, and with
/// U+FFFD for bytes that are not UTF-8, since `show-options` prints names
/// unframed.
///
/// # Errors
///
/// Returns an error when tmux refuses the listing.
pub async fn option_names(&self) -> Result<Vec<String>, Error> {
options::names(&self.core, options::Scope::Server).await
}
/// Read every option set at this server, decoded by its declared kind.
///
/// Costs one tmux command per option, because each value is read as the
/// bytes tmux stored rather than the form it lists them in. Use
/// [`Self::option_names`] when only the names are wanted, and
/// [`Self::typed_option`] for one value.
///
/// An array option keeps the indexed name tmux lists it under, so
/// `command-alias[0]` and `command-alias[1]` are separate entries.
///
/// Reports what is set *at this scope*, not what the object resolves to.
/// A session that has set nothing of its own answers empty even though
/// every option still has an effective value it inherits.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached or refuses the listing.
/// An empty map means nothing is set, never that the listing failed.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// server.set_option("buffer-limit", "42").await?;
/// let options = server.options().await?;
/// assert!(options.contains_key("buffer-limit"));
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn options(&self) -> Result<BTreeMap<String, OptionValue>, Error> {
options::typed_all(&self.core, options::Scope::Server).await
}
/// Set one server option to text, unchecked.
///
/// tmux validates the value itself. [`Self::set_typed_option`] checks it
/// against tmux's option table first; [`OptionValue`] compares the two.
///
/// # Errors
///
/// Returns an error when tmux rejects the name or value.
pub async fn set_option(&self, name: &str, value: impl Into<OsString>) -> Result<(), Error> {
options::set(&self.core, options::Scope::Server, name, value, false).await
}
/// Set one server option to a typed value, checked before it is sent.
///
/// The value must be the variant [`Self::typed_option`] reads back for
/// the option; [`OptionValue`] gives the rules, and what is not checked.
///
/// # Errors
///
/// Returns [`Error::OptionValueRefused`] without sending anything when
/// tmux's option table refuses the value, and
/// [`Error::OptionScopeMismatch`] when the option is not a server option.
/// Otherwise returns an error when tmux rejects the name or value.
///
/// # Examples
///
/// ```no_run
/// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
/// server.set_typed_option("escape-time", 10).await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_typed_option(
&self,
name: &str,
value: impl Into<OptionValue>,
) -> Result<(), Error> {
options::set_typed(&self.core, options::Scope::Server, name, value.into()).await
}
/// Remove one server option.
///
/// # Errors
///
/// Returns an error when tmux rejects the name.
pub async fn unset_option(&self, name: &str) -> Result<(), Error> {
options::unset(&self.core, options::Scope::Server, name).await
}
/// Set one global session option to text, unchecked.
///
/// Sessions inherit from this table, so it is where a default belongs.
/// [`Self::set_typed_global_option`] checks the value first.
///
/// # Errors
///
/// Returns an error when tmux rejects the name or value.
pub async fn set_global_option(
&self,
name: &str,
value: impl Into<OsString>,
) -> Result<(), Error> {
options::set(
&self.core,
options::Scope::GlobalSession,
name,
value,
false,
)
.await
}
/// Set one global session option to a typed value, checked before it is
/// sent.
///
/// The value must be the variant [`Self::typed_global_option`] reads back
/// for the option; [`OptionValue`] gives the rules, and what is not
/// checked.
///
/// # Errors
///
/// Returns [`Error::OptionValueRefused`] without sending anything when
/// tmux's option table refuses the value, and
/// [`Error::OptionScopeMismatch`] when the option is not a session option.
/// Otherwise returns an error when tmux rejects the name or value.
///
/// # Examples
///
/// ```no_run
/// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
/// server.set_typed_global_option("mouse", true).await?;
/// server.set_typed_global_option("history-limit", 50_000).await?;
/// server.set_typed_global_option("status-position", "top").await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_typed_global_option(
&self,
name: &str,
value: impl Into<OptionValue>,
) -> Result<(), Error> {
options::set_typed(
&self.core,
options::Scope::GlobalSession,
name,
value.into(),
)
.await
}
/// Set a variable in the server's own environment.
///
/// tmux keeps this and each session's environment in separate stores, and
/// merges them only when it starts a process. So a name set here is
/// reported as an unknown variable by
/// [`Session::environment`](crate::Session::environment) -- reading
/// a session does not fall back to the server -- while a pane started
/// afterwards is handed it all the same.
///
/// Where both hold a name, the session's value is the one the process
/// gets. [`Self::hide_environment`] removes the name from the merge
/// entirely.
///
/// Panes already running keep the environment they were started with.
///
/// The value is marked sensitive, since an environment carries tokens.
///
/// # Errors
///
/// Returns an error when tmux rejects the name or value.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// use libtmux::EnvironmentEntry;
///
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// server.set_environment("EDITOR", "hx").await?;
/// assert!(matches!(
/// server.environment("EDITOR").await?,
/// Some(EnvironmentEntry::Set(value)) if value.as_bytes() == b"hx",
/// ));
///
/// // Separate stores: the session has no entry of its own, and reading it
/// // does not fall back to the server. The value still reaches a process
/// // the session starts.
/// let session = server.new_session("separate").await?;
/// assert_eq!(session.environment("EDITOR").await?, None);
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn set_environment(
&self,
name: &str,
value: impl Into<OsString>,
) -> Result<(), Error> {
environment::set(&self.core, environment::Scope::Global, name, value.into()).await
}
/// Read one variable from the server's environment.
///
/// tmux keeps two different things under a name: a value, and a mark
/// saying a process started from it must not inherit the name at all.
/// [`EnvironmentEntry`] keeps them apart, because collapsing both to
/// absence would hide the second, which a caller sets deliberately with
/// [`Self::hide_environment`].
///
/// `None` means tmux holds nothing under the name.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached.
pub async fn environment(&self, name: &str) -> Result<Option<EnvironmentEntry>, Error> {
environment::get(&self.core, environment::Scope::Global, name).await
}
/// Read the server's whole environment.
///
/// Costs one tmux command, read the way
/// [`Session::environment_all`](crate::Session::environment_all)
/// describes: each value reads exactly as [`Self::environment`] reads it.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached or refuses the listing,
/// and [`Error::DecodeListing`] when the listing is not in the shape tmux
/// prints. An empty map means the server holds nothing, never that the
/// listing failed.
pub async fn environment_all(&self) -> Result<BTreeMap<String, EnvironmentEntry>, Error> {
environment::all(&self.core, environment::Scope::Global).await
}
/// Hide a variable from processes tmux starts.
///
/// Different from [`Self::unset_environment`], which deletes the server's
/// own entry and lets whatever tmux was started with show through. This
/// keeps an entry and marks it, so a process started afterwards is handed
/// an environment with the name *absent* even though the tmux server was
/// started with one. It is what [`EnvironmentEntry::Removed`] reports.
///
/// # Errors
///
/// Returns an error when tmux rejects the name.
pub async fn hide_environment(&self, name: &str) -> Result<(), Error> {
environment::hide(&self.core, environment::Scope::Global, name).await
}
/// Remove a variable from the server's environment.
///
/// # Errors
///
/// Returns an error when tmux rejects the name.
pub async fn unset_environment(&self, name: &str) -> Result<(), Error> {
environment::unset(&self.core, environment::Scope::Global, name).await
}
/// Read every value an array option holds, by index.
///
/// Some tmux options hold a numbered set rather than one value:
/// `command-alias` and `terminal-overrides` are the common ones, and every
/// hook is one too. The indices are sparse and tmux keeps the gaps, so
/// this reports them rather than a list. An empty result means the option
/// holds nothing.
///
/// # Errors
///
/// Returns an error when tmux does not recognize the option name.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// // Written far apart on purpose: nothing renumbers, so the gap stays.
/// server.set_array_option("command-alias", 30, "thirty=display -p 30").await?;
/// server.set_array_option("command-alias", 35, "five=display -p 35").await?;
///
/// let aliases = server.array_option("command-alias").await?;
/// assert_eq!(aliases.get(31), None, "the gap is tmux's, and it is kept");
/// assert_eq!(
/// aliases.get(35).map(|value| value.to_string_lossy().into_owned()),
/// Some("five=display -p 35".to_owned()),
/// );
///
/// server.unset_array_option("command-alias", 35).await?;
/// assert_eq!(server.array_option("command-alias").await?.get(35), None);
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn array_option(&self, name: &str) -> Result<SparseValues<TmuxText>, Error> {
Ok(SparseValues::from(
options::indexed(&self.core, array_scope(name), name).await?,
))
}
/// Write one index of an array option, leaving the others alone.
///
/// # Errors
///
/// Returns an error when tmux refuses the option name or the value.
pub async fn set_array_option(
&self,
name: &str,
index: u32,
value: impl Into<OsString>,
) -> Result<(), Error> {
options::set(
&self.core,
array_scope(name),
&format!("{name}[{index}]"),
value,
false,
)
.await
}
/// Extend the value already at one index of an array option.
///
/// Appends to that index's value rather than adding an entry, which is
/// what tmux's `-a` does here.
///
/// # Errors
///
/// Returns an error when tmux refuses the option name or the value.
pub async fn append_array_option(
&self,
name: &str,
index: u32,
value: impl Into<OsString>,
) -> Result<(), Error> {
options::set(
&self.core,
array_scope(name),
&format!("{name}[{index}]"),
value,
true,
)
.await
}
/// Remove one index of an array option, leaving a gap where it was.
///
/// # Errors
///
/// Returns an error when tmux refuses the option name.
pub async fn unset_array_option(&self, name: &str, index: u32) -> Result<(), Error> {
options::unset(&self.core, array_scope(name), &format!("{name}[{index}]")).await
}
/// Set one global window option to text, unchecked.
///
/// [`Self::set_typed_global_window_option`] checks the value first.
///
/// # Errors
///
/// Returns an error when tmux rejects the name or value.
pub async fn set_global_window_option(
&self,
name: &str,
value: impl Into<OsString>,
) -> Result<(), Error> {
options::set(&self.core, options::Scope::GlobalWindow, name, value, false).await
}
/// Set one global window option to a typed value, checked before it is
/// sent.
///
/// The value must be the variant [`Self::typed_global_window_option`]
/// reads back for the option; [`OptionValue`] gives the rules, and what
/// is not checked.
///
/// # Errors
///
/// Returns [`Error::OptionValueRefused`] without sending anything when
/// tmux's option table refuses the value, and
/// [`Error::OptionScopeMismatch`] when the option is not a window option.
/// Otherwise returns an error when tmux rejects the name or value.
///
/// # Examples
///
/// ```no_run
/// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
/// server.set_typed_global_window_option("mode-keys", "vi").await?;
/// # Ok(())
/// # }
/// ```
pub async fn set_typed_global_window_option(
&self,
name: &str,
value: impl Into<OptionValue>,
) -> Result<(), Error> {
options::set_typed(&self.core, options::Scope::GlobalWindow, name, value.into()).await
}
/// Set one global hook.
///
/// Hooks live in the option tables, so [`Server::typed_global_option`]
/// reads one back under an indexed name such as `after-new-window[0]`.
///
/// # Errors
///
/// Returns an error when tmux rejects the hook name or command.
pub async fn set_hook(&self, name: &str, command: impl Into<OsString>) -> Result<(), Error> {
options::set_hook(&self.core, options::Scope::GlobalSession, name, command).await
}
/// Remove one global hook.
///
/// # Errors
///
/// Returns an error when tmux rejects the hook name.
pub async fn unset_hook(&self, name: &str) -> Result<(), Error> {
options::unset_hook(&self.core, options::Scope::GlobalSession, name).await
}
/// Write a whole hook at once.
///
/// [`ReplaceMode::Replace`] clears the hook first, so only what is
/// written remains; [`ReplaceMode::Merge`] leaves entries at indices the
/// write does not name.
///
/// Sent as at most two tmux invocations rather than one per index: the
/// first command alone, then the rest together. That is not atomic: tmux
/// applies a shared invocation in order and stops at the first refusal,
/// so a rejected entry leaves the ones before it written.
///
/// # Errors
///
/// Returns an error when tmux rejects the name or any command.
///
/// # Cancel safety
///
/// Under [`ReplaceMode::Replace`] the clear and the entries are one
/// invocation, so a drop leaves the hook as it was or fully written,
/// never cleared and unwritten; tmux reports one status for that group,
/// so a refusal there cannot name which command drew it. Under
/// [`ReplaceMode::Merge`] the first entry is sent on its own, so a drop
/// after it leaves that entry written and the rest not.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// use std::collections::BTreeMap;
/// use libtmux::{IndexedHooks, ReplaceMode, TmuxText};
///
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// let mut entries = BTreeMap::new();
/// entries.insert(0, TmuxText::from(b"display-message first".to_vec()));
/// entries.insert(3, TmuxText::from(b"display-message fourth".to_vec()));
///
/// server
/// .set_hooks("alert-bell", &IndexedHooks::from(entries), ReplaceMode::Replace)
/// .await?;
///
/// let written = server.hook("alert-bell").await?.expect("the hook is set");
/// assert_eq!(written.len(), 2);
/// assert!(written.get(1).is_none(), "the gap is kept");
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn set_hooks(
&self,
name: &str,
hooks: &IndexedHooks,
replace: ReplaceMode,
) -> Result<(), Error> {
options::set_hooks(
&self.core,
options::Scope::GlobalSession,
name,
hooks,
replace,
)
.await
}
/// Read every hook set at this server.
///
/// Only hooks holding something are reported: tmux lists every hook name
/// it knows, and the ones holding nothing are absent here rather than
/// present and empty.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached or refuses the listing.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// server.set_hook("alert-bell", "display-message rang").await?;
/// let hooks = server.hooks().await?;
/// assert!(hooks.contains_key("alert-bell"));
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn hooks(&self) -> Result<BTreeMap<String, IndexedHooks>, Error> {
options::hooks(&self.core, options::Scope::GlobalSession).await
}
/// Read one hook's commands, or `None` when it holds nothing.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached or refuses the listing.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
///
/// assert!(server.hook("alert-bell").await?.is_none());
/// server.set_hook("alert-bell", "display-message rang").await?;
/// assert!(server.hook("alert-bell").await?.is_some());
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn hook(&self, name: &str) -> Result<Option<IndexedHooks>, Error> {
options::hook(&self.core, options::Scope::GlobalSession, name).await
}
/// Read one server option, decoded according to its declared kind.
///
/// The one way to read a single option; [`OptionValue`] says how reads
/// and writes fit together. `TmuxText::from(value)` recovers the exact
/// bytes tmux stored.
///
/// `None` means the option holds nothing: a built-in option that is unset,
/// or a user option that was never set. tmux prints nothing for an option
/// set to the empty string either, so that also reads as `None`.
///
/// # Errors
///
/// Returns an error when tmux does not recognize the option name.
pub async fn typed_option(&self, name: &str) -> Result<Option<OptionValue>, Error> {
options::get_typed(&self.core, options::Scope::Server, name).await
}
/// Read one global session option, decoded according to its declared kind.
///
/// Sessions inherit from this table. Absence and decoding work as in
/// [`Self::typed_option`].
///
/// # Errors
///
/// Returns an error when tmux does not recognize the option name.
pub async fn typed_global_option(&self, name: &str) -> Result<Option<OptionValue>, Error> {
options::get_typed(&self.core, options::Scope::GlobalSession, name).await
}
/// Read one global window option, decoded according to its declared kind.
///
/// Windows inherit from this table. Absence and decoding work as in
/// [`Self::typed_option`].
///
/// # Errors
///
/// Returns an error when tmux does not recognize the option name.
///
/// # Examples
///
/// ```no_run
/// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
/// use libtmux::OptionValue;
///
/// let base = server.typed_global_window_option("pane-base-index").await?;
/// assert!(matches!(base, Some(OptionValue::Number(_))));
/// # Ok(())
/// # }
/// ```
pub async fn typed_global_window_option(
&self,
name: &str,
) -> Result<Option<OptionValue>, Error> {
options::get_typed(&self.core, options::Scope::GlobalWindow, name).await
}
}