Debian Codegraph @

Xtermina/src/escape/csi.rs

raw symbols SCIP
1 //! Strongly typed Control Sequence Introducer (CSI) escape sequences.
2 //!
3 //! Each enum in this module represents a family of CSI sequences and implements [`Display`] where
4 //! Termina knows how to emit the sequence. This keeps terminal control code explicit while still
5 //! allowing applications to write the formatted value directly to any [`std::io::Write`] target.
6 //!
7 //! # Implementation Notes
8 //!
9 //! This module is adapted from [termwiz's CSI support], but it was incrementally pulled across
10 //! rather than copied wholesale. Termina keeps a curated subset, removes conversion traits, and
11 //! adds focused extensions such as Contour theme reporting and the [`SgrAttributes`] /
12 //! [`SgrModifiers`] grouping types. TermWiz has a more complete set of CSI escape sequences.
13 //!
14 //! [termwiz's CSI support]: https://docs.rs/termwiz/latest/termwiz/escape/enum.Csi.html
15
16 use std::{
17 fmt::{self, Display},
18 num::NonZeroU16,
19 };
20
21 use crate::{
22 event::Modifiers,
23 style::{Blink, ColorSpec, CursorStyle, Font, Intensity, RgbaColor, Underline, VerticalAlign},
24 OneBased,
25 };
26
27 /// A Control Sequence Introducer command.
28 ///
29 /// Formatting writes the `ESC [` introducer followed by the command family payload. CSI commands
30 /// are the main terminal protocol surface for cursor movement, text styling, mode changes, device
31 /// reports, mouse reports, and window operations.
32 #[derive(Debug, Clone, PartialEq, Eq)]
33 pub enum Csi {
34 /// Select Graphic Rendition commands described by [`Sgr`].
35 ///
36 /// These `CSI ... m` commands change how subsequent cells are rendered.
37 Sgr(Sgr),
38
39 /// Cursor commands described by [`Cursor`].
40 ///
41 /// This family covers cursor movement, cursor shape, margins, and position reports.
42 Cursor(Cursor),
43
44 /// Text and display editing commands described by [`Edit`].
45 ///
46 /// This family covers insert, delete, erase, repeat, and scroll operations.
47 Edit(Edit),
48
49 /// Terminal mode commands described by [`Mode`].
50 ///
51 /// This family covers setting, resetting, saving, restoring, querying, and reporting terminal
52 /// modes.
53 Mode(Mode),
54
55 /// Mouse input reports described by [`MouseReport`].
56 ///
57 /// Modes such as [`DecPrivateModeCode::MouseTracking`],
58 /// [`DecPrivateModeCode::ButtonEventMouse`], and [`DecPrivateModeCode::AnyEventMouse`]
59 /// control when terminals send these reports.
60 Mouse(MouseReport),
61
62 /// Kitty keyboard protocol commands described by [`Keyboard`].
63 ///
64 /// This family covers flag query, report, push, pop, and set commands.
65 Keyboard(Keyboard),
66
67 /// Device and status commands described by [`Device`].
68 ///
69 /// This family covers device attributes, terminal status, terminal identity, and terminal
70 /// parameters.
71 Device(Device),
72
73 /// Window commands described by [`Window`].
74 ///
75 /// This family covers window manipulation and reports, mostly from xterm-compatible
76 /// extensions.
77 Window(Box<Window>),
78 }
79
80 impl Display for Csi {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 // This here is the "control sequence introducer" (CSI):
83 f.write_str(super::CSI)?;
84 match self {
85 Self::Sgr(sgr) => write!(f, "{sgr}m"),
86 Self::Cursor(cursor) => cursor.fmt(f),
87 Self::Edit(edit) => edit.fmt(f),
88 Self::Mode(mode) => mode.fmt(f),
89 Self::Mouse(report) => report.fmt(f),
90 Self::Keyboard(keyboard) => keyboard.fmt(f),
91 Self::Device(device) => device.fmt(f),
92 Self::Window(window) => window.fmt(f),
93 }
94 }
95 }
96
97 /// A Select Graphic Rendition (`CSI ... m`) attribute update.
98 ///
99 /// SGR changes rendering state for text written after the sequence: color, intensity, underline,
100 /// blink, and related cell attributes. Terminals keep that state until another SGR command changes
101 /// it or [`Self::Reset`] clears it. The VT510 reference documents the standard [SGR] parameter
102 /// meanings that Termina models here.
103 ///
104 /// [SGR]: https://vt100.net/docs/vt510-rm/SGR.html
105 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
106 pub enum Sgr {
107 /// SGR 0: reset all graphic rendition attributes to terminal defaults.
108 Reset,
109
110 /// Set text intensity described by [`Intensity`].
111 Intensity(Intensity),
112
113 /// Set underline style described by [`Underline`].
114 ///
115 /// This includes Kitty's styled underline extension when terminals support it.
116 Underline(Underline),
117
118 /// Set blink behavior described by [`Blink`].
119 Blink(Blink),
120
121 /// Enable SGR 3 italic text or disable it with SGR 23.
122 Italic(bool),
123
124 /// Enable SGR 7 reverse video or disable it with SGR 27.
125 Reverse(bool),
126
127 /// Enable SGR 8 invisible text or disable it with SGR 28.
128 Invisible(bool),
129
130 /// Enable SGR 9 strikethrough text or disable it with SGR 29.
131 StrikeThrough(bool),
132
133 /// Enable SGR 53 overline text or disable it with SGR 55.
134 Overline(bool),
135
136 /// Select the active font described by [`Font`].
137 Font(Font),
138
139 /// Set vertical alignment described by [`VerticalAlign`].
140 VerticalAlign(VerticalAlign),
141
142 /// Set the foreground color described by [`ColorSpec`].
143 Foreground(ColorSpec),
144
145 /// Set the background color described by [`ColorSpec`].
146 Background(ColorSpec),
147
148 /// Set the underline color described by [`ColorSpec`].
149 ///
150 /// This uses the SGR 58 underline-color extension.
151 UnderlineColor(ColorSpec),
152
153 /// Combine multiple SGR updates described by [`SgrAttributes`].
154 Attributes(SgrAttributes),
155 }
156
157 impl Display for Sgr {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 fn write_true_color(
160 code: u8,
161 RgbaColor {
162 red,
163 green,
164 blue,
165 alpha,
166 }: RgbaColor,
167 f: &mut fmt::Formatter,
168 ) -> fmt::Result {
169 if alpha == 255 {
170 // [ITU T.416](https://www.itu.int/rec/T-REC-T.416-199303-I/en) ยง 13.1.8
171 // says that the correct way to format true colors, even for foreground/background
172 // is `{code}:2:{colorspace (optional)}:{red}:{green}:{blue}`. More commonly than
173 // not though terminals support the semicolon format shown below. We use semicolon
174 // as it seems to have better compatibility in the wild, especially with legacy or
175 // limited terminals like Windows conhost.
176 //
177 // The Microsoft docs also recommend the semicolon format (however Windows
178 // Terminal accepts either):
179 // <https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#extended-colors>
180 write!(f, "{code};2;{red};{green};{blue}")
181 } else {
182 write!(f, "{code}:6::{red}:{green}:{blue}:{alpha}")
183 }
184 }
185
186 // CSI <n> m
187 match self {
188 // The proper thing to do here is `write!(f, "0")?`. By default though when no Ps
189 // is specified the terminal defaults to 0, so we can save a byte here.
190 Self::Reset => (),
191 Self::Intensity(Intensity::Normal) => write!(f, "22")?,
192 Self::Intensity(Intensity::Bold) => write!(f, "1")?,
193 Self::Intensity(Intensity::Dim) => write!(f, "2")?,
194 Self::Underline(Underline::None) => write!(f, "24")?,
195 Self::Underline(Underline::Single) => write!(f, "4")?,
196 Self::Underline(Underline::Double) => write!(f, "21")?,
197 Self::Underline(Underline::Curly) => write!(f, "4:3")?,
198 Self::Underline(Underline::Dotted) => write!(f, "4:4")?,
199 Self::Underline(Underline::Dashed) => write!(f, "4:5")?,
200 Self::Blink(Blink::None) => write!(f, "25")?,
201 Self::Blink(Blink::Slow) => write!(f, "5")?,
202 Self::Blink(Blink::Rapid) => write!(f, "6")?,
203 Self::Italic(true) => write!(f, "3")?,
204 Self::Italic(false) => write!(f, "23")?,
205 Self::Reverse(true) => write!(f, "7")?,
206 Self::Reverse(false) => write!(f, "27")?,
207 Self::Invisible(true) => write!(f, "8")?,
208 Self::Invisible(false) => write!(f, "28")?,
209 Self::StrikeThrough(true) => write!(f, "9")?,
210 Self::StrikeThrough(false) => write!(f, "29")?,
211 Self::Overline(true) => write!(f, "53")?,
212 Self::Overline(false) => write!(f, "55")?,
213 Self::Font(Font::Default) => write!(f, "10")?,
214 Self::Font(Font::Alternate(1)) => write!(f, "11")?,
215 Self::Font(Font::Alternate(2)) => write!(f, "12")?,
216 Self::Font(Font::Alternate(3)) => write!(f, "13")?,
217 Self::Font(Font::Alternate(4)) => write!(f, "14")?,
218 Self::Font(Font::Alternate(5)) => write!(f, "15")?,
219 Self::Font(Font::Alternate(6)) => write!(f, "16")?,
220 Self::Font(Font::Alternate(7)) => write!(f, "17")?,
221 Self::Font(Font::Alternate(8)) => write!(f, "18")?,
222 Self::Font(Font::Alternate(9)) => write!(f, "19")?,
223 Self::Font(_) => (),
224 Self::VerticalAlign(VerticalAlign::BaseLine) => write!(f, "75")?,
225 Self::VerticalAlign(VerticalAlign::SuperScript) => write!(f, "73")?,
226 Self::VerticalAlign(VerticalAlign::SubScript) => write!(f, "74")?,
227 Self::Foreground(ColorSpec::Reset) => write!(f, "39")?,
228 Self::Foreground(ColorSpec::BLACK) => write!(f, "30")?,
229 Self::Foreground(ColorSpec::RED) => write!(f, "31")?,
230 Self::Foreground(ColorSpec::GREEN) => write!(f, "32")?,
231 Self::Foreground(ColorSpec::YELLOW) => write!(f, "33")?,
232 Self::Foreground(ColorSpec::BLUE) => write!(f, "34")?,
233 Self::Foreground(ColorSpec::MAGENTA) => write!(f, "35")?,
234 Self::Foreground(ColorSpec::CYAN) => write!(f, "36")?,
235 Self::Foreground(ColorSpec::WHITE) => write!(f, "37")?,
236 Self::Foreground(ColorSpec::BRIGHT_BLACK) => write!(f, "90")?,
237 Self::Foreground(ColorSpec::BRIGHT_RED) => write!(f, "91")?,
238 Self::Foreground(ColorSpec::BRIGHT_GREEN) => write!(f, "92")?,
239 Self::Foreground(ColorSpec::BRIGHT_YELLOW) => write!(f, "93")?,
240 Self::Foreground(ColorSpec::BRIGHT_BLUE) => write!(f, "94")?,
241 Self::Foreground(ColorSpec::BRIGHT_MAGENTA) => write!(f, "95")?,
242 Self::Foreground(ColorSpec::BRIGHT_CYAN) => write!(f, "96")?,
243 Self::Foreground(ColorSpec::BRIGHT_WHITE) => write!(f, "97")?,
244 Self::Foreground(ColorSpec::PaletteIndex(idx)) => write!(f, "38;5;{idx}")?,
245 Self::Foreground(ColorSpec::TrueColor(color)) => write_true_color(38, *color, f)?,
246 Self::Background(ColorSpec::Reset) => write!(f, "49")?,
247 Self::Background(ColorSpec::BLACK) => write!(f, "40")?,
248 Self::Background(ColorSpec::RED) => write!(f, "41")?,
249 Self::Background(ColorSpec::GREEN) => write!(f, "42")?,
250 Self::Background(ColorSpec::YELLOW) => write!(f, "43")?,
251 Self::Background(ColorSpec::BLUE) => write!(f, "44")?,
252 Self::Background(ColorSpec::MAGENTA) => write!(f, "45")?,
253 Self::Background(ColorSpec::CYAN) => write!(f, "46")?,
254 Self::Background(ColorSpec::WHITE) => write!(f, "47")?,
255 Self::Background(ColorSpec::BRIGHT_BLACK) => write!(f, "100")?,
256 Self::Background(ColorSpec::BRIGHT_RED) => write!(f, "101")?,
257 Self::Background(ColorSpec::BRIGHT_GREEN) => write!(f, "102")?,
258 Self::Background(ColorSpec::BRIGHT_YELLOW) => write!(f, "103")?,
259 Self::Background(ColorSpec::BRIGHT_BLUE) => write!(f, "104")?,
260 Self::Background(ColorSpec::BRIGHT_MAGENTA) => write!(f, "105")?,
261 Self::Background(ColorSpec::BRIGHT_CYAN) => write!(f, "106")?,
262 Self::Background(ColorSpec::BRIGHT_WHITE) => write!(f, "107")?,
263 Self::Background(ColorSpec::PaletteIndex(idx)) => write!(f, "48;5;{idx}")?,
264 Self::Background(ColorSpec::TrueColor(color)) => write_true_color(48, *color, f)?,
265 Self::UnderlineColor(ColorSpec::Reset) => write!(f, "59")?,
266 Self::UnderlineColor(ColorSpec::PaletteIndex(idx)) => write!(f, "58:5:{idx}")?,
267 Self::UnderlineColor(ColorSpec::TrueColor(RgbaColor {
268 red,
269 green,
270 blue,
271 alpha: 255,
272 })) => {
273 // As mentioned above in `write_true_color`, this is the _correct_ format for a
274 // true color. Styled and colored underlines are a relatively new extension and
275 // terminals tend to support colon syntax since it is correct.
276 write!(f, "58:2::{red}:{green}:{blue}")?;
277 }
278 Self::UnderlineColor(ColorSpec::TrueColor(RgbaColor {
279 red,
280 green,
281 blue,
282 alpha,
283 })) => {
284 write!(f, "58:6::{red}:{green}:{blue}:{alpha}")?;
285 }
286 Self::Attributes(attributes) => {
287 use SgrModifiers as Mod;
288
289 let ps_budget = attributes.parameter_chunk_size.get();
290 let mut ps_written = 0;
291 let mut first = true;
292 let mut write = |sgr: Self, n_ps: u16| {
293 // If writing this parameter would exceed the budget, finish this CSI sequence
294 // and start a new one which will start with this SGR.
295 ps_written += n_ps;
296 if ps_written > ps_budget {
297 write!(f, "m{}", super::CSI)?;
298 ps_written = n_ps;
299 } else if !first {
300 f.write_str(";")?;
301 }
302 first = false;
303 write!(f, "{sgr}")
304 };
305 if attributes.modifiers.contains(Mod::RESET) {
306 write(Self::Reset, 0)?;
307 }
308 if let Some(color) = attributes.foreground {
309 write(
310 Self::Foreground(color),
311 // TODO: for colors currently we estimate the largest Ps count. This could
312 // be fine-tuned a bit more.
313 match color {
314 ColorSpec::Reset => 1,
315 ColorSpec::PaletteIndex(_) => 3,
316 ColorSpec::TrueColor(RgbaColor { alpha: 255, .. }) => 5,
317 ColorSpec::TrueColor(_) => 6,
318 },
319 )?;
320 }
321 if let Some(color) = attributes.background {
322 write(
323 Self::Background(color),
324 match color {
325 ColorSpec::Reset => 1,
326 ColorSpec::PaletteIndex(_) => 3,
327 ColorSpec::TrueColor(RgbaColor { alpha: 255, .. }) => 5,
328 ColorSpec::TrueColor(_) => 6,
329 },
330 )?;
331 }
332 if let Some(color) = attributes.underline_color {
333 write(
334 Self::UnderlineColor(color),
335 match color {
336 ColorSpec::Reset => 1,
337 ColorSpec::PaletteIndex(_) => 3,
338 ColorSpec::TrueColor(_) => 6,
339 },
340 )?;
341 }
342 if attributes.modifiers.contains(Mod::INTENSITY_NORMAL) {
343 write(Self::Intensity(Intensity::Normal), 1)?;
344 }
345 if attributes.modifiers.contains(Mod::INTENSITY_DIM) {
346 write(Self::Intensity(Intensity::Dim), 1)?;
347 }
348 if attributes.modifiers.contains(Mod::INTENSITY_BOLD) {
349 write(Self::Intensity(Intensity::Bold), 1)?;
350 }
351 if attributes.modifiers.contains(Mod::UNDERLINE_NONE) {
352 write(Self::Underline(Underline::None), 1)?;
353 }
354 if attributes.modifiers.contains(Mod::UNDERLINE_SINGLE) {
355 write(Self::Underline(Underline::Single), 1)?;
356 }
357 if attributes.modifiers.contains(Mod::UNDERLINE_DOUBLE) {
358 write(Self::Underline(Underline::Double), 1)?;
359 }
360 if attributes.modifiers.contains(Mod::UNDERLINE_CURLY) {
361 write(Self::Underline(Underline::Curly), 2)?;
362 }
363 if attributes.modifiers.contains(Mod::UNDERLINE_DOTTED) {
364 write(Self::Underline(Underline::Dotted), 2)?;
365 }
366 if attributes.modifiers.contains(Mod::UNDERLINE_DASHED) {
367 write(Self::Underline(Underline::Dashed), 2)?;
368 }
369 if attributes.modifiers.contains(Mod::BLINK_NONE) {
370 write(Self::Blink(Blink::None), 1)?;
371 }
372 if attributes.modifiers.contains(Mod::BLINK_SLOW) {
373 write(Self::Blink(Blink::Slow), 1)?;
374 }
375 if attributes.modifiers.contains(Mod::BLINK_RAPID) {
376 write(Self::Blink(Blink::Rapid), 1)?;
377 }
378 if attributes.modifiers.contains(Mod::ITALIC) {
379 write(Self::Italic(true), 1)?;
380 }
381 if attributes.modifiers.contains(Mod::NO_ITALIC) {
382 write(Self::Italic(false), 1)?;
383 }
384 if attributes.modifiers.contains(Mod::REVERSE) {
385 write(Self::Reverse(true), 1)?;
386 }
387 if attributes.modifiers.contains(Mod::NO_REVERSE) {
388 write(Self::Reverse(false), 1)?;
389 }
390 if attributes.modifiers.contains(Mod::INVISIBLE) {
391 write(Self::Invisible(true), 1)?;
392 }
393 if attributes.modifiers.contains(Mod::NO_INVISIBLE) {
394 write(Self::Invisible(false), 1)?;
395 }
396 if attributes.modifiers.contains(Mod::STRIKE_THROUGH) {
397 write(Self::StrikeThrough(true), 1)?;
398 }
399 if attributes.modifiers.contains(Mod::NO_STRIKE_THROUGH) {
400 write(Self::StrikeThrough(false), 1)?;
401 }
402 }
403 }
404 Ok(())
405 }
406 }
407
408 /// A grouped SGR update.
409 ///
410 /// [`Sgr`] accepts more than one parameter in a single `CSI ... m` sequence, so one escape can set
411 /// the foreground color, background color, underline color, and text modifiers together. Grouping
412 /// related changes reduces the number of bytes written and the number of CSI sequences the
413 /// terminal has to parse.
414 ///
415 /// Note that if no attributes are set ([`SgrAttributes::default`]) the terminal will treat the
416 /// escape the same as [`Sgr::Reset`]. So if you are using this type you may wish to compare the
417 /// attributes you've built with [`SgrAttributes::default`] to decide whether or not you want to
418 /// write it to the terminal. Otherwise the escape codes for this type do not reset SGR. The
419 /// example below sets a green foreground and bold intensity but would not affect any other SGR
420 /// settings like underline or background color.
421 ///
422 /// ```
423 /// # use termina::escape::csi::{Csi, Sgr, SgrAttributes, SgrModifiers};
424 /// # use termina::style::{ColorSpec, Intensity};
425 /// let attributes = SgrAttributes {
426 /// foreground: Some(ColorSpec::GREEN),
427 /// modifiers: SgrModifiers::INTENSITY_BOLD,
428 /// ..Default::default()
429 /// };
430 /// // Both SGR codes are in one CSI escape.
431 /// assert_eq!(Csi::Sgr(Sgr::Attributes(attributes)).to_string(), "\x1b[32;1m");
432 /// // Compare to emitting them separately:
433 /// assert_eq!(Csi::Sgr(Sgr::Foreground(ColorSpec::GREEN)).to_string(), "\x1b[32m");
434 /// assert_eq!(Csi::Sgr(Sgr::Intensity(Intensity::Bold)).to_string(), "\x1b[1m");
435 /// ```
436 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
437 // > You can use more than one Ps value to select different character attributes.
438 // <https://vt100.net/docs/vt510-rm/SGR>
439 pub struct SgrAttributes {
440 /// The foreground color used to paint text.
441 pub foreground: Option<ColorSpec>,
442
443 /// The background color used to paint the cell.
444 pub background: Option<ColorSpec>,
445
446 /// The color of the underline in the current cell.
447 pub underline_color: Option<ColorSpec>,
448
449 /// Bitflags for text modifiers such as intensity, underline, blink, italic, and reverse video.
450 pub modifiers: SgrModifiers,
451
452 /// The number of parameters which are allowed in a chunk.
453 ///
454 /// The VT parsers used in many terminal emulators set limits on the number of parameters a
455 /// CSI sequence can use. After the limit they typically ignore all other parameters. For
456 /// many terminals this is a relatively high number like 256 but some set their limit as low as
457 /// 10. For maximum compatibility this is set to 10 by default.
458 ///
459 /// The number of parameters taken to describe a modifier varies by modifier. True-color colors
460 /// (foreground, background, underline color) take the most while simple modifiers like
461 /// [`SgrModifiers::ITALIC`] take just one.
462 pub parameter_chunk_size: NonZeroU16,
463 }
464
465 impl Default for SgrAttributes {
466 fn default() -> Self {
467 Self {
468 foreground: Default::default(),
469 background: Default::default(),
470 underline_color: Default::default(),
471 modifiers: Default::default(),
472 parameter_chunk_size: unsafe { NonZeroU16::new_unchecked(10) },
473 }
474 }
475 }
476
477 impl SgrAttributes {
478 /// Returns `true` if no attributes are set, `false` otherwise.
479 ///
480 /// When empty attributes are displayed they produce the same escape sequence as [`Sgr::Reset`].
481 /// If you are building attributes incrementally starting with [`SgrAttributes::default`] then
482 /// you may wish to check whether the attributes are empty to decide whether or not you should
483 /// write them to the terminal.
484 ///
485 /// ```
486 /// # use termina::escape::csi::{Csi, Sgr, SgrAttributes, SgrModifiers};
487 /// let mut attributes = SgrAttributes::default();
488 /// assert!(attributes.is_empty());
489 /// assert_eq!(
490 /// Csi::Sgr(Sgr::Reset).to_string(),
491 /// Csi::Sgr(Sgr::Attributes(attributes)).to_string(),
492 /// );
493 ///
494 /// attributes.modifiers |= SgrModifiers::ITALIC;
495 /// assert!(!attributes.is_empty());
496 /// ```
497 #[inline]
498 pub fn is_empty(&self) -> bool {
499 self.foreground.is_none()
500 && self.background.is_none()
501 && self.underline_color.is_none()
502 && self.modifiers.is_empty()
503 }
504 }
505
506 // We could represent `SgrAttributes` as a `Vec<Sgr>` but we can flatten the type out to have a
507 // more compact representation with bitflags for each SGR instead:
508 bitflags::bitflags! {
509 /// SGR modifier bits used by [`SgrAttributes`].
510 ///
511 /// These flags mirror SGR attributes that can be represented without carrying additional
512 /// color or font data.
513 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
514 pub struct SgrModifiers: u32 {
515 /// No SGR modifiers.
516 const NONE = 0;
517
518 /// SGR 0: reset all attributes.
519 const RESET = 1 << 1;
520
521 /// SGR 22: normal intensity.
522 const INTENSITY_NORMAL = 1 << 2;
523
524 /// SGR 2: dim intensity.
525 const INTENSITY_DIM = 1 << 3;
526
527 /// SGR 1: bold intensity.
528 const INTENSITY_BOLD = 1 << 4;
529
530 /// SGR 24: no underline.
531 const UNDERLINE_NONE = 1 << 5;
532
533 /// SGR 4: single underline.
534 const UNDERLINE_SINGLE = 1 << 6;
535
536 /// SGR 21: double underline.
537 const UNDERLINE_DOUBLE = 1 << 7;
538
539 /// Kitty underline style 3: curly underline.
540 const UNDERLINE_CURLY = 1 << 8;
541
542 /// Kitty underline style 4: dotted underline.
543 const UNDERLINE_DOTTED = 1 << 9;
544
545 /// Kitty underline style 5: dashed underline.
546 const UNDERLINE_DASHED = 1 << 10;
547
548 /// SGR 25: no blink.
549 const BLINK_NONE = 1 << 11;
550
551 /// SGR 5: slow blink.
552 const BLINK_SLOW = 1 << 12;
553
554 /// SGR 6: rapid blink.
555 const BLINK_RAPID = 1 << 13;
556
557 /// SGR 3: italic.
558 const ITALIC = 1 << 14;
559
560 /// SGR 23: no italic.
561 const NO_ITALIC = 1 << 15;
562
563 /// SGR 7: reverse video.
564 const REVERSE = 1 << 16;
565
566 /// SGR 27: no reverse video.
567 const NO_REVERSE = 1 << 17;
568
569 /// SGR 8: invisible text.
570 const INVISIBLE = 1 << 18;
571
572 /// SGR 28: visible text.
573 const NO_INVISIBLE = 1 << 19;
574
575 /// SGR 9: strikethrough.
576 const STRIKE_THROUGH = 1 << 20;
577
578 /// SGR 29: no strikethrough.
579 const NO_STRIKE_THROUGH = 1 << 21;
580 // Support font and vertical align? They're not well supported in terminals so I think
581 // it's fine to leave them out of this type.
582 }
583 }
584
585 impl Default for SgrModifiers {
586 fn default() -> Self {
587 Self::NONE
588 }
589 }
590
591 // Cursor
592
593 /// The cursor shape for the Kitty multi-cursor protocol.
594 ///
595 /// This represents either a specific [`CursorStyle`] (protocol values 0-6)
596 /// or the special "follow main cursor" value (protocol value 29).
597 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
598 pub enum MultiCursorShape {
599 /// Use a specific cursor style for secondary cursors.
600 Style(CursorStyle),
601
602 /// Use the main cursor's current shape for secondary cursors.
603 FollowMainCursor,
604 }
605
606 /// Supported operations in the kitty multi-cursor protocol.
607 ///
608 /// Returned in the capability query response (`CSI > SP q`). Each variant
609 /// corresponds to a protocol operation code the terminal advertises support for.
610 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
611 pub enum MultiCursorCapability {
612 /// Block cursor shape.
613 BlockShape = 1,
614 /// Beam cursor shape.
615 BeamShape = 2,
616 /// Underline cursor shape.
617 UnderlineShape = 3,
618 /// Follow the main cursor's shape.
619 FollowMainCursorShape = 29,
620 /// Change the color of text under extra cursors.
621 TextColor = 30,
622 /// Change the color of extra cursors.
623 CursorColor = 40,
624 /// Query currently set cursors.
625 QueryCurrentCursors = 100,
626 /// Query extra cursor colors.
627 QueryColors = 101,
628 }
629
630 impl TryFrom<u8> for MultiCursorCapability {
631 type Error = u8;
632
633 fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
634 match value {
635 1 => Ok(Self::BlockShape),
636 2 => Ok(Self::BeamShape),
637 3 => Ok(Self::UnderlineShape),
638 29 => Ok(Self::FollowMainCursorShape),
639 30 => Ok(Self::TextColor),
640 40 => Ok(Self::CursorColor),
641 100 => Ok(Self::QueryCurrentCursors),
642 101 => Ok(Self::QueryColors),
643 _ => Err(value),
644 }
645 }
646 }
647
648 /// Cursor-related CSI commands.
649 ///
650 /// This includes cursor movement, tabulation, position reports, margins, cursor style, and
651 /// Kitty's multi-cursor extension.
652 ///
653 /// ```
654 /// use termina::{
655 /// escape::csi::{Csi, Cursor},
656 /// OneBased,
657 /// };
658 ///
659 /// let position = Cursor::Position {
660 /// line: OneBased::new(3).unwrap(),
661 /// col: OneBased::new(10).unwrap(),
662 /// };
663 /// assert_eq!(Csi::Cursor(position).to_string(), "\x1b[3;10H");
664 /// assert_eq!(Csi::Cursor(Cursor::default_position()).to_string(), "\x1b[1;1H");
665 /// ```
666 #[derive(Debug, Clone, PartialEq, Eq)]
667 pub enum Cursor {
668 /// CBT Moves cursor to the Ps tabs backward. The default value of Ps is 1.
669 BackwardTabulation(u32),
670
671 /// TBC - TABULATION CLEAR
672 TabulationClear(TabulationClear),
673
674 /// CHA: Moves cursor to the Ps-th column of the active line. The default
675 /// value of Ps is 1.
676 CharacterAbsolute(OneBased),
677
678 /// HPA CHARACTER POSITION ABSOLUTE
679 /// HPA Moves cursor to the Ps-th column of the active line. The default
680 /// value of Ps is 1.
681 CharacterPositionAbsolute(OneBased),
682
683 /// HPB - CHARACTER POSITION BACKWARD
684 /// HPB Moves cursor to the left Ps columns. The default value of Ps is 1.
685 CharacterPositionBackward(u32),
686
687 /// HPR - CHARACTER POSITION FORWARD
688 /// HPR Moves cursor to the right Ps columns. The default value of Ps is 1.
689 CharacterPositionForward(u32),
690
691 /// HVP - CHARACTER AND LINE POSITION
692 /// HVP Moves cursor to the Ps1-th line and to the Ps2-th column. The
693 /// default value of Ps1 and Ps2 is 1.
694 CharacterAndLinePosition {
695 /// The destination line.
696 line: OneBased,
697 /// The destination column.
698 col: OneBased,
699 },
700
701 /// VPA - LINE POSITION ABSOLUTE
702 /// Move to the corresponding vertical position (line Ps) of the current
703 /// column. The default value of Ps is 1.
704 LinePositionAbsolute(u32),
705
706 /// VPB - LINE POSITION BACKWARD
707 /// Moves cursor up Ps lines in the same column. The default value of Ps is
708 /// 1.
709 LinePositionBackward(u32),
710
711 /// VPR - LINE POSITION FORWARD
712 /// Moves cursor down Ps lines in the same column. The default value of Ps
713 /// is 1.
714 LinePositionForward(u32),
715
716 /// CHT
717 /// Moves cursor to the Ps tabs forward. The default value of Ps is 1.
718 ForwardTabulation(u32),
719
720 /// CNL Moves cursor to the first column of Ps-th following line. The
721 /// default value of Ps is 1.
722 NextLine(u32),
723
724 /// CPL Moves cursor to the first column of Ps-th preceding line. The
725 /// default value of Ps is 1.
726 PrecedingLine(u32),
727
728 /// CPR - ACTIVE POSITION REPORT
729 /// If the DEVICE COMPONENT SELECT MODE (DCSM)
730 /// is set to PRESENTATION, CPR is used to report the active presentation
731 /// position of the sending device as residing in the presentation
732 /// component at the n-th line position according to the line progression
733 /// and at the m-th character position according to the character path,
734 /// where n equals the value of Pn1 and m equal s the value of Pn2.
735 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to DATA, CPR is used
736 /// to report the active data position of the sending device as
737 /// residing in the data component at the n-th line position according
738 /// to the line progression and at the m-th character position
739 /// according to the character progression, where n equals the value of
740 /// Pn1 and m equals the value of Pn2. CPR may be solicited by a DEVICE
741 /// STATUS REPORT (DSR) or be sent unsolicited .
742 ActivePositionReport {
743 /// The reported line.
744 line: OneBased,
745 /// The reported column.
746 col: OneBased,
747 },
748
749 /// CPR: this is the request from the client.
750 /// The terminal will respond with ActivePositionReport.
751 RequestActivePositionReport,
752
753 /// SCP - Save Cursor Position.
754 /// Only works when DECLRMM is disabled
755 SaveCursor,
756
757 /// RCP - Restore Cursor Position.
758 RestoreCursor,
759
760 /// CTC - CURSOR TABULATION CONTROL
761 /// CTC causes one or more tabulation stops to be set or cleared in the
762 /// presentation component, depending on the parameter values.
763 /// In the case of parameter values 0, 2 or 4 the number of lines affected
764 /// depends on the setting of the TABULATION STOP MODE (TSM).
765 TabulationControl(CursorTabulationControl),
766
767 /// CUB - Cursor Left
768 /// Moves cursor to the left Ps columns. The default value of Ps is 1.
769 Left(u32),
770
771 /// CUD - Cursor Down
772 Down(u32),
773
774 /// CUF - Cursor Right
775 Right(u32),
776
777 /// CUU - Cursor Up
778 Up(u32),
779
780 /// CUP - Cursor Position
781 /// Moves cursor to the Ps1-th line and to the Ps2-th column. The default
782 /// value of Ps1 and Ps2 is 1.
783 Position {
784 /// The destination line.
785 line: OneBased,
786 /// The destination column.
787 col: OneBased,
788 },
789
790 /// CVT - Cursor Line Tabulation
791 /// CVT causes the active presentation position to be moved to the
792 /// corresponding character position of the line corresponding to the n-th
793 /// following line tabulation stop in the presentation component, where n
794 /// equals the value of Pn.
795 LineTabulation(u32),
796
797 /// DECSTBM - Set top and bottom margins.
798 SetTopAndBottomMargins {
799 /// The top margin line.
800 top: OneBased,
801 /// The bottom margin line.
802 bottom: OneBased,
803 },
804
805 /// [DECSLRM] - Set left and right margins.
806 ///
807 /// [DECSLRM]: https://vt100.net/docs/vt510-rm/DECSLRM.html
808 SetLeftAndRightMargins {
809 /// The left margin column.
810 left: OneBased,
811 /// The right margin column.
812 right: OneBased,
813 },
814
815 /// Set the cursor style.
816 CursorStyle(CursorStyle),
817
818 /// Query the current cursor shape.
819 QueryCursorShape,
820
821 /// Capability query response (kitty multi-cursor protocol).
822 ///
823 /// Contains the set of operations the terminal supports. An empty list
824 /// means the protocol is not supported.
825 CursorShapeQueryResponse(Vec<MultiCursorCapability>),
826
827 /// Set secondary cursor positions for the kitty multi-cursor protocol.
828 SetMultipleCursors {
829 /// The shape used for the secondary cursors.
830 shape: MultiCursorShape,
831
832 /// The one-based `(line, column)` positions of the secondary cursors.
833 positions: Vec<(OneBased, OneBased)>,
834 },
835
836 /// Clear all secondary cursors from the kitty multi-cursor protocol.
837 ClearSecondaryCursors,
838 }
839
840 impl Cursor {
841 /// Returns the home cursor position, line 1 column 1.
842 pub const fn default_position() -> Self {
843 Self::Position {
844 line: OneBased::from_zero_based(0),
845 col: OneBased::from_zero_based(0),
846 }
847 }
848 }
849
850 impl Display for Cursor {
851 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
852 fn write_csi<T: Default + Eq + Display>(
853 value: T,
854 f: &mut fmt::Formatter<'_>,
855 control: &str,
856 ) -> fmt::Result {
857 if value == T::default() {
858 write!(f, "{control}")
859 } else {
860 write!(f, "{value}{control}")
861 }
862 }
863
864 match self {
865 Cursor::BackwardTabulation(n) => write_csi(*n, f, "Z"),
866 Cursor::TabulationClear(n) => write_csi(*n, f, "g"),
867 Cursor::CharacterAbsolute(n) => write_csi(*n, f, "G"),
868 Cursor::CharacterPositionAbsolute(n) => write_csi(*n, f, "``"),
869 Cursor::CharacterPositionBackward(n) => write_csi(*n, f, "j"),
870 Cursor::CharacterPositionForward(n) => write_csi(*n, f, "a"),
871 Cursor::CharacterAndLinePosition { line, col } => write!(f, "{line};{col}f"),
872 Cursor::LinePositionAbsolute(n) => write_csi(*n, f, "d"),
873 Cursor::LinePositionBackward(n) => write_csi(*n, f, "k"),
874 Cursor::LinePositionForward(n) => write_csi(*n, f, "e"),
875 Cursor::ForwardTabulation(n) => write_csi(*n, f, "I"),
876 Cursor::NextLine(n) => write_csi(*n, f, "E"),
877 Cursor::PrecedingLine(n) => write_csi(*n, f, "F"),
878 Cursor::ActivePositionReport { line, col } => write!(f, "{line};{col}R"),
879 Cursor::RequestActivePositionReport => write!(f, "6n"),
880 Cursor::SaveCursor => write!(f, "s"),
881 Cursor::RestoreCursor => write!(f, "u"),
882 Cursor::TabulationControl(n) => write_csi(*n, f, "W"),
883 Cursor::Left(n) => write_csi(*n, f, "D"),
884 Cursor::Down(n) => write_csi(*n, f, "B"),
885 Cursor::Right(n) => write_csi(*n, f, "C"),
886 Cursor::Up(n) => write_csi(*n, f, "A"),
887 Cursor::Position { line, col } => write!(f, "{line};{col}H"),
888 Cursor::LineTabulation(n) => write_csi(*n, f, "Y"),
889 Cursor::SetTopAndBottomMargins { top, bottom } => {
890 if top.get() == 1 && bottom.get() == u16::MAX {
891 write!(f, "r")
892 } else {
893 write!(f, "{top};{bottom}r")
894 }
895 }
896 Cursor::SetLeftAndRightMargins { left, right } => {
897 if left.get() == 1 && right.get() == u16::MAX {
898 write!(f, "s")
899 } else {
900 write!(f, "{left};{right}s")
901 }
902 }
903 Cursor::CursorStyle(style) => write!(f, "{} q", *style as u8),
904 Cursor::QueryCursorShape => write!(f, "> q"),
905 Cursor::CursorShapeQueryResponse(caps) => {
906 write!(f, ">")?;
907 for (i, cap) in caps.iter().enumerate() {
908 if i > 0 {
909 write!(f, ";")?;
910 }
911 write!(f, "{}", *cap as u8)?;
912 }
913 write!(f, " q")
914 }
915 Cursor::SetMultipleCursors { shape, positions } => {
916 write!(
917 f,
918 ">{}",
919 match shape {
920 MultiCursorShape::Style(style) => *style as u8,
921 MultiCursorShape::FollowMainCursor => 29,
922 }
923 )?;
924 for (line, col) in positions {
925 write!(f, ";2:{}:{}", line, col)?;
926 }
927 write!(f, " q")
928 }
929 Cursor::ClearSecondaryCursors => write!(f, ">0;4 q"),
930 }
931 }
932 }
933
934 /// Cursor tabulation control actions for CTC.
935 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
936 pub enum CursorTabulationControl {
937 /// Set a character tab stop at the active position.
938 #[default]
939 SetCharacterTabStopAtActivePosition = 0,
940
941 /// Set a line tab stop at the active line.
942 SetLineTabStopAtActiveLine = 1,
943
944 /// Clear the character tab stop at the active position.
945 ClearCharacterTabStopAtActivePosition = 2,
946
947 /// Clear the line tab stop at the active line.
948 ClearLineTabstopAtActiveLine = 3,
949
950 /// Clear all character tab stops on the active line.
951 ClearAllCharacterTabStopsAtActiveLine = 4,
952
953 /// Clear all character tab stops.
954 ClearAllCharacterTabStops = 5,
955
956 /// Clear all line tab stops.
957 ClearAllLineTabStops = 6,
958 }
959
960 impl Display for CursorTabulationControl {
961 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962 write!(f, "{}", *self as u8)
963 }
964 }
965
966 /// Tab-stop clearing actions for TBC.
967 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
968 pub enum TabulationClear {
969 /// Clear the character tab stop at the active position.
970 #[default]
971 ClearCharacterTabStopAtActivePosition = 0,
972
973 /// Clear the line tab stop at the active line.
974 ClearLineTabStopAtActiveLine = 1,
975
976 /// Clear all character tab stops on the active line.
977 ClearCharacterTabStopsAtActiveLine = 2,
978
979 /// Clear all character tab stops.
980 ClearAllCharacterTabStops = 3,
981
982 /// Clear all line tab stops.
983 ClearAllLineTabStops = 4,
984
985 /// Clear all character and line tab stops.
986 ClearAllTabStops = 5,
987 }
988
989 impl Display for TabulationClear {
990 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
991 write!(f, "{}", *self as u8)
992 }
993 }
994
995 // Edit
996
997 /// Text and display editing CSI commands.
998 ///
999 /// ```
1000 /// use termina::escape::csi::{Csi, Edit, EraseInDisplay, EraseInLine};
1001 ///
1002 /// assert_eq!(
1003 /// Csi::Edit(Edit::EraseInLine(EraseInLine::EraseToEndOfLine)).to_string(),
1004 /// "\x1b[0K",
1005 /// );
1006 /// assert_eq!(
1007 /// Csi::Edit(Edit::EraseInDisplay(EraseInDisplay::EraseDisplay)).to_string(),
1008 /// "\x1b[2J",
1009 /// );
1010 /// ```
1011 #[derive(Debug, Clone, PartialEq, Eq)]
1012 pub enum Edit {
1013 /// DCH - DELETE CHARACTER
1014 /// Deletes Ps characters from the cursor position to the right. The
1015 /// default value of Ps is 1. If the DEVICE COMPONENT SELECT MODE
1016 /// (DCSM) is set to PRESENTATION, DCH causes the contents of the
1017 /// active presentation position and, depending on the setting of the
1018 /// CHARACTER EDITING MODE (HEM), the contents of the n-1 preceding or
1019 /// following character positions to be removed from the presentation
1020 /// component, where n equals the value of Pn. The resulting gap is
1021 /// closed by shifting the contents of the adjacent character positions
1022 /// towards the active presentation position. At the other end of the
1023 /// shifted part, n character positions are put into the erased state.
1024 DeleteCharacter(u32),
1025
1026 /// DL - DELETE LINE
1027 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to PRESENTATION, DL
1028 /// causes the contents of the active line (the line that contains the
1029 /// active presentation position) and, depending on the setting of the
1030 /// LINE EDITING MODE (VEM), the contents of the n-1 preceding or
1031 /// following lines to be removed from the presentation component, where n
1032 /// equals the value of Pn. The resulting gap is closed by shifting the
1033 /// contents of a number of adjacent lines towards the active line. At
1034 /// the other end of the shifted part, n lines are put into the
1035 /// erased state. The active presentation position is moved to the line
1036 /// home position in the active line. The line home position is
1037 /// established by the parameter value of SET LINE HOME (SLH). If the
1038 /// TABULATION STOP MODE (TSM) is set to SINGLE, character tabulation stops
1039 /// are cleared in the lines that are put into the erased state. The
1040 /// extent of the shifted part is established by SELECT EDITING EXTENT
1041 /// (SEE). Any occurrences of the start or end of a selected area, the
1042 /// start or end of a qualified area, or a tabulation stop in the shifted
1043 /// part, are also shifted.
1044 DeleteLine(u32),
1045
1046 /// ECH - ERASE CHARACTER
1047 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to PRESENTATION, ECH
1048 /// causes the active presentation position and the n-1 following
1049 /// character positions in the presentation component to be put into
1050 /// the erased state, where n equals the value of Pn.
1051 EraseCharacter(u32),
1052
1053 /// EL - ERASE IN LINE
1054 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to PRESENTATION, EL
1055 /// causes some or all character positions of the active line (the line
1056 /// which contains the active presentation position in the presentation
1057 /// component) to be put into the erased state, depending on the
1058 /// parameter values
1059 EraseInLine(EraseInLine),
1060
1061 /// ICH - INSERT CHARACTER
1062 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to PRESENTATION, ICH
1063 /// is used to prepare the insertion of n characters, by putting into the
1064 /// erased state the active presentation position and, depending on the
1065 /// setting of the CHARACTER EDITING MODE (HEM), the n-1 preceding or
1066 /// following character positions in the presentation component, where n
1067 /// equals the value of Pn. The previous contents of the active
1068 /// presentation position and an adjacent string of character positions are
1069 /// shifted away from the active presentation position. The contents of n
1070 /// character positions at the other end of the shifted part are removed.
1071 /// The active presentation position is moved to the line home position in
1072 /// the active line. The line home position is established by the parameter
1073 /// value of SET LINE HOME (SLH).
1074 InsertCharacter(u32),
1075
1076 /// IL - INSERT LINE
1077 /// If the DEVICE COMPONENT SELECT MODE (DCSM) is set to PRESENTATION, IL
1078 /// is used to prepare the insertion of n lines, by putting into the
1079 /// erased state in the presentation component the active line (the
1080 /// line that contains the active presentation position) and, depending on
1081 /// the setting of the LINE EDITING MODE (VEM), the n-1 preceding or
1082 /// following lines, where n equals the value of Pn. The previous
1083 /// contents of the active line and of adjacent lines are shifted away
1084 /// from the active line. The contents of n lines at the other end of the
1085 /// shifted part are removed. The active presentation position is moved
1086 /// to the line home position in the active line. The line home
1087 /// position is established by the parameter value of SET LINE
1088 /// HOME (SLH).
1089 InsertLine(u32),
1090
1091 /// SD - SCROLL DOWN
1092 /// SD causes the data in the presentation component to be moved by n line
1093 /// positions if the line orientation is horizontal, or by n character
1094 /// positions if the line orientation is vertical, such that the data
1095 /// appear to move down; where n equals the value of Pn. The active
1096 /// presentation position is not affected by this control function.
1097 ///
1098 /// Also known as Pan Up in DEC; see [SD].
1099 ///
1100 /// [SD]: https://vt100.net/docs/vt510-rm/SD.html
1101 ScrollDown(u32),
1102
1103 /// SU - SCROLL UP
1104 /// SU causes the data in the presentation component to be moved by n line
1105 /// positions if the line orientation is horizontal, or by n character
1106 /// positions if the line orientation is vertical, such that the data
1107 /// appear to move up; where n equals the value of Pn. The active
1108 /// presentation position is not affected by this control function.
1109 ScrollUp(u32),
1110
1111 /// ED - ERASE IN PAGE (XTerm calls this Erase in Display)
1112 EraseInDisplay(EraseInDisplay),
1113
1114 /// REP - Repeat the preceding character n times
1115 Repeat(u32),
1116 }
1117
1118 impl Display for Edit {
1119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1120 fn write_csi(param: u32, f: &mut fmt::Formatter<'_>, control: &str) -> fmt::Result {
1121 if param == 1 {
1122 write!(f, "{control}")
1123 } else {
1124 write!(f, "{param}{control}")
1125 }
1126 }
1127
1128 match self {
1129 Self::DeleteCharacter(n) => write_csi(*n, f, "P"),
1130 Self::DeleteLine(n) => write_csi(*n, f, "M"),
1131 Self::EraseCharacter(n) => write_csi(*n, f, "X"),
1132 Self::EraseInLine(n) => write_csi(*n as u32, f, "K"),
1133 Self::InsertCharacter(n) => write_csi(*n, f, "@"),
1134 Self::InsertLine(n) => write_csi(*n, f, "L"),
1135 Self::ScrollDown(n) => write_csi(*n, f, "T"),
1136 Self::ScrollUp(n) => write_csi(*n, f, "S"),
1137 Self::EraseInDisplay(n) => write_csi(*n as u32, f, "J"),
1138 Self::Repeat(n) => write_csi(*n, f, "b"),
1139 }
1140 }
1141 }
1142
1143 /// Erase-in-line modes for EL.
1144 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1145 pub enum EraseInLine {
1146 /// Erase from the active position to the end of the line.
1147 #[default]
1148 EraseToEndOfLine = 0,
1149
1150 /// Erase from the start of the line through the active position.
1151 EraseToStartOfLine = 1,
1152
1153 /// Erase the entire active line.
1154 EraseLine = 2,
1155 }
1156
1157 /// Erase-in-display modes for ED.
1158 #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1159 pub enum EraseInDisplay {
1160 /// the active presentation position and the character positions up to the
1161 /// end of the page are put into the erased state
1162 #[default]
1163 EraseToEndOfDisplay = 0,
1164 /// the character positions from the beginning of the page up to and
1165 /// including the active presentation position are put into the erased
1166 /// state
1167 EraseToStartOfDisplay = 1,
1168 /// all character positions of the page are put into the erased state
1169 EraseDisplay = 2,
1170 /// Clears the scrollback. This is an Xterm extension to ECMA-48.
1171 EraseScrollback = 3,
1172 }
1173
1174 // Mode
1175
1176 /// Terminal mode CSI commands.
1177 ///
1178 /// This enum covers Digital Equipment Corporation (DEC) private modes
1179 /// (`CSI ? ... h/l/s/r/$p`), standard modes, xterm key modifier resources, and terminal theme
1180 /// query/report extensions.
1181 ///
1182 /// ```
1183 /// use termina::escape::csi::{Csi, DecPrivateMode, DecPrivateModeCode, Mode};
1184 ///
1185 /// let bracketed_paste = DecPrivateMode::Code(DecPrivateModeCode::BracketedPaste);
1186 /// assert_eq!(
1187 /// Csi::Mode(Mode::SetDecPrivateMode(bracketed_paste)).to_string(),
1188 /// "\x1b[?2004h",
1189 /// );
1190 /// assert_eq!(
1191 /// Csi::Mode(Mode::ResetDecPrivateMode(bracketed_paste)).to_string(),
1192 /// "\x1b[?2004l",
1193 /// );
1194 /// ```
1195 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1196 pub enum Mode {
1197 /// Set a DEC private mode.
1198 SetDecPrivateMode(DecPrivateMode),
1199
1200 /// Reset a DEC private mode.
1201 ResetDecPrivateMode(DecPrivateMode),
1202
1203 /// Save a DEC private mode.
1204 SaveDecPrivateMode(DecPrivateMode),
1205
1206 /// Restore a DEC private mode.
1207 RestoreDecPrivateMode(DecPrivateMode),
1208
1209 /// Query a DEC private mode setting.
1210 QueryDecPrivateMode(DecPrivateMode),
1211
1212 /// Report a DEC private mode setting.
1213 ReportDecPrivateMode {
1214 /// The DEC private mode being reported.
1215 mode: DecPrivateMode,
1216
1217 /// The current setting state for the mode.
1218 setting: DecModeSetting,
1219 },
1220
1221 /// Set a standard terminal mode.
1222 SetMode(TerminalMode),
1223
1224 /// Reset a standard terminal mode.
1225 ResetMode(TerminalMode),
1226
1227 /// Query a standard terminal mode.
1228 QueryMode(TerminalMode),
1229
1230 /// Set or query an xterm key modifier resource.
1231 XtermKeyMode {
1232 /// The xterm key modifier resource.
1233 resource: XtermKeyModifierResource,
1234
1235 /// The resource value, or `None` to query it.
1236 value: Option<i64>,
1237 },
1238
1239 /// Query the current terminal theme.
1240 QueryTheme,
1241
1242 /// Report the current terminal theme.
1243 ReportTheme(ThemeMode),
1244 }
1245
1246 impl Display for Mode {
1247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1248 match self {
1249 Self::SetDecPrivateMode(mode) => write!(f, "?{mode}h"),
1250 Self::ResetDecPrivateMode(mode) => write!(f, "?{mode}l"),
1251 Self::SaveDecPrivateMode(mode) => write!(f, "?{mode}s"),
1252 Self::RestoreDecPrivateMode(mode) => write!(f, "?{mode}r"),
1253 Self::QueryDecPrivateMode(mode) => write!(f, "?{mode}$p"),
1254 Self::ReportDecPrivateMode { mode, setting } => {
1255 write!(f, "?{mode};{}$y", *setting as u8)
1256 }
1257 Self::SetMode(mode) => write!(f, "{mode}h"),
1258 Self::ResetMode(mode) => write!(f, "{mode}l"),
1259 Self::QueryMode(mode) => write!(f, "?{mode}$p"),
1260 Self::XtermKeyMode { resource, value } => {
1261 write!(f, ">{}", *resource as u8)?;
1262 if let Some(value) = value {
1263 write!(f, ";{}", value)?;
1264 } else {
1265 write!(f, ";")?;
1266 }
1267 write!(f, "m")
1268 }
1269 Self::QueryTheme => write!(f, "?996n"),
1270 Self::ReportTheme(mode) => write!(f, "?997;{}n", *mode as u8),
1271 }
1272 }
1273 }
1274
1275 /// A Digital Equipment Corporation private mode value.
1276 ///
1277 /// DEC private modes are terminal-specific mode numbers encoded with `CSI ? ...` sequences. Many
1278 /// modern terminal emulators still use this namespace for xterm-compatible extensions.
1279 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1280 pub enum DecPrivateMode {
1281 /// A known DEC private mode code.
1282 Code(DecPrivateModeCode),
1283
1284 /// A DEC private mode code not modeled by [`DecPrivateModeCode`].
1285 Unspecified(u16),
1286 }
1287
1288 impl Display for DecPrivateMode {
1289 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1290 let code = match *self {
1291 Self::Code(code) => code as u16,
1292 Self::Unspecified(code) => code,
1293 };
1294 write!(f, "{code}")
1295 }
1296 }
1297
1298 /// Known Digital Equipment Corporation private mode numbers.
1299 ///
1300 /// The DEC private-mode namespace started with DEC terminals and now also carries common
1301 /// xterm-compatible extensions such as mouse tracking, alternate screens, and bracketed paste.
1302 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1303 pub enum DecPrivateModeCode {
1304 /// Mode 1: [DECCKM] - Application Cursor Keys.
1305 ///
1306 /// This mode is only effective when the terminal is in keypad application mode (see DECKPAM)
1307 /// and the ANSI/VT52 mode (DECANM) is set (see DECANM). Under these conditions, if the cursor
1308 /// key mode is reset, the four cursor function keys will send ANSI cursor control commands. If
1309 /// cursor key mode is set, the four cursor function keys will send application functions.
1310 ///
1311 /// [DECCKM]: https://vt100.net/docs/vt510-rm/DECCKM.html
1312 ApplicationCursorKeys = 1,
1313
1314 /// Mode 2: [DECANM] - behave like a VT52.
1315 ///
1316 /// This is a historical compatibility mode. Modern terminal applications usually leave the
1317 /// terminal in ANSI mode and should not need to enable VT52 behavior.
1318 ///
1319 /// [DECANM]: https://vt100.net/docs/vt510-rm/DECANM.html
1320 DecAnsiMode = 2,
1321
1322 /// Mode 3: [DECCOLM] - Select 132 columns.
1323 ///
1324 /// Setting this mode asks the terminal to switch from 80 columns to 132 columns. Many modern
1325 /// terminals ignore or restrict this behavior.
1326 ///
1327 /// [DECCOLM]: https://vt100.net/docs/vt510-rm/DECCOLM.html
1328 Select132Columns = 3,
1329
1330 /// Mode 4: [DECSCLM] - Smooth scroll.
1331 ///
1332 /// This mode controls whether scrolling should be smooth or jump-scroll style on DEC
1333 /// terminals. Modern emulators commonly ignore it.
1334 ///
1335 /// [DECSCLM]: https://vt100.net/docs/vt510-rm/DECSCLM.html
1336 SmoothScroll = 4,
1337
1338 /// Mode 5: [DECSCNM] - Reverse video.
1339 ///
1340 /// Setting this mode swaps the screen's foreground and background presentation.
1341 ///
1342 /// [DECSCNM]: https://vt100.net/docs/vt510-rm/DECSCNM.html
1343 ReverseVideo = 5,
1344
1345 /// Mode 6: [DECOM] - Origin Mode.
1346 ///
1347 /// When enabled, OriginMode constrains cursor to the scroll region and makes its position
1348 /// relative to that region.
1349 ///
1350 /// [DECOM]: https://vt100.net/docs/vt510-rm/DECOM.html
1351 OriginMode = 6,
1352
1353 /// Mode 7: [DECAWM] - Auto Wrap.
1354 ///
1355 /// When enabled, wrap to next line. Otherwise replace the last character.
1356 ///
1357 /// [DECAWM]: https://vt100.net/docs/vt510-rm/DECAWM.html
1358 AutoWrap = 7,
1359
1360 /// Mode 8: [DECARM] - Auto Repeat.
1361 ///
1362 /// This controls whether held-down keys repeatedly generate input.
1363 ///
1364 /// [DECARM]: https://vt100.net/docs/vt510-rm/DECARM.html
1365 AutoRepeat = 8,
1366
1367 /// Mode 12: start blinking the cursor.
1368 ///
1369 /// This is an xterm cursor-control extension, not a DEC private mode from the VT manuals.
1370 StartBlinkingCursor = 12,
1371
1372 /// Mode 25: show the cursor.
1373 ///
1374 /// Applications commonly set this mode while running and reset it to hide the cursor during
1375 /// full-screen drawing.
1376 ShowCursor = 25,
1377
1378 /// Mode 45: reverse-wrap from the left edge to the previous line.
1379 ///
1380 /// This xterm extension controls whether cursor-left from column 1 wraps to the previous line.
1381 ReverseWraparound = 45,
1382
1383 /// Mode 69: [DECLRMM] - Left Right Margin Mode.
1384 ///
1385 /// [DECLRMM]: https://vt100.net/docs/vt510-rm/DECLRMM.html
1386 LeftRightMarginMode = 69,
1387
1388 /// Mode 80: DECSDM - Sixel Display Mode.
1389 ///
1390 /// See the sixel mode discussion in [EK-VT38T-UG-001].
1391 ///
1392 /// [EK-VT38T-UG-001]: https://vt100.net/dec/ek-vt38t-ug-001.pdf#page=132
1393 SixelDisplayMode = 80,
1394
1395 /// Mode 1000: enable mouse button press/release reporting.
1396 ///
1397 /// xterm mouse tracking defines the report encoding for this mode. Termina parses compatible
1398 /// reports as [`crate::Event::Mouse`].
1399 ///
1400 /// [xterm mouse tracking]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1401 MouseTracking = 1000,
1402
1403 /// Mode 1001: enable highlight mouse tracking.
1404 ///
1405 /// Warning: this requires a cooperative and timely application response; otherwise the
1406 /// terminal can hang. xterm mouse tracking defines the report encoding for this mode.
1407 /// Termina parses compatible reports as [`crate::Event::Mouse`].
1408 ///
1409 /// [xterm mouse tracking]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1410 HighlightMouseTracking = 1001,
1411
1412 /// Mode 1002: enable mouse button press/release and drag reporting.
1413 ///
1414 /// xterm mouse tracking defines the report encoding for this mode. Termina parses compatible
1415 /// reports as [`crate::Event::Mouse`].
1416 ///
1417 /// [xterm mouse tracking]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1418 ButtonEventMouse = 1002,
1419
1420 /// Mode 1003: enable mouse motion, button press/release, and drag reporting.
1421 ///
1422 /// xterm mouse tracking defines the report encoding for this mode. Termina parses compatible
1423 /// reports as [`crate::Event::Mouse`].
1424 ///
1425 /// [xterm mouse tracking]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1426 AnyEventMouse = 1003,
1427
1428 /// Mode 1004: enable FocusIn/FocusOut events.
1429 ///
1430 /// When enabled, compatible terminals send focus events as CSI `I` and CSI `O`. Termina parses
1431 /// those reports as [`crate::Event::FocusIn`] and [`crate::Event::FocusOut`].
1432 FocusTracking = 1004,
1433
1434 /// Mode 1005: use the UTF-8 mouse coordinate encoding.
1435 ///
1436 /// This is an older extended-coordinate encoding. New applications generally prefer
1437 /// [`Self::SGRMouse`] when supported.
1438 Utf8Mouse = 1005,
1439
1440 /// Mode 1006: use SGR extended coordinates in mouse reporting.
1441 ///
1442 /// This does not enable mouse reporting itself; it only controls how reports are encoded.
1443 /// xterm extended coordinates define the `CSI < ... M/m` report shape parsed as
1444 /// [`MouseReport::Sgr1006`].
1445 ///
1446 /// [xterm extended coordinates]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1447 SGRMouse = 1006,
1448
1449 /// Mode 1015: use RXVT mouse coordinate encoding.
1450 ///
1451 /// xterm extended coordinates document this as the older urxvt-style coordinate extension.
1452 ///
1453 /// [xterm extended coordinates]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html
1454 RXVTMouse = 1015,
1455
1456 /// Mode 1016: use pixels rather than text cells in mouse reporting.
1457 ///
1458 /// This does not enable mouse reporting itself; it only controls how reports are encoded.
1459 /// xterm SGR pixels define the pixel-coordinate report shape parsed as
1460 /// [`MouseReport::Sgr1016`].
1461 ///
1462 /// [xterm SGR pixels]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-SGR-Pixels
1463 SGRPixelsMouse = 1016,
1464
1465 /// Mode 1036: make xterm send Escape before Meta-modified keys.
1466 ///
1467 /// This changes keyboard encoding so Meta-modified input is delivered as an Escape-prefixed
1468 /// sequence.
1469 XTermMetaSendsEscape = 1036,
1470
1471 /// Mode 1039: make xterm send Escape before Alt-modified keys.
1472 ///
1473 /// This changes keyboard encoding so Alt-modified input is delivered as an Escape-prefixed
1474 /// sequence.
1475 XTermAltSendsEscape = 1039,
1476
1477 /// Mode 1048: save cursor as in DECSC.
1478 ///
1479 /// Full-screen applications often combine this with alternate-screen modes so they can restore
1480 /// the user's cursor position on exit.
1481 SaveCursor = 1048,
1482
1483 /// Mode 1049: clear and switch to the alternate screen.
1484 ///
1485 /// This is the common xterm private mode for full-screen applications. It switches away from
1486 /// the scrollback-backed main screen and clears the alternate screen.
1487 ClearAndEnableAlternateScreen = 1049,
1488
1489 /// Mode 47: switch to the alternate screen.
1490 ///
1491 /// This is an older alternate-screen mode. New applications usually use mode 1049.
1492 EnableAlternateScreen = 47,
1493
1494 /// Mode 1047: switch to the alternate screen using xterm's optional alternate-screen mode.
1495 ///
1496 /// Unlike mode 1049, this does not imply saving/restoring the cursor.
1497 OptEnableAlternateScreen = 1047,
1498
1499 /// Mode 2004: enable bracketed paste mode.
1500 ///
1501 /// When enabled, pasted text is wrapped in explicit start/end markers so applications can
1502 /// distinguish paste from typed input. Termina parses the wrapped payload as
1503 /// [`crate::Event::Paste`]. xterm documents this mode as [bracketed paste mode].
1504 ///
1505 /// [bracketed paste mode]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Bracketed-Paste-Mode
1506 BracketedPaste = 2004,
1507
1508 /// Mode 2027: grapheme clustering mode from [Contour Unicode core].
1509 ///
1510 /// [Contour Unicode core]: https://github.com/contour-terminal/terminal-unicode-core/
1511 GraphemeClustering = 2027,
1512
1513 /// Mode 2031: theme notification mode from [Contour color-palette notifications].
1514 ///
1515 /// [Contour color-palette notifications]: https://github.com/contour-terminal/contour/
1516 Theme = 2031,
1517
1518 /// Mode 1070: use private color registers for each sixel or ReGIS graphic.
1519 ///
1520 /// This keeps image color registers local to a graphic instead of sharing them globally across
1521 /// the terminal session.
1522 UsePrivateColorRegistersForEachGraphic = 1070,
1523
1524 /// Mode 2026: [Synchronized output proposal] mode.
1525 ///
1526 /// [Synchronized output proposal]: https://gist.github.com/christianparpart/
1527 SynchronizedOutput = 2026,
1528
1529 /// Mode 7727: enable MinTTY application Escape key mode.
1530 ///
1531 /// This MinTTY extension changes how the Escape key is encoded in application contexts.
1532 MinTTYApplicationEscapeKeyMode = 7727,
1533
1534 /// Mode 8452: adjust cursor positioning after emitting sixel.
1535 ///
1536 /// This xterm mode controls whether sixel output advances the cursor as if the graphic
1537 /// occupied cells.
1538 SixelScrollsRight = 8452,
1539
1540 /// Mode 9001: Windows Terminal win32-input-mode from [Microsoft terminal keyboard handling].
1541 ///
1542 /// [Microsoft terminal keyboard handling]: https://github.com/microsoft/terminal/
1543 Win32InputMode = 9001,
1544 }
1545
1546 /// A standard terminal mode value.
1547 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1548 pub enum TerminalMode {
1549 /// A known standard terminal mode code.
1550 Code(TerminalModeCode),
1551
1552 /// A standard terminal mode code not modeled by [`TerminalModeCode`].
1553 Unspecified(u16),
1554 }
1555
1556 impl Display for TerminalMode {
1557 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1558 let code = match *self {
1559 Self::Code(code) => code as u16,
1560 Self::Unspecified(code) => code,
1561 };
1562 write!(f, "{code}")
1563 }
1564 }
1565
1566 /// Known standard terminal mode numbers.
1567 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1568 pub enum TerminalModeCode {
1569 /// Mode 2: [KAM] - Keyboard Action Mode.
1570 ///
1571 /// When set, keyboard input is disabled. Applications usually avoid this mode unless they are
1572 /// intentionally locking local keyboard entry.
1573 ///
1574 /// [KAM]: https://vt100.net/docs/vt510-rm/KAM.html
1575 KeyboardAction = 2,
1576
1577 /// Mode 4: [IRM] - Insert Replace Mode.
1578 ///
1579 /// When set, printable characters insert at the cursor and shift existing content right.
1580 /// When reset, printable characters replace existing cells.
1581 ///
1582 /// [IRM]: https://vt100.net/docs/vt510-rm/IRM.html
1583 Insert = 4,
1584
1585 /// Mode 8: bidirectional support mode.
1586 ///
1587 /// The terminal-wg bidi recommendation uses this mode to enable bidirectional text support in
1588 /// terminals that implement the proposal.
1589 ///
1590 /// [Terminal WG bidi recommendation]: https://terminal-wg.pages.freedesktop.org/bidi/
1591 BiDirectionalSupportMode = 8,
1592
1593 /// Mode 12: [SRM] - Send Receive Mode.
1594 ///
1595 /// ECMA-48 defines this as local echo control. Microsoft terminal implementations also use
1596 /// mode 12 for cursor blinking, so callers should be aware of that compatibility difference.
1597 ///
1598 /// [SRM]: https://vt100.net/docs/vt510-rm/SRM.html
1599 SendReceive = 12,
1600
1601 /// Mode 20: [LNM] - Line Feed/New Line Mode.
1602 ///
1603 /// When set, line feed also performs carriage return. When reset, line feed only moves to the
1604 /// next line.
1605 ///
1606 /// [LNM]: https://vt100.net/docs/vt510-rm/LNM.html
1607 AutomaticNewline = 20,
1608
1609 /// Mode 25: Microsoft terminal cursor visibility.
1610 ///
1611 /// This mirrors the DEC private cursor-visibility mode in some Microsoft terminal contexts.
1612 ShowCursor = 25,
1613 }
1614
1615 /// xterm key modifier resources addressed by `CSI > ... m`.
1616 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1617 pub enum XtermKeyModifierResource {
1618 /// Resource 0: xterm keyboard modifier keys.
1619 ///
1620 /// This resource controls xterm's general modified-key behavior.
1621 Keyboard = 0,
1622
1623 /// Resource 1: xterm cursor-key modifier keys.
1624 ///
1625 /// This resource controls modified arrow-key and navigation-key encodings.
1626 CursorKeys = 1,
1627
1628 /// Resource 2: xterm function-key modifier keys.
1629 ///
1630 /// This resource controls modified function-key encodings.
1631 FunctionKeys = 2,
1632
1633 /// Resource 4: xterm other-key modifier keys.
1634 ///
1635 /// This resource controls modified-key encodings for keys outside the cursor/function groups.
1636 OtherKeys = 4,
1637 }
1638
1639 /// Reported state for a DEC private mode query.
1640 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1641 pub enum DecModeSetting {
1642 /// Report value 0: the terminal does not recognize the requested mode.
1643 NotRecognized = 0,
1644
1645 /// Report value 1: the mode is set.
1646 Set = 1,
1647
1648 /// Report value 2: the mode is reset.
1649 Reset = 2,
1650
1651 /// Report value 3: the mode is permanently set and cannot be changed.
1652 PermanentlySet = 3,
1653
1654 /// Report value 4: the mode is permanently reset and cannot be changed.
1655 PermanentlyReset = 4,
1656 }
1657
1658 /// Terminal theme values reported by the Contour theme extension.
1659 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1660 pub enum ThemeMode {
1661 /// Report value 1: the terminal is using a dark theme.
1662 Dark = 1,
1663
1664 /// Report value 2: the terminal is using a light theme.
1665 Light = 2,
1666 }
1667
1668 // Mouse
1669
1670 /// Mouse reports emitted by terminal mouse tracking modes.
1671 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1672 pub enum MouseReport {
1673 /// An SGR 1006 mouse report using text-cell coordinates.
1674 ///
1675 /// This is the report format enabled by [`DecPrivateModeCode::SGRMouse`]. Coordinates are
1676 /// one-based terminal cell positions.
1677 Sgr1006 {
1678 /// The one-based cell column.
1679 x: u16,
1680
1681 /// The one-based cell row.
1682 y: u16,
1683
1684 /// The reported mouse button action.
1685 button: MouseButton,
1686
1687 /// The modifiers active during the mouse event.
1688 modifiers: Modifiers,
1689 },
1690
1691 /// An SGR 1016 mouse report using pixel coordinates.
1692 ///
1693 /// This is the report format enabled by [`DecPrivateModeCode::SGRPixelsMouse`]. Coordinates
1694 /// are pixel positions instead of terminal cell positions.
1695 Sgr1016 {
1696 /// The x coordinate in pixels.
1697 x_pixels: u16,
1698
1699 /// The y coordinate in pixels.
1700 y_pixels: u16,
1701
1702 /// The reported mouse button action.
1703 button: MouseButton,
1704
1705 /// The modifiers active during the mouse event.
1706 modifiers: Modifiers,
1707 },
1708 }
1709
1710 impl Display for MouseReport {
1711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1712 match self {
1713 MouseReport::Sgr1006 {
1714 x,
1715 y,
1716 button,
1717 modifiers,
1718 } => {
1719 let mut b = 0;
1720 // TODO: check this.
1721 if (*modifiers & Modifiers::SHIFT) != Modifiers::NONE {
1722 b |= 4;
1723 }
1724 if (*modifiers & Modifiers::ALT) != Modifiers::NONE {
1725 b |= 8;
1726 }
1727 if (*modifiers & Modifiers::CONTROL) != Modifiers::NONE {
1728 b |= 16;
1729 }
1730 b |= match button {
1731 MouseButton::Button1Press | MouseButton::Button1Release => 0,
1732 MouseButton::Button2Press | MouseButton::Button2Release => 1,
1733 MouseButton::Button3Press | MouseButton::Button3Release => 2,
1734 MouseButton::Button4Press | MouseButton::Button4Release => 64,
1735 MouseButton::Button5Press | MouseButton::Button5Release => 65,
1736 MouseButton::Button6Press | MouseButton::Button6Release => 66,
1737 MouseButton::Button7Press | MouseButton::Button7Release => 67,
1738 MouseButton::Button1Drag => 32,
1739 MouseButton::Button2Drag => 33,
1740 MouseButton::Button3Drag => 34,
1741 MouseButton::None => 35,
1742 };
1743 let trailer = match button {
1744 MouseButton::Button1Press
1745 | MouseButton::Button2Press
1746 | MouseButton::Button3Press
1747 | MouseButton::Button4Press
1748 | MouseButton::Button5Press
1749 | MouseButton::Button1Drag
1750 | MouseButton::Button2Drag
1751 | MouseButton::Button3Drag
1752 | MouseButton::None => 'M',
1753 _ => 'm',
1754 };
1755 write!(f, "<{b};{x};{y}{trailer}")
1756 }
1757 MouseReport::Sgr1016 {
1758 x_pixels,
1759 y_pixels,
1760 button,
1761 modifiers,
1762 } => {
1763 let mut b = 0;
1764 // TODO: check this.
1765 if (*modifiers & Modifiers::SHIFT) != Modifiers::NONE {
1766 b |= 4;
1767 }
1768 if (*modifiers & Modifiers::ALT) != Modifiers::NONE {
1769 b |= 8;
1770 }
1771 if (*modifiers & Modifiers::CONTROL) != Modifiers::NONE {
1772 b |= 16;
1773 }
1774 b |= match button {
1775 MouseButton::Button1Press | MouseButton::Button1Release => 0,
1776 MouseButton::Button2Press | MouseButton::Button2Release => 1,
1777 MouseButton::Button3Press | MouseButton::Button3Release => 2,
1778 MouseButton::Button4Press | MouseButton::Button4Release => 64,
1779 MouseButton::Button5Press | MouseButton::Button5Release => 65,
1780 MouseButton::Button6Press | MouseButton::Button6Release => 66,
1781 MouseButton::Button7Press | MouseButton::Button7Release => 67,
1782 MouseButton::Button1Drag => 32,
1783 MouseButton::Button2Drag => 33,
1784 MouseButton::Button3Drag => 34,
1785 MouseButton::None => 35,
1786 };
1787 let trailer = match button {
1788 MouseButton::Button1Press
1789 | MouseButton::Button2Press
1790 | MouseButton::Button3Press
1791 | MouseButton::Button4Press
1792 | MouseButton::Button5Press
1793 | MouseButton::Button1Drag
1794 | MouseButton::Button2Drag
1795 | MouseButton::Button3Drag
1796 | MouseButton::None => 'M',
1797 _ => 'm',
1798 };
1799 write!(f, "<{b};{x_pixels};{y_pixels}{trailer}")
1800 }
1801 }
1802 }
1803 }
1804
1805 /// Mouse button actions encoded in SGR mouse reports.
1806 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1807 pub enum MouseButton {
1808 /// Button 1 was pressed; encoded with button value 0 and trailer `M`.
1809 Button1Press,
1810
1811 /// Button 2 was pressed; encoded with button value 1 and trailer `M`.
1812 Button2Press,
1813
1814 /// Button 3 was pressed; encoded with button value 2 and trailer `M`.
1815 Button3Press,
1816
1817 /// Button 4 was pressed; encoded with button value 64 and trailer `M`.
1818 Button4Press,
1819
1820 /// Button 5 was pressed; encoded with button value 65 and trailer `M`.
1821 Button5Press,
1822
1823 /// Button 6 was pressed; encoded with button value 66.
1824 Button6Press,
1825
1826 /// Button 7 was pressed; encoded with button value 67.
1827 Button7Press,
1828
1829 /// Button 1 was released; encoded with button value 0 and trailer `m`.
1830 Button1Release,
1831
1832 /// Button 2 was released; encoded with button value 1 and trailer `m`.
1833 Button2Release,
1834
1835 /// Button 3 was released; encoded with button value 2 and trailer `m`.
1836 Button3Release,
1837
1838 /// Button 4 was released; encoded with button value 64 and trailer `m`.
1839 Button4Release,
1840
1841 /// Button 5 was released; encoded with button value 65 and trailer `m`.
1842 Button5Release,
1843
1844 /// Button 6 was released; encoded with button value 66.
1845 Button6Release,
1846
1847 /// Button 7 was released; encoded with button value 67.
1848 Button7Release,
1849
1850 /// Button 1 was dragged; encoded with button value 32 and trailer `M`.
1851 Button1Drag,
1852
1853 /// Button 2 was dragged; encoded with button value 33 and trailer `M`.
1854 Button2Drag,
1855
1856 /// Button 3 was dragged; encoded with button value 34 and trailer `M`.
1857 Button3Drag,
1858
1859 /// No mouse button was involved; encoded with button value 35 and trailer `M`.
1860 None,
1861 }
1862
1863 // --- Kitty keyboard protocol ---
1864 //
1865 // <https://sw.kovidgoyal.net/kitty/keyboard-protocol/>.
1866
1867 bitflags::bitflags! {
1868 /// Feature flags for the Kitty keyboard protocol.
1869 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1870 pub struct KittyKeyboardFlags: u8 {
1871 /// No keyboard enhancement flags.
1872 const NONE = 0;
1873
1874 /// Disambiguate escape codes for keys that otherwise share encodings.
1875 const DISAMBIGUATE_ESCAPE_CODES = 1;
1876
1877 /// Report press, release, and repeat event types.
1878 const REPORT_EVENT_TYPES = 2;
1879
1880 /// Report alternate key values.
1881 const REPORT_ALTERNATE_KEYS = 4;
1882
1883 /// Report all keys as escape codes.
1884 const REPORT_ALL_KEYS_AS_ESCAPE_CODES = 8;
1885
1886 /// Report associated text for key events.
1887 const REPORT_ASSOCIATED_TEXT = 16;
1888 }
1889 }
1890
1891 impl Display for KittyKeyboardFlags {
1892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1893 write!(f, "{}", self.bits())
1894 }
1895 }
1896
1897 /// CSI sequences for interacting with the [Kitty Keyboard Protocol].
1898 ///
1899 /// [Kitty Keyboard Protocol]: https://sw.kovidgoyal.net/kitty/keyboard-protocol/
1900 ///
1901 /// Note that the Kitty Keyboard Protocol requires terminals to maintain different stacks for the
1902 /// main and alternate screens. This means that applications which use alternate screens do not
1903 /// necessarily need to pop flags (via [`Self::PopFlags`]) when exiting. By entering the main screen
1904 /// the flags must be automatically reset by the terminal. Any flags which were pushed, however,
1905 /// will remain active in the alternate screen, even if the alternate screen is entered by a
1906 /// different application. Pop flags during shutdown when the application pushed flags itself.
1907 ///
1908 /// ```
1909 /// use termina::escape::csi::{
1910 /// Csi, Keyboard, KittyKeyboardFlags, SetKeyboardFlagsMode,
1911 /// };
1912 ///
1913 /// let command = Keyboard::SetFlags {
1914 /// flags: KittyKeyboardFlags::REPORT_EVENT_TYPES,
1915 /// mode: SetKeyboardFlagsMode::SetSpecified,
1916 /// };
1917 /// assert_eq!(Csi::Keyboard(command).to_string(), "\x1b[=2;2u");
1918 /// ```
1919 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1920 pub enum Keyboard {
1921 /// Query the current values of the flags.
1922 QueryFlags,
1923
1924 /// A report from the terminal declaring which flags are currently set.
1925 ReportFlags(KittyKeyboardFlags),
1926
1927 /// Pushes the given flags onto the terminal's stack.
1928 PushFlags(KittyKeyboardFlags),
1929
1930 /// Pops the given number of stack entries from the terminal's stack.
1931 PopFlags(u8),
1932
1933 /// Requests keyboard enhancement with the given flags according to the mode.
1934 ///
1935 /// Also see [SetKeyboardFlagsMode].
1936 SetFlags {
1937 /// The flags to assign, set, or clear.
1938 flags: KittyKeyboardFlags,
1939 /// How the terminal should apply `flags`.
1940 mode: SetKeyboardFlagsMode,
1941 },
1942 }
1943
1944 impl Display for Keyboard {
1945 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1946 match self {
1947 Self::QueryFlags => write!(f, "?u"),
1948 // NOTE: this is sent by the terminal, not meant to be sent by the application.
1949 Self::ReportFlags(flags) => write!(f, "?{flags}u"),
1950 Self::PushFlags(flags) => write!(f, ">{flags}u"),
1951 Self::PopFlags(number) => write!(f, "<{number}u"),
1952 Self::SetFlags { flags, mode } => write!(f, "={flags};{mode}u"),
1953 }
1954 }
1955 }
1956
1957 /// Controls how the flags passed in [Keyboard::SetFlags] are interpreted by the terminal.
1958 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1959 pub enum SetKeyboardFlagsMode {
1960 /// Request any of the given flags and reset any flags which are not given.
1961 AssignAll = 1,
1962
1963 /// Request the given flags and ignore any flags which are not given.
1964 SetSpecified = 2,
1965
1966 /// Clear the given flags and ignore any flags which are not given.
1967 ClearSpecified = 3,
1968 }
1969
1970 impl Display for SetKeyboardFlagsMode {
1971 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1972 write!(f, "{}", *self as u8)
1973 }
1974 }
1975
1976 /// Device and status CSI commands.
1977 ///
1978 /// ```
1979 /// use termina::escape::csi::{Csi, Device};
1980 ///
1981 /// assert_eq!(Csi::Device(Device::StatusReport).to_string(), "\x1b[5n");
1982 /// assert_eq!(
1983 /// Csi::Device(Device::RequestPrimaryDeviceAttributes).to_string(),
1984 /// "\x1b[c",
1985 /// );
1986 /// ```
1987 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1988 pub enum Device {
1989 /// A device-attributes response.
1990 DeviceAttributes(()),
1991
1992 /// [DECSTR] - soft terminal reset.
1993 ///
1994 /// [DECSTR]: https://vt100.net/docs/vt510-rm/DECSTR.html
1995 SoftReset,
1996
1997 /// Request primary device attributes.
1998 RequestPrimaryDeviceAttributes,
1999
2000 /// Request secondary device attributes.
2001 RequestSecondaryDeviceAttributes,
2002
2003 /// Request tertiary device attributes.
2004 RequestTertiaryDeviceAttributes,
2005
2006 /// Request terminal status.
2007 StatusReport,
2008
2009 /// Request the terminal name and version.
2010 ///
2011 /// Mintty and GNOME VTE discuss this query in [Mintty issue #881] and [GNOME VTE issue #235].
2012 ///
2013 /// [Mintty issue #881]: https://github.com/mintty/mintty/issues/881
2014 /// [GNOME VTE issue #235]: https://gitlab.gnome.org/GNOME/vte/-/issues/235
2015 RequestTerminalNameAndVersion,
2016
2017 /// Request terminal parameters.
2018 RequestTerminalParameters(i64),
2019 }
2020
2021 impl Display for Device {
2022 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2023 match self {
2024 Self::DeviceAttributes(_) => unimplemented!(),
2025 Self::SoftReset => write!(f, "!p"),
2026 Self::RequestPrimaryDeviceAttributes => write!(f, "c"),
2027 Self::RequestSecondaryDeviceAttributes => write!(f, ">c"),
2028 Self::RequestTertiaryDeviceAttributes => write!(f, "=c"),
2029 Self::StatusReport => write!(f, "5n"),
2030 Self::RequestTerminalNameAndVersion => write!(f, ">q"),
2031 Self::RequestTerminalParameters(n) => write!(f, "{};1;1;128;128;1;0x", n + 2),
2032 }
2033 }
2034 }
2035
2036 // Window
2037
2038 /// Window manipulation and window report CSI commands.
2039 ///
2040 /// ```
2041 /// use termina::escape::csi::{Csi, Window};
2042 ///
2043 /// assert_eq!(
2044 /// Csi::Window(Box::new(Window::ReportWindowTitle)).to_string(),
2045 /// "\x1b[21t",
2046 /// );
2047 /// assert_eq!(
2048 /// Csi::Window(Box::new(Window::ResizeWindowCells {
2049 /// width: Some(120),
2050 /// height: Some(40),
2051 /// }))
2052 /// .to_string(),
2053 /// "\x1b[8;40;120t",
2054 /// );
2055 /// ```
2056 #[derive(Debug, Clone, PartialEq, Eq)]
2057 pub enum Window {
2058 /// De-iconify the window.
2059 DeIconify,
2060
2061 /// Iconify the window.
2062 Iconify,
2063
2064 /// Move the window to a pixel position.
2065 MoveWindow {
2066 /// The x coordinate in pixels.
2067 x: i64,
2068
2069 /// The y coordinate in pixels.
2070 y: i64,
2071 },
2072
2073 /// Resize the window to a pixel size.
2074 ResizeWindowPixels {
2075 /// The desired width in pixels.
2076 width: Option<i64>,
2077
2078 /// The desired height in pixels.
2079 height: Option<i64>,
2080 },
2081
2082 /// Raise the window.
2083 RaiseWindow,
2084
2085 /// Lower the window.
2086 LowerWindow,
2087
2088 /// Refresh the window.
2089 RefreshWindow,
2090
2091 /// Resize the window to a cell size.
2092 ResizeWindowCells {
2093 /// The desired width in cells.
2094 width: Option<i64>,
2095
2096 /// The desired height in cells.
2097 height: Option<i64>,
2098 },
2099
2100 /// Restore a maximized window.
2101 RestoreMaximizedWindow,
2102
2103 /// Maximize the window.
2104 MaximizeWindow,
2105
2106 /// Maximize the window vertically.
2107 MaximizeWindowVertically,
2108
2109 /// Maximize the window horizontally.
2110 MaximizeWindowHorizontally,
2111
2112 /// Leave fullscreen mode.
2113 UndoFullScreenMode,
2114
2115 /// Enter fullscreen mode.
2116 ChangeToFullScreenMode,
2117
2118 /// Toggle fullscreen mode.
2119 ToggleFullScreen,
2120
2121 /// Request the window state.
2122 ReportWindowState,
2123
2124 /// Request the window position.
2125 ReportWindowPosition,
2126
2127 /// Request the text-area position.
2128 ReportTextAreaPosition,
2129
2130 /// Request the text-area size in pixels.
2131 ReportTextAreaSizePixels,
2132
2133 /// Request the window size in pixels.
2134 ReportWindowSizePixels,
2135
2136 /// Request the screen size in pixels.
2137 ReportScreenSizePixels,
2138
2139 /// Request the cell size in pixels.
2140 ReportCellSizePixels,
2141
2142 /// Report the cell size in pixels.
2143 ReportCellSizePixelsResponse {
2144 /// The reported cell width in pixels.
2145 width: Option<i64>,
2146
2147 /// The reported cell height in pixels.
2148 height: Option<i64>,
2149 },
2150
2151 /// Request the text-area size in cells.
2152 ReportTextAreaSizeCells,
2153
2154 /// Request the screen size in cells.
2155 ReportScreenSizeCells,
2156
2157 /// Request the icon label.
2158 ReportIconLabel,
2159
2160 /// Request the window title.
2161 ReportWindowTitle,
2162
2163 /// Push the icon and window title onto the title stack.
2164 PushIconAndWindowTitle,
2165
2166 /// Push the icon title onto the title stack.
2167 PushIconTitle,
2168
2169 /// Push the window title onto the title stack.
2170 PushWindowTitle,
2171
2172 /// Pop the icon and window title from the title stack.
2173 PopIconAndWindowTitle,
2174
2175 /// Pop the icon title from the title stack.
2176 PopIconTitle,
2177
2178 /// Pop the window title from the title stack.
2179 PopWindowTitle,
2180
2181 /// DECRQCRA; used by esctest
2182 ChecksumRectangularArea {
2183 /// The checksum request identifier.
2184 request_id: i64,
2185
2186 /// The page number to checksum.
2187 page_number: i64,
2188
2189 /// The top row of the rectangular area.
2190 top: OneBased,
2191
2192 /// The left column of the rectangular area.
2193 left: OneBased,
2194
2195 /// The bottom row of the rectangular area.
2196 bottom: OneBased,
2197
2198 /// The right column of the rectangular area.
2199 right: OneBased,
2200 },
2201 }
2202
2203 impl Display for Window {
2204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2205 struct NumstrOrEmpty(Option<i64>);
2206 impl Display for NumstrOrEmpty {
2207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2208 if let Some(x) = self.0 {
2209 write!(f, "{x}")?
2210 }
2211 Ok(())
2212 }
2213 }
2214
2215 match self {
2216 Window::DeIconify => write!(f, "1t"),
2217 Window::Iconify => write!(f, "2t"),
2218 Window::MoveWindow { x, y } => write!(f, "3;{x};{y}t"),
2219 Window::ResizeWindowPixels { width, height } => {
2220 write!(f, "4;{};{}t", NumstrOrEmpty(*height), NumstrOrEmpty(*width))
2221 }
2222 Window::RaiseWindow => write!(f, "5t"),
2223 Window::LowerWindow => write!(f, "6t"),
2224 Window::RefreshWindow => write!(f, "7t"),
2225 Window::ResizeWindowCells { width, height } => {
2226 write!(f, "8;{};{}t", NumstrOrEmpty(*height), NumstrOrEmpty(*width))
2227 }
2228 Window::RestoreMaximizedWindow => write!(f, "9;0t"),
2229 Window::MaximizeWindow => write!(f, "9;1t"),
2230 Window::MaximizeWindowVertically => write!(f, "9;2t"),
2231 Window::MaximizeWindowHorizontally => write!(f, "9;3t"),
2232 Window::UndoFullScreenMode => write!(f, "10;0t"),
2233 Window::ChangeToFullScreenMode => write!(f, "10;1t"),
2234 Window::ToggleFullScreen => write!(f, "10;2t"),
2235 Window::ReportWindowState => write!(f, "11t"),
2236 Window::ReportWindowPosition => write!(f, "13t"),
2237 Window::ReportTextAreaPosition => write!(f, "13;2t"),
2238 Window::ReportTextAreaSizePixels => write!(f, "14t"),
2239 Window::ReportWindowSizePixels => write!(f, "14;2t"),
2240 Window::ReportScreenSizePixels => write!(f, "15t"),
2241 Window::ReportCellSizePixels => write!(f, "16t"),
2242 Window::ReportCellSizePixelsResponse { width, height } => {
2243 write!(f, "6;{};{}t", NumstrOrEmpty(*height), NumstrOrEmpty(*width))
2244 }
2245 Window::ReportTextAreaSizeCells => write!(f, "18t"),
2246 Window::ReportScreenSizeCells => write!(f, "19t"),
2247 Window::ReportIconLabel => write!(f, "20t"),
2248 Window::ReportWindowTitle => write!(f, "21t"),
2249 Window::PushIconAndWindowTitle => write!(f, "22;0t"),
2250 Window::PushIconTitle => write!(f, "22;1t"),
2251 Window::PushWindowTitle => write!(f, "22;2t"),
2252 Window::PopIconAndWindowTitle => write!(f, "23;0t"),
2253 Window::PopIconTitle => write!(f, "23;1t"),
2254 Window::PopWindowTitle => write!(f, "23;2t"),
2255 Window::ChecksumRectangularArea {
2256 request_id,
2257 page_number,
2258 top,
2259 left,
2260 bottom,
2261 right,
2262 } => write!(
2263 f,
2264 "{request_id};{page_number};{top};{left};{bottom};{right}*y"
2265 ),
2266 }
2267 }
2268 }
2269
2270 #[cfg(test)]
2271 mod test {
2272 use crate::style::RgbColor;
2273
2274 use super::*;
2275
2276 const ENTER_ALTERNATE_SCREEN: Csi = Csi::Mode(Mode::SetDecPrivateMode(DecPrivateMode::Code(
2277 DecPrivateModeCode::ClearAndEnableAlternateScreen,
2278 )));
2279
2280 const EXIT_ALTERNATE_SCREEN: Csi = Csi::Mode(Mode::ResetDecPrivateMode(DecPrivateMode::Code(
2281 DecPrivateModeCode::ClearAndEnableAlternateScreen,
2282 )));
2283
2284 #[test]
2285 fn encoding() {
2286 // Enter the alternate screen using the mode part of CSI.
2287 // <https://learn.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences#alternate-screen-buffer>
2288 assert_eq!("\x1b[?1049h", ENTER_ALTERNATE_SCREEN.to_string());
2289 assert_eq!("\x1b[?1049l", EXIT_ALTERNATE_SCREEN.to_string());
2290
2291 // Push Kitty keyboard flags used by Helix and Kakoune at time of writing.
2292 assert_eq!(
2293 "\x1b[>5u",
2294 Csi::Keyboard(Keyboard::PushFlags(
2295 KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES
2296 | KittyKeyboardFlags::REPORT_ALTERNATE_KEYS
2297 ))
2298 .to_string()
2299 );
2300
2301 // Common SGR: turn the text (i.e. foreground) green
2302 assert_eq!(
2303 "\x1b[32m",
2304 Csi::Sgr(Sgr::Foreground(ColorSpec::GREEN)).to_string(),
2305 );
2306 // ... and then reset to turn off the green.
2307 assert_eq!(
2308 "\x1b[39m",
2309 Csi::Sgr(Sgr::Foreground(ColorSpec::Reset)).to_string(),
2310 );
2311
2312 // Push current window title to the terminal's stack.
2313 assert_eq!(
2314 "\x1b[22;0t",
2315 Csi::Window(Box::new(Window::PushIconAndWindowTitle)).to_string(),
2316 );
2317 // ... and pop it.
2318 assert_eq!(
2319 "\x1b[23;0t",
2320 Csi::Window(Box::new(Window::PopIconAndWindowTitle)).to_string(),
2321 );
2322
2323 // Set the cursor style to the terminal's default.
2324 // <https://terminalguide.namepad.de/seq/csi_sq_t_space/>
2325 assert_eq!(
2326 "\x1b[0 q",
2327 Csi::Cursor(Cursor::CursorStyle(CursorStyle::Default)).to_string()
2328 );
2329 }
2330
2331 #[test]
2332 fn sgr_attributes_csi_param_limit() {
2333 let mut attributes = SgrAttributes {
2334 foreground: Some(ColorSpec::TrueColor(RgbColor::new(80, 100, 120).into())),
2335 background: Some(ColorSpec::TrueColor(RgbColor::new(80, 100, 120).into())),
2336 underline_color: Some(ColorSpec::TrueColor(RgbColor::new(80, 100, 120).into())),
2337 modifiers: SgrModifiers::UNDERLINE_CURLY,
2338 ..Default::default()
2339 };
2340 // The sequence must be chunked into two since the chunk size is exceeded.
2341 // Here it is perfectly chunked so that the foreground and background are a full chunk.
2342 let expected = "\x1b[38;2;80;100;120;48;2;80;100;120m\x1b[58:2::80:100:120;4:3m";
2343 assert_eq!(expected, Csi::Sgr(Sgr::Attributes(attributes)).to_string());
2344 // If we make the chunk size bigger, we still chunk the same way. We wouldn't cut an SGR
2345 // sequence up in the middle: that would make it nonsense.
2346 attributes.parameter_chunk_size = NonZeroU16::new(12).unwrap();
2347 assert_eq!(expected, Csi::Sgr(Sgr::Attributes(attributes)).to_string());
2348 }
2349
2350 #[test]
2351 fn multi_cursor_encoding() {
2352 // QueryCursorShape
2353 assert_eq!(
2354 "\x1b[> q",
2355 Csi::Cursor(Cursor::QueryCursorShape).to_string()
2356 );
2357
2358 // CursorShapeQueryResponse with capability codes
2359 assert_eq!(
2360 "\x1b[>1;2;29;100 q",
2361 Csi::Cursor(Cursor::CursorShapeQueryResponse(vec![
2362 MultiCursorCapability::BlockShape,
2363 MultiCursorCapability::BeamShape,
2364 MultiCursorCapability::FollowMainCursorShape,
2365 MultiCursorCapability::QueryCurrentCursors,
2366 ]))
2367 .to_string()
2368 );
2369
2370 // SetMultipleCursors with MultiCursorShape::FollowMainCursor
2371 assert_eq!(
2372 "\x1b[>29;2:1:1;2:2:5 q",
2373 Csi::Cursor(Cursor::SetMultipleCursors {
2374 shape: MultiCursorShape::FollowMainCursor,
2375 positions: vec![
2376 (OneBased::new(1).unwrap(), OneBased::new(1).unwrap()),
2377 (OneBased::new(2).unwrap(), OneBased::new(5).unwrap()),
2378 ],
2379 })
2380 .to_string()
2381 );
2382
2383 // SetMultipleCursors with MultiCursorShape::Style
2384 assert_eq!(
2385 "\x1b[>2;2:3:10 q",
2386 Csi::Cursor(Cursor::SetMultipleCursors {
2387 shape: MultiCursorShape::Style(CursorStyle::SteadyBlock),
2388 positions: vec![(OneBased::new(3).unwrap(), OneBased::new(10).unwrap()),],
2389 })
2390 .to_string()
2391 );
2392
2393 // ClearSecondaryCursors
2394 assert_eq!(
2395 "\x1b[>0;4 q",
2396 Csi::Cursor(Cursor::ClearSecondaryCursors).to_string()
2397 );
2398 }
2399 }