rmux-core 0.6.1

Core session, pane, layout, format, hook, and buffer model for the RMUX terminal multiplexer.
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
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! tmux-compatible command tokenization and command-name lookup.
//!
//! This module mirrors the frozen tmux `cmd-parse.y` lexer boundary closely
//! enough for RMUX command dispatch and config parsing to share one parser.
//! Frozen source anchors: `/opt/rmux/reference/tmux` at commit
//! `31d77e29b6c9fbb07d032018da78db3a8a38d979`, especially `cmd.c:121`
//! (`cmd_table[]`) and `cmd-parse.y:1053`, `cmd-parse.y:1201`,
//! `cmd-parse.y:1626` for argv parsing, continuation handling, and
//! tokenization.

use std::error::Error;
use std::fmt;

use crate::{
    formats::{is_truthy, render_template, FormatVariable, FormatVariables},
    EnvironmentStore,
};

#[path = "command_parser/aliases.rs"]
mod aliases;
#[path = "command_parser/grammar.rs"]
mod grammar;
#[path = "command_parser/lexer.rs"]
mod lexer;
#[path = "command_parser/lookup.rs"]
mod lookup;
#[path = "command_parser/table.rs"]
mod table;

use aliases::CommandAlias;
use grammar::GrammarParser;
use lexer::Lexer;
use lookup::lookup_command_at;
pub use table::{CommandEntry, COMMAND_TABLE};

const DEFAULT_MAX_COMMAND_BYTES: usize = 16 * 1024;
/// Maximum size of a single command parsed from `source-file` input.
pub const SOURCE_FILE_MAX_COMMAND_BYTES: usize = 1024 * 1024;

/// Parses a tmux command string with default expansion context.
pub fn parse_command_string(input: &str) -> Result<ParsedCommands, CommandParseError> {
    CommandParser::new().parse(input)
}

/// Parses a tmux command argument vector with default expansion context.
pub fn parse_command_arguments<I, S>(arguments: I) -> Result<ParsedCommands, CommandParseError>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    CommandParser::new().parse_arguments(arguments)
}

/// Looks up a frozen tmux command using exact alias then unique name prefix.
pub fn lookup_command(name: &str) -> Result<&'static CommandEntry, CommandParseError> {
    lookup_command_at(name, 0)
}

/// Parser output for one command list.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ParsedCommands {
    commands: Vec<ParsedCommand>,
    assignments: Vec<EnvironmentAssignment>,
    grouping: CommandGrouping,
}

impl ParsedCommands {
    fn with_grouping(grouping: CommandGrouping) -> Self {
        Self {
            commands: Vec::new(),
            assignments: Vec::new(),
            grouping,
        }
    }

    /// Returns the parsed command sequence.
    #[must_use]
    pub fn commands(&self) -> &[ParsedCommand] {
        &self.commands
    }

    /// Returns parse-time environment assignments.
    #[must_use]
    pub fn assignments(&self) -> &[EnvironmentAssignment] {
        &self.assignments
    }

    /// Returns how queue group IDs should be assigned for this parsed list.
    #[must_use]
    pub const fn grouping(&self) -> CommandGrouping {
        self.grouping
    }

    /// Consumes the list and returns only the command sequence.
    #[must_use]
    pub fn into_commands(self) -> Vec<ParsedCommand> {
        self.commands
    }

    /// Returns whether the parser found no executable commands.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    fn push_assignment(&mut self, assignment: EnvironmentAssignment) {
        self.assignments.push(assignment);
    }

    fn push_command(&mut self, command: ParsedCommand) {
        self.commands.push(command);
    }

    /// Appends another parsed command list, preserving the grouping mode of
    /// this list.
    pub fn append(&mut self, mut other: Self) {
        self.assignments.append(&mut other.assignments);
        self.commands.append(&mut other.commands);
    }

    /// Adds an offset to every source line recorded in this command list.
    ///
    /// Recovery parsers use this after parsing a suffix of a larger source
    /// file so diagnostics and verbose output still reference original lines.
    pub fn add_line_offset(&mut self, offset: usize) {
        if offset == 0 {
            return;
        }
        for command in &mut self.commands {
            command.add_line_offset(offset);
        }
    }

    /// Converts the parsed commands back to a tmux-style command string.
    #[must_use]
    pub fn to_tmux_string(&self) -> String {
        self.commands
            .iter()
            .map(ParsedCommand::to_tmux_string)
            .collect::<Vec<_>>()
            .join(" ; ")
    }

    /// Converts the parsed commands to a command string suitable for
    /// embedding in a `bind-key` line.
    #[must_use]
    pub fn to_tmux_binding_string(&self) -> String {
        self.commands
            .iter()
            .map(ParsedCommand::to_tmux_string)
            .collect::<Vec<_>>()
            .join(" \\; ")
    }
}

/// Queue grouping mode captured while parsing a tmux command list.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CommandGrouping {
    /// Commands that start on the same source line share one queue group.
    #[default]
    ByLine,
    /// All commands in the parsed list share one queue group.
    OneGroup,
}

/// One parsed tmux command with a canonical command name.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedCommand {
    name: String,
    arguments: Vec<CommandArgument>,
    line: usize,
}

impl ParsedCommand {
    /// Returns the canonical command name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the parsed command arguments.
    #[must_use]
    pub fn arguments(&self) -> &[CommandArgument] {
        &self.arguments
    }

    /// Returns the one-based input line where this command started.
    #[must_use]
    pub fn line(&self) -> usize {
        self.line
    }

    fn new(name: String, arguments: Vec<CommandArgument>, line: usize) -> Self {
        Self {
            name,
            arguments,
            line,
        }
    }

    fn add_line_offset(&mut self, offset: usize) {
        self.line = self.line.saturating_add(offset);
        for argument in &mut self.arguments {
            if let CommandArgument::Commands(commands) = argument {
                commands.add_line_offset(offset);
            }
        }
    }

    /// Converts this command back to a tmux-style command string.
    #[must_use]
    pub fn to_tmux_string(&self) -> String {
        std::iter::once(self.name.clone())
            .chain(self.arguments.iter().map(CommandArgument::to_tmux_string))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

/// A parsed command argument.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommandArgument {
    /// A scalar string argument after tmux quote and expansion handling.
    String(String),
    /// A brace-delimited nested command list.
    Commands(ParsedCommands),
}

impl CommandArgument {
    /// Returns the string value when this is a scalar argument.
    #[must_use]
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::String(value) => Some(value),
            Self::Commands(_) => None,
        }
    }

    /// Converts the argument to a string suitable for the legacy CLI bridge.
    #[must_use]
    pub fn to_tmux_string(&self) -> String {
        match self {
            Self::String(value) => escape_argument(value),
            Self::Commands(commands) => format!("{{ {} }}", commands.to_tmux_string()),
        }
    }
}

/// A parse-time `name=value` environment assignment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvironmentAssignment {
    name: String,
    value: String,
    hidden: bool,
}

impl EnvironmentAssignment {
    /// Returns the assignment variable name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the assignment value.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Returns whether `%hidden` preceded this assignment.
    #[must_use]
    pub fn hidden(&self) -> bool {
        self.hidden
    }

    fn from_equals(value: String, hidden: bool) -> Self {
        let (name, value) = value
            .split_once('=')
            .expect("lexer only classifies assignments containing '='");
        Self {
            name: name.to_owned(),
            value: value.to_owned(),
            hidden,
        }
    }
}

/// A reusable parser with parse-time expansion context.
#[derive(Debug, Clone)]
pub struct CommandParser {
    environment: Vec<(String, String)>,
    format_variables: Vec<(String, String)>,
    home_dir: Option<String>,
    user_home_dirs: Vec<(String, String)>,
    command_aliases: Vec<CommandAlias>,
    max_command_bytes: usize,
}

impl Default for CommandParser {
    fn default() -> Self {
        Self {
            environment: Vec::new(),
            format_variables: Vec::new(),
            home_dir: None,
            user_home_dirs: Vec::new(),
            command_aliases: Vec::new(),
            max_command_bytes: DEFAULT_MAX_COMMAND_BYTES,
        }
    }
}

impl CommandParser {
    /// Creates a parser with no environment, tilde, or user alias overrides.
    #[must_use]
    pub fn new() -> Self {
        let mut parser = Self::default();
        parser.command_aliases.extend(CommandAlias::builtin());
        parser
    }

    /// Adds one variable to the parse-time environment expansion context.
    #[must_use]
    pub fn with_environment_value(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> Self {
        self.environment.push((name.into(), value.into()));
        self
    }

    /// Adds one parse-time format variable used by `%if` condition expansion.
    #[must_use]
    pub fn with_format_value(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.format_variables.push((name.into(), value.into()));
        self
    }

    /// Copies global values from an RMUX environment store into the parser.
    #[must_use]
    pub fn with_environment_store(mut self, environment: &EnvironmentStore) -> Self {
        self.environment.extend(
            environment
                .global_entries()
                .map(|(name, value)| (name.to_owned(), value.to_owned())),
        );
        self
    }

    /// Adds the fallback home directory used for `~` expansion.
    #[must_use]
    pub fn with_home_dir(mut self, home_dir: impl Into<String>) -> Self {
        self.home_dir = Some(home_dir.into());
        self
    }

    /// Adds a deterministic `~user` expansion mapping.
    #[must_use]
    pub fn with_user_home_dir(
        mut self,
        user: impl Into<String>,
        home_dir: impl Into<String>,
    ) -> Self {
        self.user_home_dirs.push((user.into(), home_dir.into()));
        self
    }

    /// Adds one `command-alias` option entry of the form `name=value`.
    pub fn with_command_alias(
        mut self,
        definition: impl Into<String>,
    ) -> Result<Self, CommandParseError> {
        let definition = definition.into();
        let Some(alias) = CommandAlias::parse(definition) else {
            return Err(CommandParseError::new(
                0,
                "command-alias entry must be name=value",
            ));
        };
        self.command_aliases.push(alias);
        Ok(self)
    }

    /// Replaces the parser alias table with valid `command-alias` entries.
    #[must_use]
    pub fn with_command_aliases<I, S>(mut self, definitions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.command_aliases.clear();
        self.command_aliases
            .extend(definitions.into_iter().filter_map(CommandAlias::parse));
        self
    }

    /// Overrides the maximum parsed command size.
    #[must_use]
    pub fn with_max_command_bytes(mut self, max_command_bytes: usize) -> Self {
        self.max_command_bytes = max_command_bytes;
        self
    }

    /// Parses a tmux command string through the tmux-style lexer.
    pub fn parse(&self, input: &str) -> Result<ParsedCommands, CommandParseError> {
        self.parse_inner(input, false, CommandGrouping::ByLine)
    }

    /// Parses a tmux command string with `CMD_PARSE_ONEGROUP` semantics.
    ///
    /// tmux uses this mode when a command string is parsed from an argument or
    /// option value, so embedded newlines do not create independent abort
    /// groups.
    pub fn parse_one_group(&self, input: &str) -> Result<ParsedCommands, CommandParseError> {
        self.parse_inner(input, false, CommandGrouping::OneGroup)
    }

    /// Parses an argv-style tmux command vector.
    ///
    /// tmux treats these arguments as already split and only divides commands
    /// on unescaped trailing semicolons.
    pub fn parse_arguments<I, S>(&self, arguments: I) -> Result<ParsedCommands, CommandParseError>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let arguments = arguments
            .into_iter()
            .map(|argument| argument.as_ref().to_owned())
            .collect::<Vec<_>>();
        let command_bytes = arguments
            .iter()
            .map(String::len)
            .sum::<usize>()
            .saturating_add(arguments.len().saturating_sub(1));
        ensure_command_length(command_bytes, 0, self.max_command_bytes)?;

        let mut commands = ParsedCommands::with_grouping(CommandGrouping::ByLine);
        let mut current = Vec::new();

        for argument in arguments {
            let mut value = argument;
            let mut ends_command = false;

            if value.ends_with(';') {
                value.pop();
                if value.ends_with('\\') {
                    value.pop();
                    value.push(';');
                } else {
                    ends_command = true;
                }
            }

            if !ends_command || !value.is_empty() {
                current.push(CommandArgument::String(value));
            }
            if ends_command && !current.is_empty() {
                commands.push_command(command_from_arguments(std::mem::take(&mut current), 1)?);
            }
        }

        if !current.is_empty() {
            commands.push_command(command_from_arguments(current, 1)?);
        }

        self.expand_and_lookup(commands, false)
    }

    fn parse_inner(
        &self,
        input: &str,
        no_alias: bool,
        grouping: CommandGrouping,
    ) -> Result<ParsedCommands, CommandParseError> {
        let mut parser = GrammarParser::new(Lexer::new(input, self), grouping);
        let commands = parser.parse_all()?;
        ensure_parsed_command_lengths(&commands, self.max_command_bytes)?;
        self.expand_and_lookup(commands, no_alias)
    }

    fn expand_and_lookup(
        &self,
        commands: ParsedCommands,
        no_alias: bool,
    ) -> Result<ParsedCommands, CommandParseError> {
        let assignments = commands.assignments.clone();
        let mut output = ParsedCommands {
            commands: Vec::new(),
            assignments: commands.assignments,
            grouping: commands.grouping,
        };

        for mut command in commands.commands {
            if !no_alias {
                if let Some(alias) = self.find_command_alias(&command.name) {
                    let mut alias_parser = self.clone();
                    alias_parser.environment.extend(
                        assignments
                            .iter()
                            .map(|assignment| (assignment.name.clone(), assignment.value.clone())),
                    );
                    let mut replacement =
                        alias_parser.parse_inner(alias, true, CommandGrouping::OneGroup)?;
                    for replacement_command in &mut replacement.commands {
                        replacement_command.line = command.line;
                    }
                    if let Some(last) = replacement.commands.last_mut() {
                        last.arguments.append(&mut command.arguments);
                    }
                    output.append(replacement);
                    continue;
                }
            }

            for argument in &mut command.arguments {
                if let CommandArgument::Commands(nested) = argument {
                    let nested_commands = std::mem::take(nested);
                    *nested = self.expand_and_lookup(nested_commands, no_alias)?;
                }
            }

            let entry = lookup_command_at(&command.name, command.line)?;
            command.name = entry.name.to_owned();
            output.push_command(command);
        }

        Ok(output)
    }

    fn find_command_alias(&self, name: &str) -> Option<&str> {
        self.command_aliases
            .iter()
            .rev()
            .find(|alias| alias.name() == name)
            .map(CommandAlias::value)
    }

    fn lookup_environment(&self, name: &str) -> Option<&str> {
        self.environment
            .iter()
            .rev()
            .find(|(candidate, _)| candidate == name)
            .map(|(_, value)| value.as_str())
    }

    fn expand_tilde(&self, user: &str) -> Option<&str> {
        if user.is_empty() {
            return self
                .lookup_environment("HOME")
                .filter(|home| !home.is_empty())
                .or(self.home_dir.as_deref());
        }

        self.user_home_dirs
            .iter()
            .find(|(candidate, _)| candidate == user)
            .map(|(_, home)| home.as_str())
    }

    fn condition_is_true(&self, value: &str) -> bool {
        let expanded = if value.contains("#{") {
            render_template(
                value,
                &ParseTimeFormatVariables {
                    values: &self.format_variables,
                },
            )
        } else {
            value.to_owned()
        };

        is_truthy(&expanded)
    }
}

fn ensure_command_length(
    bytes: usize,
    line: usize,
    max_command_bytes: usize,
) -> Result<(), CommandParseError> {
    if bytes > max_command_bytes {
        return Err(CommandParseError::new(line, "command too long"));
    }
    Ok(())
}

fn ensure_parsed_command_lengths(
    commands: &ParsedCommands,
    max_command_bytes: usize,
) -> Result<(), CommandParseError> {
    for command in commands.commands() {
        ensure_parsed_command_length(command, max_command_bytes)?;
    }
    Ok(())
}

fn ensure_parsed_command_length(
    command: &ParsedCommand,
    max_command_bytes: usize,
) -> Result<(), CommandParseError> {
    let mut bytes = command.name.len();
    for argument in command.arguments() {
        bytes = bytes.saturating_add(1);
        match argument {
            CommandArgument::String(value) => {
                bytes = bytes.saturating_add(value.len());
            }
            CommandArgument::Commands(commands) => {
                ensure_parsed_command_lengths(commands, max_command_bytes)?;
            }
        }
    }
    ensure_command_length(bytes, command.line(), max_command_bytes)
}

struct ParseTimeFormatVariables<'a> {
    values: &'a [(String, String)],
}

impl FormatVariables for ParseTimeFormatVariables<'_> {
    fn format_value(&self, _variable: FormatVariable) -> Option<String> {
        None
    }

    fn format_value_by_name(&self, name: &str) -> Option<String> {
        self.values
            .iter()
            .rev()
            .find(|(candidate, _)| candidate == name)
            .map(|(_, value)| value.clone())
    }
}

/// Error returned by command tokenization, parsing, or lookup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandParseError {
    line: usize,
    message: String,
}

impl CommandParseError {
    /// Returns the one-based input line for the error, or zero when unknown.
    #[must_use]
    pub fn line(&self) -> usize {
        self.line
    }

    /// Returns the tmux-style error message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    pub(crate) fn new(line: usize, message: impl Into<String>) -> Self {
        Self {
            line,
            message: message.into(),
        }
    }
}

impl fmt::Display for CommandParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for CommandParseError {}

fn command_from_arguments(
    mut arguments: Vec<CommandArgument>,
    line: usize,
) -> Result<ParsedCommand, CommandParseError> {
    let Some(CommandArgument::String(name)) = arguments.first() else {
        return Err(CommandParseError::new(line, "no command"));
    };
    let name = name.clone();
    arguments.remove(0);
    Ok(ParsedCommand::new(name, arguments, line))
}

fn escape_argument(value: &str) -> String {
    if value.is_empty() {
        return "''".to_owned();
    }
    if !value.chars().any(argument_needs_quotes) {
        return value.replace('\\', r"\\");
    }

    if value.contains('"') && !value.contains('\'') && !value.contains('$') {
        return format!("'{value}'");
    }

    format!("\"{}\"", escape_double_quoted_argument(value))
}

fn argument_needs_quotes(ch: char) -> bool {
    ch.is_whitespace() || matches!(ch, ';' | '{' | '}' | '\'' | '"' | '#' | '$')
}

fn escape_double_quoted_argument(value: &str) -> String {
    let mut escaped = String::with_capacity(value.len());
    for ch in value.chars() {
        match ch {
            '$' => escaped.push_str(r"\$"),
            '\\' | '"' => {
                escaped.push('\\');
                escaped.push(ch);
            }
            _ => escaped.push(ch),
        }
    }
    escaped
}

#[cfg(test)]
#[path = "command_parser/tests.rs"]
mod tests;