Skip to content

Commit

Permalink
Idiomatic Crossterm
Browse files Browse the repository at this point in the history
  • Loading branch information
pflenker committed Apr 2, 2024
1 parent 0208201 commit fc28b24
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/editor.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::io::{self, Read};
use crossterm::event::{read, Event::Key, KeyCode::Char};

This comment has been minimized.

Copy link
@pflenker

pflenker Apr 2, 2024

Author Owner

We need a bit more from Crossterm now, especially the ability to deal with "events". Crossterm exposes anything that happens to the terminal - like a keypress, but also more - to us via an Event. For now, we're only interested in Key events (as opposed to e.g. an event that is fired when someone pastes something into the terminal).

use crossterm::terminal::{disable_raw_mode, enable_raw_mode};


pub struct Editor {

}
Expand All @@ -11,20 +12,21 @@ impl Editor {
}
pub fn run(&self){
enable_raw_mode().unwrap();
for b in io::stdin().bytes() {
match b {
Ok(b) => {
let c = b as char;
if c.is_control() {
println!("Binary: {0:08b} ASCII: {0:#03} \r", b);
} else {
println!("Binary: {0:08b} ASCII: {0:#03} Character: {1:#?}\r", b, c);
}
if c == 'q' {
break;
}
}
loop {

This comment has been minimized.

Copy link
@pflenker

pflenker Apr 2, 2024

Author Owner

We've replaced for..in with a loop here, which will continue until we use break to get out of it.

match read() {
Ok(Key(event)) => {

This comment has been minimized.

Copy link
@pflenker

pflenker Apr 2, 2024

Author Owner

OK, we've really expanded the usage of match here. We'll take a closer look at this back in the tutorial text.

println!("{:?} \r", event);

This comment has been minimized.

Copy link
@pflenker

pflenker Apr 2, 2024

Author Owner

Remember: {:?} prints the debug representation of event. Play around with the output after this change to see what the event from crossterm contains.

match (event.code) {
Char(c) => {
if c == 'q' {
break;
}
},
_ => (),
}
},
Err(err) => println!("Error: {}", err),
_ => ()
}
}
disable_raw_mode().unwrap();
Expand Down

0 comments on commit fc28b24

Please sign in to comment.