Struct StringEditor

Source
pub struct StringEditor { /* private fields */ }
Expand description

A StringEditor instance wraps a String and provides a way to edit it using a variety of commands. It also keeps track of the cursor position, which can be used for rendering.

§Example

use string_cmd::StringEditor;

let mut editor = StringEditor::new();

// Insert text
editor.execute(Command::Insert('H'));
editor.execute(Command::Insert('e'));
editor.execute(Command::Insert('l'));
editor.execute(Command::Insert('l'));
editor.execute(Command::Insert('o'));

// Get the current text
let text = editor.get_text(); // "Hello"

// Get the cursor position
let cursor = editor.cursor_pos(); // 5

In most cases, you’ll want to use the StringEditor in conjunction with a terminal event loop. If you’re using crossterm and want to use the default keybindings, check out the events module (requires the crossterm feature).

Implementations§

Source§

impl StringEditor

Source

pub fn new() -> Self

Create a new StringEditor with an empty string.

Examples found in repository?
examples/demo.rs (line 11)
10fn main() -> std::io::Result<()> {
11    let mut editor = StringEditor::new();
12    let mut stdout = std::io::stdout();
13
14    println!("Enter text below:");
15    enable_raw_mode()?;
16
17    let input = loop {
18        if event::poll(Duration::from_millis(10))? {
19            let event = event::read()?;
20            if let event::Event::Key(key) = &event {
21                let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL);
22
23                match key.code {
24                    KeyCode::Esc => break None,
25                    KeyCode::Char('q') if ctrl => break None,
26                    KeyCode::Enter => break Some(editor.get_text()),
27                    _ => {}
28                }
29            }
30
31            if let Some(command) = event_to_command(&event) {
32                editor.execute(command);
33            }
34        }
35
36        execute!(
37            stdout,
38            cursor::MoveToColumn(0),
39            terminal::Clear(terminal::ClearType::CurrentLine)
40        )?;
41        print!("{}", editor.get_text());
42        execute!(stdout, cursor::MoveToColumn(editor.cursor_pos() as u16))?;
43    };
44
45    disable_raw_mode()?;
46    println!("\nGot input: {:?}", input);
47
48    Ok(())
49}
Source

pub fn with_string(text: &str) -> Self

Create a new StringEditor with a given string. Sets the cursor position to just after the end of the string.

Source

pub fn get_text(&self) -> &str

Get the current text of the editor.

Examples found in repository?
examples/demo.rs (line 26)
10fn main() -> std::io::Result<()> {
11    let mut editor = StringEditor::new();
12    let mut stdout = std::io::stdout();
13
14    println!("Enter text below:");
15    enable_raw_mode()?;
16
17    let input = loop {
18        if event::poll(Duration::from_millis(10))? {
19            let event = event::read()?;
20            if let event::Event::Key(key) = &event {
21                let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL);
22
23                match key.code {
24                    KeyCode::Esc => break None,
25                    KeyCode::Char('q') if ctrl => break None,
26                    KeyCode::Enter => break Some(editor.get_text()),
27                    _ => {}
28                }
29            }
30
31            if let Some(command) = event_to_command(&event) {
32                editor.execute(command);
33            }
34        }
35
36        execute!(
37            stdout,
38            cursor::MoveToColumn(0),
39            terminal::Clear(terminal::ClearType::CurrentLine)
40        )?;
41        print!("{}", editor.get_text());
42        execute!(stdout, cursor::MoveToColumn(editor.cursor_pos() as u16))?;
43    };
44
45    disable_raw_mode()?;
46    println!("\nGot input: {:?}", input);
47
48    Ok(())
49}
Source

pub fn cursor_pos(&self) -> usize

Get the current cursor position.

Examples found in repository?
examples/demo.rs (line 42)
10fn main() -> std::io::Result<()> {
11    let mut editor = StringEditor::new();
12    let mut stdout = std::io::stdout();
13
14    println!("Enter text below:");
15    enable_raw_mode()?;
16
17    let input = loop {
18        if event::poll(Duration::from_millis(10))? {
19            let event = event::read()?;
20            if let event::Event::Key(key) = &event {
21                let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL);
22
23                match key.code {
24                    KeyCode::Esc => break None,
25                    KeyCode::Char('q') if ctrl => break None,
26                    KeyCode::Enter => break Some(editor.get_text()),
27                    _ => {}
28                }
29            }
30
31            if let Some(command) = event_to_command(&event) {
32                editor.execute(command);
33            }
34        }
35
36        execute!(
37            stdout,
38            cursor::MoveToColumn(0),
39            terminal::Clear(terminal::ClearType::CurrentLine)
40        )?;
41        print!("{}", editor.get_text());
42        execute!(stdout, cursor::MoveToColumn(editor.cursor_pos() as u16))?;
43    };
44
45    disable_raw_mode()?;
46    println!("\nGot input: {:?}", input);
47
48    Ok(())
49}
Source§

impl StringEditor

Source

pub fn execute(&mut self, command: Command)

Execute a command on the editor.

Examples found in repository?
examples/demo.rs (line 32)
10fn main() -> std::io::Result<()> {
11    let mut editor = StringEditor::new();
12    let mut stdout = std::io::stdout();
13
14    println!("Enter text below:");
15    enable_raw_mode()?;
16
17    let input = loop {
18        if event::poll(Duration::from_millis(10))? {
19            let event = event::read()?;
20            if let event::Event::Key(key) = &event {
21                let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL);
22
23                match key.code {
24                    KeyCode::Esc => break None,
25                    KeyCode::Char('q') if ctrl => break None,
26                    KeyCode::Enter => break Some(editor.get_text()),
27                    _ => {}
28                }
29            }
30
31            if let Some(command) = event_to_command(&event) {
32                editor.execute(command);
33            }
34        }
35
36        execute!(
37            stdout,
38            cursor::MoveToColumn(0),
39            terminal::Clear(terminal::ClearType::CurrentLine)
40        )?;
41        print!("{}", editor.get_text());
42        execute!(stdout, cursor::MoveToColumn(editor.cursor_pos() as u16))?;
43    };
44
45    disable_raw_mode()?;
46    println!("\nGot input: {:?}", input);
47
48    Ok(())
49}

Trait Implementations§

Source§

impl Clone for StringEditor

Source§

fn clone(&self) -> StringEditor

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for StringEditor

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for StringEditor

Source§

fn default() -> StringEditor

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.