rmux-core 0.10.0

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
//! Command dispatch for terminal input sequences.

pub use super::commands::{CsiCommand, DcsPayload, EscCommand, InputAction, OscCommand};
pub use super::writer::ScreenWriter;

use super::csi_helpers::{
    dispatch_rm, dispatch_rm_private, dispatch_sm, dispatch_sm_private, dispatch_winops,
};
use super::mode;
use super::sgr;
use super::tables;
use super::{InputEndType, InputParser, OscColourSlot, INPUT_LAST};

const XTVERSION_REPLY: &str = concat!("\x1bP>|rmux ", env!("CARGO_PKG_VERSION"), "\x1b\\");

// ─── C0 dispatch ───────────────────────────────────────────────────

pub(crate) fn dispatch_c0<W: ScreenWriter + ?Sized>(parser: &mut InputParser, writer: &mut W) {
    match parser.ch {
        0x00 => {} // NUL
        0x07 => {
            // BEL
            writer.bell();
        }
        0x08 => {
            // BS
            writer.backspace();
        }
        0x09 => {
            // HT
            writer.tab();
        }
        0x0a..=0x0c => {
            // LF/VT/FF
            let bg = parser.cell.cell.bg;
            writer.linefeed(false, bg);
            if writer.current_mode() & mode::MODE_CRLF != 0 {
                writer.carriage_return();
            }
        }
        0x0d => {
            // CR
            writer.carriage_return();
        }
        0x0e => {
            // SO — shift out (activate G1)
            parser.cell.set = 1;
        }
        0x0f => {
            // SI — shift in (activate G0)
            parser.cell.set = 0;
        }
        _ => {}
    }
}

// ─── ESC dispatch ──────────────────────────────────────────────────

pub(crate) fn dispatch_esc<W: ScreenWriter + ?Sized>(parser: &mut InputParser, writer: &mut W) {
    let cmd = match tables::lookup_esc(parser.ch, parser.interm_str()) {
        Some(cmd) => cmd,
        None => return,
    };

    match cmd {
        EscCommand::Ris => {
            parser.cell.reset();
            writer.full_reset();
        }
        EscCommand::Ind => {
            let bg = parser.cell.cell.bg;
            writer.linefeed(false, bg);
        }
        EscCommand::Nel => {
            let bg = parser.cell.cell.bg;
            writer.carriage_return();
            writer.linefeed(false, bg);
        }
        EscCommand::Hts => {
            writer.set_tab_stop();
        }
        EscCommand::Ri => {
            let bg = parser.cell.cell.bg;
            writer.reverse_index(bg);
        }
        EscCommand::Deckpam => {
            writer.mode_set(mode::MODE_KKEYPAD);
        }
        EscCommand::Deckpnm => {
            writer.mode_clear(mode::MODE_KKEYPAD);
        }
        EscCommand::Decsc => {
            // Save cell state, cursor position, and origin mode.
            parser.saved.cell = parser.cell.clone();
            parser.saved.cx = writer.cursor_x();
            parser.saved.cy = writer.cursor_y();
            parser.saved.mode_origin = (writer.current_mode() & mode::MODE_ORIGIN) != 0;
        }
        EscCommand::Decrc => {
            // Restore cell state, cursor position, and origin mode.
            parser.cell = parser.saved.cell.clone();
            if parser.saved.mode_origin {
                writer.mode_set(mode::MODE_ORIGIN);
            } else {
                writer.mode_clear(mode::MODE_ORIGIN);
            }
            writer.cursor_move(parser.saved.cx as i32, parser.saved.cy as i32, false);
        }
        EscCommand::Decaln => {
            writer.alignment_test();
        }
        EscCommand::Scsg0On => {
            parser.cell.g0set = 1;
        }
        EscCommand::Scsg0Off => {
            parser.cell.g0set = 0;
        }
        EscCommand::Scsg1On => {
            parser.cell.g1set = 1;
        }
        EscCommand::Scsg1Off => {
            parser.cell.g1set = 0;
        }
        EscCommand::St => {
            // ST just terminates — state transition already handled it.
        }
    }
}

// ─── CSI dispatch ──────────────────────────────────────────────────

pub(crate) fn dispatch_csi<W: ScreenWriter + ?Sized>(parser: &mut InputParser, writer: &mut W) {
    if !parser.param_list.split(&parser.param_buf, parser.param_len) {
        return;
    }

    let cmd = match tables::lookup_csi(parser.ch, parser.interm_str()) {
        Some(cmd) => cmd,
        None => return,
    };

    let bg = parser.cell.cell.bg;

    match cmd {
        CsiCommand::Ich => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.insert_character(n as u32, bg);
            }
        }
        CsiCommand::Cuu => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_up(n as u32);
            }
        }
        CsiCommand::Cud => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_down(n as u32);
            }
        }
        CsiCommand::Cuf => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_right(n as u32);
            }
        }
        CsiCommand::Cub => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_left(n as u32);
            }
        }
        CsiCommand::Cnl => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.carriage_return();
                writer.cursor_down(n as u32);
            }
        }
        CsiCommand::Cpl => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.carriage_return();
                writer.cursor_up(n as u32);
            }
        }
        CsiCommand::Cup => {
            let n = parser.param_list.get(0, 1, 1);
            let m = parser.param_list.get(1, 1, 1);
            if n != -1 && m != -1 {
                writer.cursor_move(m - 1, n - 1, true);
            }
        }
        CsiCommand::Hpa => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_move(n - 1, -1, true);
            }
        }
        CsiCommand::Vpa => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_move(-1, n - 1, true);
            }
        }
        CsiCommand::Ed => match parser.param_list.get(0, 0, 0) {
            -1 => {}
            0 => writer.clear_end_of_screen(bg),
            1 => writer.clear_start_of_screen(bg),
            2 => writer.clear_screen(bg),
            3 if parser.param_list.get(1, 0, 0) == 0 => {
                writer.clear_history();
            }
            _ => {}
        },
        CsiCommand::El => match parser.param_list.get(0, 0, 0) {
            -1 => {}
            0 => writer.clear_end_of_line(bg),
            1 => writer.clear_start_of_line(bg),
            2 => writer.clear_line(bg),
            _ => {}
        },
        CsiCommand::Il => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.insert_line(n as u32, bg);
            }
        }
        CsiCommand::Dl => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.delete_line(n as u32, bg);
            }
        }
        CsiCommand::Dch => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.delete_character(n as u32, bg);
            }
        }
        CsiCommand::Ech => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.clear_character(n as u32, bg);
            }
        }
        CsiCommand::Su => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.scroll_up(n as u32, bg);
            }
        }
        CsiCommand::Sd => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.scroll_down(n as u32, bg);
            }
        }
        CsiCommand::Cbt => {
            let n = parser.param_list.get(0, 1, 1);
            if n != -1 {
                writer.cursor_backward_tab(n as u32);
            }
        }
        CsiCommand::Rep => {
            let n = parser.param_list.get(0, 1, 1);
            if n == -1 || parser.flags & INPUT_LAST == 0 {
                return; // No prior character to repeat, or invalid param.
            }
            if let Some(ch) = parser.last_char {
                // INPUT_LAST is parser-only state: no ANSI keyframe can seed
                // it in another emulator. A character printed earlier in this
                // same feed is replayable from the same raw event; a REP that
                // reaches across feed boundaries requires an authoritative
                // post-dispatch recovery rebase.
                parser.note_effective_rep();
                let set = if parser.cell.set == 0 {
                    parser.cell.g0set
                } else {
                    parser.cell.g1set
                };
                let remaining = writer.screen_size_x().saturating_sub(writer.cursor_x());
                let count = (n as u32).min(remaining);
                for _ in 0..count {
                    writer.collect_add_with_charset(ch, &parser.cell, set != 0);
                }
            }
        }
        CsiCommand::Da => {
            match parser.param_list.get(0, 0, 0) {
                0 => {
                    // DA primary: VT100 with AVO.
                    parser.reply("\x1b[?1;2c");
                }
                -1 => {}
                _ => {}
            }
        }
        CsiCommand::DaTwo => {
            match parser.param_list.get(0, 0, 0) {
                0 => {
                    // DA secondary: tmux terminal type 84.
                    parser.reply("\x1b[>84;0;0c");
                }
                -1 => {}
                _ => {}
            }
        }
        CsiCommand::Dsr => {
            match parser.param_list.get(0, 0, 0) {
                -1 => {}
                5 => {
                    // Status report: OK.
                    parser.reply("\x1b[0n");
                }
                6 => {
                    // Cursor position report.
                    let cy = writer.cursor_y() + 1;
                    let cx = writer.cursor_x() + 1;
                    let reply = format!("\x1b[{cy};{cx}R");
                    parser.reply(&reply);
                }
                _ => {}
            }
        }
        CsiCommand::DsrPrivate => {
            // Private DSR: theme query etc. — server-level concerns.
            // For now, no-op.
        }
        CsiCommand::QueryPrivate => {
            // DECRPM query — server-level concern, requires option access.
            // Surface the query for the server to handle.
            let param = parser.param_list.get(0, 0, 0);
            let mode_val = writer.current_mode();
            let reply = match param {
                1004 => {
                    let n = if mode_val & mode::MODE_FOCUSON != 0 {
                        1
                    } else {
                        2
                    };
                    format!("\x1b[?1004;{n}$y")
                }
                1006 => {
                    let n = if mode_val & mode::MODE_MOUSE_SGR != 0 {
                        1
                    } else {
                        2
                    };
                    format!("\x1b[?1006;{n}$y")
                }
                2004 => {
                    let n = if mode_val & mode::MODE_BRACKETPASTE != 0 {
                        1
                    } else {
                        2
                    };
                    format!("\x1b[?2004;{n}$y")
                }
                2026 => {
                    let n = if mode_val & mode::MODE_SYNC != 0 {
                        1
                    } else {
                        2
                    };
                    format!("\x1b[?2026;{n}$y")
                }
                2031 => "\x1b[?2031;2$y".to_owned(),
                _ => return,
            };
            parser.reply(&reply);
        }
        CsiCommand::Decstbm => {
            let n = parser.param_list.get(0, 1, 1);
            let sy = writer.screen_size_y();
            let m = parser.param_list.get(1, 1, sy as i32);
            if n != -1 && m != -1 {
                writer.set_scroll_region((n - 1) as u32, (m - 1) as u32);
            }
        }
        CsiCommand::Tbc => match parser.param_list.get(0, 0, 0) {
            -1 => {}
            0 => writer.clear_tab_stop(),
            3 => writer.clear_all_tab_stops(),
            _ => {}
        },
        CsiCommand::Sm => dispatch_sm(parser, writer),
        CsiCommand::SmPrivate => dispatch_sm_private(parser, writer),
        CsiCommand::Rm => dispatch_rm(parser, writer),
        CsiCommand::RmPrivate => dispatch_rm_private(parser, writer),
        CsiCommand::Sgr => sgr::dispatch_sgr(parser),
        CsiCommand::SmGraphics => {
            // Graphics mode query — typically needs sixel support.
            // Deferred to Milestone 30.
        }
        CsiCommand::Modset => {
            let n = parser.param_list.get(0, 0, 0);
            if n != 4 {
                return;
            }
            let m = parser.param_list.get(1, 0, 0);
            writer.mode_clear(mode::EXTENDED_KEY_MODES);
            match m {
                2 => writer.mode_set(mode::MODE_KEYS_EXTENDED_2),
                1 => writer.mode_set(mode::MODE_KEYS_EXTENDED),
                _ => {}
            }
        }
        // RMUX 0.9 does not implement the complete Kitty keyboard protocol.
        // Consume every negotiation form without replying or changing the
        // pane's key mode: accepting Set/Push while ignoring Query advertises
        // a partial protocol that applications cannot use losslessly, and Pop
        // must not clear an independently enabled xterm extended-key mode.
        CsiCommand::KittyKeyboardSet
        | CsiCommand::KittyKeyboardPush
        | CsiCommand::KittyKeyboardPop
        | CsiCommand::KittyKeyboardQuery => {}
        CsiCommand::Modoff => {
            let n = parser.param_list.get(0, 0, 0);
            if n != 4 {
                return;
            }
            writer.mode_clear(mode::EXTENDED_KEY_MODES);
        }
        CsiCommand::Scp => {
            // Save cursor position.
            parser.saved.cell = parser.cell.clone();
            parser.saved.cx = writer.cursor_x();
            parser.saved.cy = writer.cursor_y();
            parser.saved.mode_origin = (writer.current_mode() & mode::MODE_ORIGIN) != 0;
        }
        CsiCommand::Rcp => {
            // Restore cursor position.
            parser.cell = parser.saved.cell.clone();
            if parser.saved.mode_origin {
                writer.mode_set(mode::MODE_ORIGIN);
            } else {
                writer.mode_clear(mode::MODE_ORIGIN);
            }
            writer.cursor_move(parser.saved.cx as i32, parser.saved.cy as i32, false);
        }
        CsiCommand::Decscusr => {
            let n = parser.param_list.get(0, 0, 0);
            if n != -1 {
                writer.set_cursor_style(n as u32);
                if n == 0 {
                    // Go back to default blinking state.
                    writer.mode_clear(mode::MODE_CURSOR_BLINKING_SET);
                }
            }
        }
        CsiCommand::Xda => {
            let n = parser.param_list.get(0, 0, 0);
            if n == 0 {
                parser.reply(XTVERSION_REPLY);
            }
        }
        CsiCommand::Winops => dispatch_winops(parser, writer),
    }
}

// ─── OSC dispatch ──────────────────────────────────────────────────

pub(crate) fn dispatch_osc<W: ScreenWriter + ?Sized>(parser: &mut InputParser, writer: &mut W) {
    let buf = &parser.input_buf;
    if buf.is_empty() {
        return;
    }

    // Parse OSC number.
    let mut i = 0;
    if buf[i] < b'0' || buf[i] > b'9' {
        return;
    }
    let mut option: u32 = 0;
    while i < buf.len() && buf[i] >= b'0' && buf[i] <= b'9' {
        option = option
            .saturating_mul(10)
            .saturating_add(u32::from(buf[i] - b'0'));
        i += 1;
    }
    if i < buf.len() && buf[i] != b';' && buf[i] != 0 {
        return;
    }
    if i < buf.len() && buf[i] == b';' {
        i += 1;
    }

    // Owned: the OSC 10/11/12 arms below mutate parser state (stored colours
    // and the reply buffer) while the payload is still in use.
    let data = String::from_utf8_lossy(&buf[i..]).into_owned();
    let end = parser.input_end;

    match option {
        0 | 2 => writer.set_title(&data),
        4 => writer.osc_palette(&data, end),
        7 => writer.set_path(&data),
        8 => {
            writer.osc_hyperlink(&data);
            parser.cell.cell.link = writer.current_hyperlink_id();
        }
        9 => writer.osc_notification(&data),
        10 if !answer_osc_colour_query(parser, OscColourSlot::Foreground, &data, end) => {
            parser.set_osc_colour(OscColourSlot::Foreground, &data);
            writer.osc_fg_colour(&data, end);
        }
        11 if !answer_osc_colour_query(parser, OscColourSlot::Background, &data, end) => {
            parser.set_osc_colour(OscColourSlot::Background, &data);
            writer.osc_bg_colour(&data, end);
        }
        12 if !answer_osc_colour_query(parser, OscColourSlot::Cursor, &data, end) => {
            parser.set_osc_colour(OscColourSlot::Cursor, &data);
            writer.osc_cursor_colour(&data, end);
        }
        52 => writer.osc_clipboard(&data, end),
        104 => writer.osc_reset_palette(&data),
        110 => {
            parser.reset_osc_colour(OscColourSlot::Foreground);
            writer.osc_reset_fg();
        }
        111 => {
            parser.reset_osc_colour(OscColourSlot::Background);
            writer.osc_reset_bg();
        }
        112 => {
            parser.reset_osc_colour(OscColourSlot::Cursor);
            writer.osc_reset_cursor();
        }
        133 => writer.osc_shell_integration(&data),
        _ => {}
    }
}

// ─── DCS dispatch ──────────────────────────────────────────────────

pub(crate) fn dispatch_dcs<W: ScreenWriter + ?Sized>(parser: &mut InputParser, writer: &mut W) {
    let buf = &parser.input_buf;

    // DECRQSS: intermediate '$', first byte 'q'.
    if parser.interm_len == 1 && parser.interm_buf[0] == b'$' && !buf.is_empty() && buf[0] == b'q' {
        parser.reply("\x1bP0$r\x1b\\"); // Not recognized.
        return;
    }

    // tmux passthrough: DCS with `tmux;` prefix.
    if buf.starts_with(b"tmux;") {
        writer.dcs_passthrough(&buf[5..]);
        return;
    }

    // Sixel: final byte 'q' with no intermediates. Preserve DCS parameters
    // before the final byte so the outer terminal receives the original image
    // command, minus the ESC P / ST framing.
    if parser.interm_len == 0 && buf.first() == Some(&b'q') {
        let mut payload = Vec::with_capacity(parser.param_len + buf.len());
        payload.extend_from_slice(&parser.param_buf[..parser.param_len]);
        payload.extend_from_slice(buf);
        writer.sixel_passthrough(&payload);
    }
}

/// Answers an OSC 10/11/12 colour query only when the application previously
/// set that exact per-pane slot. RMUX cannot observe the attached terminal's
/// palette, so an unknown value must remain unanswered rather than
/// impersonating a confidently wrong theme. Returns false for set-colour
/// payloads, which callers handle as before.
fn answer_osc_colour_query(
    parser: &mut InputParser,
    slot: OscColourSlot,
    data: &str,
    end: InputEndType,
) -> bool {
    if data != "?" {
        return false;
    }

    if let Some(colour) = parser.osc_colour(slot) {
        let reply = format!(
            "\x1b]{};{}{}",
            slot.osc_number(),
            colour,
            match end {
                InputEndType::Bel => "\x07",
                InputEndType::St => "\x1b\\",
            }
        );
        parser.reply(&reply);
    }
    true
}