Skip to content

Commit

Permalink
Add bracketed paste parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
groves committed Aug 2, 2022
1 parent 551659d commit ca926b3
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 19 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Expand Up @@ -26,7 +26,8 @@ all-features = true
# Features
#
[features]
default = []
default = ["bracketed-paste"]
bracketed-paste = []
event-stream = ["futures-core"]

#
Expand Down
41 changes: 24 additions & 17 deletions examples/event-read.rs
Expand Up @@ -8,8 +8,8 @@ use crossterm::event::poll;
use crossterm::{
cursor::position,
event::{
read, DisableFocusChange, DisableMouseCapture, EnableFocusChange, EnableMouseCapture,
Event, KeyCode,
read, DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
EnableFocusChange, EnableMouseCapture, Event, KeyCode,
},
execute,
terminal::{disable_raw_mode, enable_raw_mode},
Expand All @@ -34,9 +34,9 @@ fn print_events() -> Result<()> {
println!("Cursor position: {:?}\r", position());
}

if let Event::Resize(_, _) = event {
let (original_size, new_size) = flush_resize_events(event);
println!("Resize from: {:?}, to: {:?}", original_size, new_size);
if let Event::Resize(x, y) = event {
let (original_size, new_size) = flush_resize_events((x, y));
println!("Resize from: {:?}, to: {:?}\r", original_size, new_size);
}

if event == Event::Key(KeyCode::Esc.into()) {
Expand All @@ -50,18 +50,15 @@ fn print_events() -> Result<()> {
// Resize events can occur in batches.
// With a simple loop they can be flushed.
// This function will keep the first and last resize event.
fn flush_resize_events(event: Event) -> ((u16, u16), (u16, u16)) {
if let Event::Resize(x, y) = event {
let mut last_resize = (x, y);
while let Ok(true) = poll(Duration::from_millis(50)) {
if let Ok(Event::Resize(x, y)) = read() {
last_resize = (x, y);
}
fn flush_resize_events(first_resize: (u16, u16)) -> ((u16, u16), (u16, u16)) {
let mut last_resize = first_resize;
while let Ok(true) = poll(Duration::from_millis(50)) {
if let Ok(Event::Resize(x, y)) = read() {
last_resize = (x, y);
}

return ((x, y), last_resize);
}
((0, 0), (0, 0))

return (first_resize, last_resize);
}

fn main() -> Result<()> {
Expand All @@ -70,13 +67,23 @@ fn main() -> Result<()> {
enable_raw_mode()?;

let mut stdout = stdout();
execute!(stdout, EnableFocusChange, EnableMouseCapture)?;
execute!(
stdout,
EnableBracketedPaste,
EnableFocusChange,
EnableMouseCapture
)?;

if let Err(e) = print_events() {
println!("Error: {:?}\r", e);
}

execute!(stdout, DisableFocusChange, DisableMouseCapture)?;
execute!(
stdout,
DisableBracketedPaste,
DisableFocusChange,
DisableMouseCapture
)?;

disable_raw_mode()
}
33 changes: 32 additions & 1 deletion src/event.rs
Expand Up @@ -450,9 +450,38 @@ impl Command for DisableFocusChange {
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EnableBracketedPaste;

impl Command for EnableBracketedPaste {
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
f.write_str(csi!("?2004h"))
}

#[cfg(windows)]
fn execute_winapi(&self) -> Result<()> {
Ok(())
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DisableBracketedPaste;

impl Command for DisableBracketedPaste {
fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
f.write_str(csi!("?2004l"))
}

#[cfg(windows)]
fn execute_winapi(&self) -> Result<()> {
Ok(())
}
}

/// Represents an event.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(not(feature = "bracketed-paste"), derive(Copy))]
#[derive(Debug, PartialOrd, PartialEq, Eq, Clone, Hash)]
pub enum Event {
/// The terminal gained focus
FocusGained,
Expand All @@ -462,6 +491,8 @@ pub enum Event {
Key(KeyEvent),
/// A single mouse event with additional pressed modifiers.
Mouse(MouseEvent),
#[cfg(feature = "bracketed-paste")]
Paste(String),
/// An resize event with new dimensions after resize (columns, rows).
/// **Note** that resize events can be occur in batches.
Resize(u16, u16),
Expand Down
20 changes: 20 additions & 0 deletions src/event/sys/unix/parse.rs
Expand Up @@ -180,6 +180,13 @@ pub(crate) fn parse_csi(buffer: &[u8]) -> Result<Option<InternalEvent>> {
if !(64..=126).contains(&last_byte) {
None
} else {
#[cfg(feature = "bracketed-paste")]
if buffer.len() >= 6 {
// If the length is 6 by the time we've hit something in the 64-126 range,
// we're in a bracketed paste. Let it keep reading till it hits its end
// delimiter
return parse_csi_bracketed_paste(buffer);
}
match buffer[buffer.len() - 1] {
b'M' => return parse_csi_rxvt_mouse(buffer),
b'~' => return parse_csi_special_key_code(buffer),
Expand Down Expand Up @@ -650,6 +657,19 @@ fn parse_cb(cb: u8) -> Result<(MouseEventKind, KeyModifiers)> {
Ok((kind, modifiers))
}

#[cfg(feature = "bracketed-paste")]
pub(crate) fn parse_csi_bracketed_paste(buffer: &[u8]) -> Result<Option<InternalEvent>> {
// ESC [ 2 0 0 ~ pasted text ESC 2 0 1 ~
assert!(buffer.starts_with(b"\x1B[200~"));

if !buffer.ends_with(b"\x1b[201~") {
Ok(None)
} else {
let paste = String::from_utf8_lossy(&buffer[6..buffer.len() - 6]).to_string();
Ok(Some(InternalEvent::Event(Event::Paste(paste))))
}
}

pub(crate) fn parse_utf8_char(buffer: &[u8]) -> Result<Option<char>> {
match std::str::from_utf8(buffer) {
Ok(s) => {
Expand Down

0 comments on commit ca926b3

Please sign in to comment.