From 3d0107cb7515fa2b52292a222e5f56cb4fa5c679 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 7 Nov 2020 09:26:32 -0800 Subject: [PATCH] term/termwiz: add Cell::semantic_type This commit allows the terminal to tag cells with their semantic type, as defined by OSC 133 escape sequences. The gist of it is that each cell is now semantically one of: * Output (eg: from the activity performed by the user. This is the default) * Input (eg: something that the user typed as input) * Prompt (eg: "uninteresting" chrome/UI from the shell) The semantic type is applied almost exactly like an SGR attribute, except that resetting SGR doesn't clear the semantic type. Tagging the cells in this way allows for smarter UX in the future; for example, selecting the entire input or output from the last command without fiddling around to avoid the prompt line(s), or "paging up" to a prior prompt rather than page. This doc covers those escapes as used in domterm, iterm2 and other terminals: https://gitlab.freedesktop.org/Per_Bothner/specifications/blob/master/proposals/semantic-prompts.md This is an example of how to configure the shell to emit these sequences; I'll add a proper little blob of shell specifically for wezterm in a later commit: https://github.com/PerBothner/DomTerm/blob/master/tools/shell-integration.zsh --- term/src/terminalstate.rs | 47 ++++++++++++++++++- term/src/test/mod.rs | 99 +++++++++++++++++++++++++++++++++++++++ termwiz/src/cell.rs | 44 ++++++++++++++++- 3 files changed, 188 insertions(+), 2 deletions(-) diff --git a/term/src/terminalstate.rs b/term/src/terminalstate.rs index 09408949e..c57562c09 100644 --- a/term/src/terminalstate.rs +++ b/term/src/terminalstate.rs @@ -15,7 +15,9 @@ use termwiz::escape::csi::{ Cursor, CursorStyle, DecPrivateMode, DecPrivateModeCode, Device, Edit, EraseInDisplay, EraseInLine, Mode, Sgr, TabulationClear, TerminalMode, TerminalModeCode, Window, }; -use termwiz::escape::osc::{ChangeColorPair, ColorOrQuery, ITermFileData, ITermProprietary}; +use termwiz::escape::osc::{ + ChangeColorPair, ColorOrQuery, FinalTermSemanticPrompt, ITermFileData, ITermProprietary, +}; use termwiz::escape::{ Action, ControlCode, DeviceControlMode, Esc, EscCode, OneBased, OperatingSystemCommand, Sixel, SixelData, CSI, @@ -1125,6 +1127,16 @@ impl TerminalState { ) } + /// Defined by FinalTermSemanticPrompt; a fresh-line is a NOP if the + /// cursor is already at the left margin, otherwise it is the same as + /// a new line. + fn fresh_line(&mut self) { + if self.cursor.x == self.left_and_right_margins.start { + return; + } + self.new_line(true); + } + fn new_line(&mut self, move_to_first_column: bool) { let x = if move_to_first_column { self.left_and_right_margins.start @@ -2460,8 +2472,10 @@ impl TerminalState { match sgr { Sgr::Reset => { let link = self.pen.hyperlink().map(Arc::clone); + let semantic_type = self.pen.semantic_type(); self.pen = CellAttributes::default(); self.pen.set_hyperlink(link); + self.pen.set_semantic_type(semantic_type); } Sgr::Intensity(intensity) => { self.pen.set_intensity(intensity); @@ -2907,6 +2921,37 @@ impl<'a> Performer<'a> { _ => error!("unhandled iterm2: {:?}", iterm), }, + OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::FreshLine) => { + self.fresh_line(); + } + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::FreshLineAndStartPrompt { .. }, + ) => { + self.fresh_line(); + self.pen.set_semantic_type(SemanticType::Prompt); + } + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::StartPrompt(_), + ) => { + self.pen.set_semantic_type(SemanticType::Prompt); + } + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::MarkEndOfCommandWithFreshLine { .. }, + ) => { + self.pen.set_semantic_type(SemanticType::Prompt); + self.fresh_line(); + } + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::MarkEndOfPromptAndStartOfInputUntilNextMarker { .. }, + ) => { + self.pen.set_semantic_type(SemanticType::Input); + } + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::MarkEndOfInputAndStartOfOutput { .. }, + ) => { + self.pen.set_semantic_type(SemanticType::Output); + } + OperatingSystemCommand::FinalTermSemanticPrompt(ft) => { error!("unhandled: {:?}", ft); } diff --git a/term/src/test/mod.rs b/term/src/test/mod.rs index 7cb50f617..af2d6e02a 100644 --- a/term/src/test/mod.rs +++ b/term/src/test/mod.rs @@ -314,6 +314,105 @@ fn assert_all_contents(term: &Terminal, file: &str, line: u32, expect_lines: &[& assert_lines_equal(file, line, &screen.all_lines(), &expect, Compare::TEXT); } +#[test] +fn test_semantic() { + use termwiz::escape::osc::FinalTermSemanticPrompt; + let mut term = TestTerm::new(5, 10, 0); + term.print("hello"); + term.print(format!( + "{}", + OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::FreshLine) + )); + term.print("there"); + + assert_visible_contents( + &term, + file!(), + line!(), + &[ + "hello ", + "there ", + " ", + " ", + " ", + ], + ); + + term.cup(0, 2); + term.print(format!( + "{}", + OperatingSystemCommand::FinalTermSemanticPrompt(FinalTermSemanticPrompt::FreshLine) + )); + term.print("three"); + assert_visible_contents( + &term, + file!(), + line!(), + &[ + "hello ", + "there ", + "three ", + " ", + " ", + ], + ); + + term.print(format!( + "{}", + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::FreshLineAndStartPrompt { + aid: None, + cl: None + } + ) + )); + term.print("> "); + term.print(format!( + "{}", + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::MarkEndOfPromptAndStartOfInputUntilNextMarker + ) + )); + term.print("ls -l\r\n"); + term.print(format!( + "{}", + OperatingSystemCommand::FinalTermSemanticPrompt( + FinalTermSemanticPrompt::MarkEndOfInputAndStartOfOutput { aid: None } + ) + )); + term.print("some file"); + + let output = CellAttributes::default(); + let mut input = CellAttributes::default(); + input.set_semantic_type(SemanticType::Input); + + let mut prompt_line = Line::from_text("> ls -l ", &output); + for i in 0..2 { + prompt_line.cells_mut()[i] + .attrs_mut() + .set_semantic_type(SemanticType::Prompt); + } + for i in 2..7 { + prompt_line.cells_mut()[i] + .attrs_mut() + .set_semantic_type(SemanticType::Input); + } + + assert_lines_equal( + file!(), + line!(), + &term.screen().visible_lines(), + &[ + Line::from_text("hello ", &output), + Line::from_text("there ", &output), + Line::from_text("three ", &output), + prompt_line, + Line::from_text("some file ", &output), + ], + Compare::TEXT | Compare::ATTRS, + ); +} + #[test] fn basic_output() { let mut term = TestTerm::new(5, 10, 0); diff --git a/termwiz/src/cell.rs b/termwiz/src/cell.rs index a081c6c85..91612d852 100644 --- a/termwiz/src/cell.rs +++ b/termwiz/src/cell.rs @@ -15,7 +15,7 @@ use unicode_width::UnicodeWidthStr; /// The setter methods return a mutable self reference so that they can /// be chained together. #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] -#[derive(Debug, Default, Clone, Eq, PartialEq)] +#[derive(Default, Clone, Eq, PartialEq)] pub struct CellAttributes { attributes: u16, /// The foreground color @@ -28,6 +28,27 @@ pub struct CellAttributes { fat: Option>, } +impl std::fmt::Debug for CellAttributes { + fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { + fmt.debug_struct("CellAttributes") + .field("attributes", &self.attributes) + .field("intensity", &self.intensity()) + .field("underline", &self.underline()) + .field("blink", &self.blink()) + .field("italic", &self.italic()) + .field("reverse", &self.reverse()) + .field("strikethrough", &self.strikethrough()) + .field("invisible", &self.invisible()) + .field("wrapped", &self.wrapped()) + .field("overline", &self.overline()) + .field("semantic_type", &self.semantic_type()) + .field("foreground", &self.foreground) + .field("background", &self.background) + .field("fat", &self.fat) + .finish() + } +} + #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] #[derive(Debug, Default, Clone, Eq, PartialEq)] struct FatAttributes { @@ -91,6 +112,26 @@ macro_rules! bitfield { }; } +/// Describes the semantic "type" of the cell. +/// This categorizes cells into Output (from the actions the user is +/// taking; this is the default if left unspecified), +/// Input (that the user typed) and Prompt (effectively, "chrome" provided +/// by the shell or application that the user is interacting with. +#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u16)] +pub enum SemanticType { + Output = 0, + Input = 1, + Prompt = 2, +} + +impl Default for SemanticType { + fn default() -> Self { + Self::Output + } +} + /// The `Intensity` of a cell describes its boldness. Most terminals /// implement `Intensity::Bold` by either using a bold font or by simply /// using an alternative color. Some terminals implement `Intensity::Half` @@ -167,6 +208,7 @@ impl CellAttributes { bitfield!(invisible, set_invisible, 9); bitfield!(wrapped, set_wrapped, 10); bitfield!(overline, set_overline, 11); + bitfield!(semantic_type, set_semantic_type, SemanticType, 0b11, 12); /// Returns true if the attribute bits in both objects are equal. /// This can be used to cheaply test whether the styles of the two