1use std::collections::BTreeMap;
4
5use crate::{Error, ReleaseVersion, Result, TmuxText, TmuxVersion};
6
7pub(crate) const FORMAT_SEPARATOR: &str = "\u{241e}";
8
9#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
11pub enum FormatScope {
12 Universal,
14 Session,
16 Window,
18 Pane,
20 Client,
22 Buffer,
24 Event,
26 Context,
28}
29
30#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
32pub enum DecodedType {
33 Text,
35 Bool,
37 Signed,
39 Unsigned,
41 Timestamp,
43 Id,
45}
46
47#[derive(Clone, Debug, Eq, PartialEq)]
49pub enum FormatValue<'a> {
50 Text(&'a TmuxText),
52 Bool(bool),
54 Signed(i64),
56 Unsigned(u64),
58 Timestamp(u64),
60 Id(&'a str),
62}
63
64#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
66pub struct FormatDescriptor {
67 token: &'static str,
68 scope: FormatScope,
69 decoded: DecodedType,
70 minimum: ReleaseVersion,
71}
72
73impl FormatDescriptor {
74 const fn new(
75 token: &'static str,
76 scope: FormatScope,
77 decoded: DecodedType,
78 minimum: ReleaseVersion,
79 ) -> Self {
80 Self {
81 token,
82 scope,
83 decoded,
84 minimum,
85 }
86 }
87
88 #[must_use]
90 pub const fn token(self) -> &'static str {
91 self.token
92 }
93
94 #[must_use]
96 pub const fn scope(self) -> FormatScope {
97 self.scope
98 }
99
100 #[must_use]
102 pub const fn decoded_type(self) -> DecodedType {
103 self.decoded
104 }
105
106 #[must_use]
108 pub const fn minimum_version(self) -> ReleaseVersion {
109 self.minimum
110 }
111
112 pub fn decode(self, value: &TmuxText) -> Result<Option<FormatValue<'_>>> {
114 if value.is_empty() {
115 return Ok(None);
116 }
117 let parsed = match self.decoded {
118 DecodedType::Text => FormatValue::Text(value),
119 DecodedType::Bool => match value.as_bytes() {
120 b"0" => FormatValue::Bool(false),
121 b"1" => FormatValue::Bool(true),
122 _ => {
123 return Err(Error::Decode {
124 context: "format boolean",
125 message: format!("{} was not 0 or 1", self.token),
126 });
127 }
128 },
129 DecodedType::Signed => FormatValue::Signed(parse_number(value, self.token)?),
130 DecodedType::Unsigned => FormatValue::Unsigned(parse_number(value, self.token)?),
131 DecodedType::Timestamp => FormatValue::Timestamp(parse_number(value, self.token)?),
132 DecodedType::Id => {
133 let value = value.to_str().map_err(|source| Error::Decode {
134 context: "format identity",
135 message: format!("{}: {source}", self.token),
136 })?;
137 FormatValue::Id(value)
138 }
139 };
140 Ok(Some(parsed))
141 }
142}
143
144const BASE: ReleaseVersion = ReleaseVersion::MINIMUM;
145const V33: ReleaseVersion = ReleaseVersion::new(3, 3, None);
146const V37: ReleaseVersion = ReleaseVersion::new(3, 7, None);
147
148macro_rules! descriptors {
149 ($(($token:literal, $scope:ident, $decoded:ident, $version:expr)),+ $(,)?) => {
150 &[
151 $(FormatDescriptor::new(
152 $token,
153 FormatScope::$scope,
154 DecodedType::$decoded,
155 $version,
156 )),+
157 ]
158 };
159}
160
161static FORMAT_CATALOG: &[FormatDescriptor] = descriptors![
162 ("pid", Universal, Unsigned, BASE),
163 ("config_files", Universal, Text, BASE),
164 ("host", Universal, Text, BASE),
165 ("host_short", Universal, Text, BASE),
166 ("line", Universal, Unsigned, BASE),
167 ("next_session_id", Universal, Unsigned, BASE),
168 ("socket_path", Universal, Text, BASE),
169 ("start_time", Universal, Timestamp, BASE),
170 ("uid", Universal, Unsigned, BASE),
171 ("user", Universal, Text, BASE),
172 ("version", Universal, Text, BASE),
173 ("session_id", Session, Id, BASE),
174 ("session_name", Session, Text, BASE),
175 ("session_windows", Session, Unsigned, BASE),
176 ("session_width", Session, Unsigned, BASE),
177 ("session_height", Session, Unsigned, BASE),
178 ("session_created", Session, Timestamp, BASE),
179 ("session_created_string", Session, Text, BASE),
180 ("session_attached", Session, Unsigned, BASE),
181 ("session_activity", Session, Timestamp, BASE),
182 ("session_alerts", Session, Text, BASE),
183 ("session_attached_list", Session, Text, BASE),
184 ("session_format", Session, Text, BASE),
185 ("session_group", Session, Text, BASE),
186 ("session_group_attached", Session, Unsigned, BASE),
187 ("session_group_attached_list", Session, Text, BASE),
188 ("session_group_list", Session, Text, BASE),
189 ("session_group_many_attached", Session, Bool, BASE),
190 ("session_group_size", Session, Unsigned, BASE),
191 ("session_grouped", Session, Bool, BASE),
192 ("session_last_attached", Session, Timestamp, BASE),
193 ("session_many_attached", Session, Bool, BASE),
194 ("session_marked", Session, Bool, BASE),
195 ("session_path", Session, Text, BASE),
196 ("session_stack", Session, Text, BASE),
197 ("active_window_index", Session, Unsigned, BASE),
198 ("last_window_index", Session, Unsigned, BASE),
199 ("window_id", Window, Id, BASE),
200 ("window_index", Window, Unsigned, BASE),
201 ("window_name", Window, Text, BASE),
202 ("window_width", Window, Unsigned, BASE),
203 ("window_height", Window, Unsigned, BASE),
204 ("window_layout", Window, Text, BASE),
205 ("window_visible_layout", Window, Text, BASE),
206 ("window_panes", Window, Unsigned, BASE),
207 ("window_flags", Window, Text, BASE),
208 ("window_active", Window, Bool, BASE),
209 ("window_bell_flag", Window, Bool, BASE),
210 ("window_activity_flag", Window, Bool, BASE),
211 ("window_silence_flag", Window, Bool, BASE),
212 ("window_zoomed_flag", Window, Bool, BASE),
213 ("window_active_clients", Window, Unsigned, BASE),
214 ("window_active_clients_list", Window, Text, BASE),
215 ("window_active_sessions", Window, Unsigned, BASE),
216 ("window_active_sessions_list", Window, Text, BASE),
217 ("window_activity", Window, Timestamp, BASE),
218 ("window_bigger", Window, Bool, BASE),
219 ("window_cell_height", Window, Unsigned, BASE),
220 ("window_cell_width", Window, Unsigned, BASE),
221 ("window_end_flag", Window, Bool, BASE),
222 ("window_format", Window, Text, BASE),
223 ("window_last_flag", Window, Bool, BASE),
224 ("window_linked", Window, Bool, BASE),
225 ("window_linked_sessions", Window, Unsigned, BASE),
226 ("window_linked_sessions_list", Window, Text, BASE),
227 ("window_marked_flag", Window, Bool, BASE),
228 ("window_offset_x", Window, Signed, BASE),
229 ("window_offset_y", Window, Signed, BASE),
230 ("window_raw_flags", Window, Text, BASE),
231 ("window_stack_index", Window, Unsigned, BASE),
232 ("window_start_flag", Window, Bool, BASE),
233 ("pane_id", Pane, Id, BASE),
234 ("pane_index", Pane, Unsigned, BASE),
235 ("pane_width", Pane, Unsigned, BASE),
236 ("pane_height", Pane, Unsigned, BASE),
237 ("pane_title", Pane, Text, BASE),
238 ("pane_active", Pane, Bool, BASE),
239 ("pane_dead", Pane, Bool, BASE),
240 ("pane_dead_status", Pane, Signed, BASE),
241 ("pane_dead_signal", Pane, Signed, V33),
242 ("pane_dead_time", Pane, Timestamp, V33),
243 ("pane_in_mode", Pane, Bool, BASE),
244 ("pane_synchronized", Pane, Bool, BASE),
245 ("pane_tty", Pane, Text, BASE),
246 ("pane_pid", Pane, Unsigned, BASE),
247 ("pane_start_command", Pane, Text, BASE),
248 ("pane_start_path", Pane, Text, BASE),
249 ("pane_current_path", Pane, Text, BASE),
250 ("pane_current_command", Pane, Text, BASE),
251 ("pane_input_off", Pane, Bool, BASE),
252 ("pane_unseen_changes", Pane, Bool, BASE),
253 ("pane_at_left", Pane, Bool, BASE),
254 ("pane_at_right", Pane, Bool, BASE),
255 ("pane_at_top", Pane, Bool, BASE),
256 ("pane_at_bottom", Pane, Bool, BASE),
257 ("history_size", Pane, Unsigned, BASE),
258 ("history_limit", Pane, Unsigned, BASE),
259 ("history_bytes", Pane, Unsigned, BASE),
260 ("alternate_saved_x", Pane, Unsigned, BASE),
261 ("alternate_saved_y", Pane, Unsigned, BASE),
262 ("cursor_x", Pane, Unsigned, BASE),
263 ("cursor_y", Pane, Unsigned, BASE),
264 ("scroll_region_upper", Pane, Unsigned, BASE),
265 ("scroll_region_lower", Pane, Unsigned, BASE),
266 ("alternate_on", Pane, Bool, BASE),
267 ("cursor_flag", Pane, Bool, BASE),
268 ("insert_flag", Pane, Bool, BASE),
269 ("keypad_cursor_flag", Pane, Bool, BASE),
270 ("keypad_flag", Pane, Bool, BASE),
271 ("wrap_flag", Pane, Bool, BASE),
272 ("mouse_standard_flag", Pane, Bool, BASE),
273 ("mouse_button_flag", Pane, Bool, BASE),
274 ("mouse_any_flag", Pane, Bool, BASE),
275 ("mouse_utf8_flag", Pane, Bool, BASE),
276 ("cursor_character", Pane, Text, BASE),
277 ("mouse_all_flag", Pane, Bool, BASE),
278 ("mouse_sgr_flag", Pane, Bool, BASE),
279 ("origin_flag", Pane, Bool, BASE),
280 ("pane_bg", Pane, Text, BASE),
281 ("pane_bottom", Pane, Signed, BASE),
282 ("pane_fg", Pane, Text, BASE),
283 ("pane_format", Pane, Text, BASE),
284 ("pane_last", Pane, Bool, BASE),
285 ("pane_left", Pane, Signed, BASE),
286 ("pane_marked", Pane, Bool, BASE),
287 ("pane_marked_set", Pane, Bool, BASE),
288 ("pane_mode", Pane, Text, BASE),
289 ("pane_path", Pane, Text, BASE),
290 ("pane_pipe", Pane, Bool, BASE),
291 ("pane_right", Pane, Signed, BASE),
292 ("pane_search_string", Pane, Text, BASE),
293 ("pane_tabs", Pane, Text, BASE),
294 ("pane_top", Pane, Signed, BASE),
295 ("pane_flags", Pane, Text, V37),
296 ("pane_floating_flag", Pane, Bool, V37),
297 ("pane_x", Pane, Signed, V37),
298 ("pane_y", Pane, Signed, V37),
299 ("pane_z", Pane, Signed, V37),
300 ("pane_zoomed_flag", Pane, Bool, V37),
301 ("pane_pb_progress", Pane, Unsigned, V37),
302 ("pane_pb_state", Pane, Text, V37),
303 ("pane_pipe_pid", Pane, Unsigned, V37),
304 ("bracket_paste_flag", Pane, Bool, V37),
305 ("synchronized_output_flag", Pane, Bool, V37),
306 ("client_name", Client, Text, BASE),
307 ("client_tty", Client, Text, BASE),
308 ("client_termname", Client, Text, BASE),
309 ("client_session", Client, Text, BASE),
310 ("client_last_session", Client, Text, BASE),
311 ("client_created", Client, Timestamp, BASE),
312 ("client_activity", Client, Timestamp, BASE),
313 ("client_width", Client, Unsigned, BASE),
314 ("client_height", Client, Unsigned, BASE),
315 ("client_pid", Client, Unsigned, BASE),
316 ("client_prefix", Client, Bool, BASE),
317 ("client_utf8", Client, Bool, BASE),
318 ("client_readonly", Client, Bool, BASE),
319 ("client_control_mode", Client, Bool, BASE),
320 ("client_flags", Client, Text, BASE),
321 ("client_cell_height", Client, Unsigned, BASE),
322 ("client_cell_width", Client, Unsigned, BASE),
323 ("client_discarded", Client, Unsigned, BASE),
324 ("client_key_table", Client, Text, BASE),
325 ("client_mode_format", Client, Text, BASE),
326 ("client_termfeatures", Client, Text, BASE),
327 ("client_termtype", Client, Text, BASE),
328 ("client_uid", Client, Unsigned, BASE),
329 ("client_user", Client, Text, BASE),
330 ("client_written", Client, Unsigned, BASE),
331 ("buffer_name", Buffer, Text, BASE),
332 ("buffer_size", Buffer, Unsigned, BASE),
333 ("buffer_sample", Buffer, Text, BASE),
334 ("copy_cursor_line", Event, Unsigned, BASE),
335 ("copy_cursor_word", Event, Text, BASE),
336 ("copy_cursor_x", Event, Unsigned, BASE),
337 ("copy_cursor_y", Event, Unsigned, BASE),
338 ("scroll_position", Event, Signed, BASE),
339 ("selection_end_x", Event, Signed, BASE),
340 ("selection_end_y", Event, Signed, BASE),
341 ("selection_start_x", Event, Signed, BASE),
342 ("selection_start_y", Event, Signed, BASE),
343 ("command_list_alias", Context, Text, BASE),
344 ("command_list_name", Context, Text, BASE),
345 ("command_list_usage", Context, Text, BASE),
346 ("current_file", Context, Text, BASE),
347 ("search_match", Context, Text, BASE),
348];
349
350#[must_use]
352pub const fn format_catalog() -> &'static [FormatDescriptor] {
353 FORMAT_CATALOG
354}
355
356#[must_use]
358pub fn format_descriptor(token: &str) -> Option<&'static FormatDescriptor> {
359 FORMAT_CATALOG
360 .iter()
361 .find(|descriptor| descriptor.token == token)
362}
363
364#[derive(Clone, Debug, Eq, Hash, PartialEq)]
366pub enum FormatToken {
367 Known(&'static FormatDescriptor),
369 Custom(String),
371}
372
373impl FormatToken {
374 pub fn custom(value: impl Into<String>) -> Result<Self> {
376 let value = value.into();
377 if value.is_empty()
378 || value.contains(['{', '}', FORMAT_SEPARATOR.chars().next().unwrap_or('\0')])
379 {
380 return Err(Error::InvalidArgument {
381 argument: "format token",
382 message: "must be non-empty and contain no braces or field separator".to_owned(),
383 });
384 }
385 Ok(Self::Custom(value))
386 }
387
388 #[must_use]
390 pub fn as_str(&self) -> &str {
391 match self {
392 Self::Known(descriptor) => descriptor.token(),
393 Self::Custom(value) => value,
394 }
395 }
396}
397
398#[derive(Clone, Debug, Eq, Hash, PartialEq)]
400pub struct NativeFilter(String);
401
402impl NativeFilter {
403 pub fn new(value: impl Into<String>) -> Result<Self> {
405 let value = value.into();
406 if value.is_empty() {
407 return Err(Error::InvalidArgument {
408 argument: "native filter",
409 message: "must not be empty".to_owned(),
410 });
411 }
412 Ok(Self(value))
413 }
414
415 #[must_use]
417 pub fn as_str(&self) -> &str {
418 &self.0
419 }
420}
421
422pub(crate) fn fields_for_listing(
423 scopes: &[FormatScope],
424 version: &TmuxVersion,
425) -> Vec<&'static FormatDescriptor> {
426 FORMAT_CATALOG
427 .iter()
428 .filter(|field| scopes.contains(&field.scope) && version.meets(field.minimum))
429 .collect()
430}
431
432pub(crate) fn render_format(fields: &[&FormatDescriptor]) -> String {
433 fields
434 .iter()
435 .map(|field| format!("#{{{}}}", field.token))
436 .collect::<Vec<_>>()
437 .join(FORMAT_SEPARATOR)
438}
439
440pub(crate) fn parse_rows(
441 bytes: &[u8],
442 fields: &[&FormatDescriptor],
443) -> Result<Vec<BTreeMap<&'static str, TmuxText>>> {
444 if bytes.is_empty() {
445 return Ok(Vec::new());
446 }
447 let separator = FORMAT_SEPARATOR.as_bytes();
448 bytes
449 .split(|byte| *byte == b'\n')
450 .filter(|line| !line.is_empty())
451 .map(|line| {
452 let values = split_fields(line, separator);
453 if values.len() != fields.len() {
454 return Err(Error::Decode {
455 context: "tmux format row",
456 message: format!(
457 "expected {} fields, received {}",
458 fields.len(),
459 values.len()
460 ),
461 });
462 }
463 Ok(fields
464 .iter()
465 .zip(values)
466 .map(|(field, value)| (field.token, TmuxText::new(value.to_vec())))
467 .collect())
468 })
469 .collect()
470}
471
472fn split_fields<'a>(line: &'a [u8], separator: &[u8]) -> Vec<&'a [u8]> {
473 let mut fields = Vec::new();
474 let mut start = 0;
475 while let Some(offset) = line[start..]
476 .windows(separator.len())
477 .position(|window| window == separator)
478 {
479 let end = start + offset;
480 fields.push(&line[start..end]);
481 start = end + separator.len();
482 }
483 fields.push(&line[start..]);
484 fields
485}
486
487fn parse_number<T>(value: &TmuxText, token: &'static str) -> Result<T>
488where
489 T: std::str::FromStr,
490 T::Err: std::fmt::Display,
491{
492 let value = value.to_str().map_err(|source| Error::Decode {
493 context: "numeric format",
494 message: format!("{token}: {source}"),
495 })?;
496 value.parse().map_err(|source| Error::Decode {
497 context: "numeric format",
498 message: format!("{token}: {source}"),
499 })
500}
501
502#[cfg(test)]
503mod tests {
504 use super::{
505 FORMAT_SEPARATOR, FormatScope, fields_for_listing, format_descriptor, parse_rows,
506 render_format,
507 };
508 use crate::{TmuxText, TmuxVersion};
509
510 #[test]
511 fn version_gates_new_fields() {
512 let Ok(version) = TmuxVersion::parse("3.6") else {
513 return;
514 };
515 let fields = fields_for_listing(&[FormatScope::Pane], &version);
516 assert!(!fields.iter().any(|field| field.token() == "pane_flags"));
517 }
518
519 #[test]
520 fn format_rows_round_trip() {
521 let Ok(version) = TmuxVersion::parse("3.2a") else {
522 return;
523 };
524 let fields = fields_for_listing(&[FormatScope::Session], &version);
525 let fields = &fields[..2];
526 assert!(render_format(fields).contains("#{session_id}"));
527 let output = format!("$1{FORMAT_SEPARATOR}name\n");
528 let Ok(rows) = parse_rows(output.as_bytes(), fields) else {
529 return;
530 };
531 assert_eq!(rows.len(), 1);
532 }
533
534 #[test]
535 fn malformed_rows_and_values_are_rejected() {
536 let Ok(version) = TmuxVersion::parse("3.2a") else {
537 return;
538 };
539 let fields = fields_for_listing(&[FormatScope::Session], &version);
540 assert!(parse_rows(b"only-one-field\n", &fields[..2]).is_err());
541
542 let Some(boolean) = format_descriptor("pane_active") else {
543 return;
544 };
545 assert!(boolean.decode(&TmuxText::from("not-a-boolean")).is_err());
546 }
547}