Skip to main content

brush_core/shell/
readline.rs

1//! Readline edit buffer support for shell instances.
2
3use crate::{error, extensions, variables::ShellVariable};
4
5impl<SE: extensions::ShellExtensions> crate::Shell<SE> {
6    /// Updates the shell state to reflect the given edit buffer contents.
7    ///
8    /// # Arguments
9    ///
10    /// * `contents` - The contents of the edit buffer.
11    /// * `cursor` - The cursor position in the edit buffer.
12    pub fn set_edit_buffer(&mut self, contents: String, cursor: usize) -> Result<(), error::Error> {
13        self.env
14            .set_global("READLINE_LINE", ShellVariable::new(contents))?;
15
16        self.env
17            .set_global("READLINE_POINT", ShellVariable::new(cursor.to_string()))?;
18
19        Ok(())
20    }
21
22    /// Returns the contents of the shell's edit buffer, if any. The buffer
23    /// state is cleared from the shell.
24    pub fn pop_edit_buffer(&mut self) -> Result<Option<(String, usize)>, error::Error> {
25        let line = self
26            .env
27            .unset("READLINE_LINE")?
28            .map(|line| line.value().to_cow_str(self).to_string());
29
30        let point = self
31            .env
32            .unset("READLINE_POINT")?
33            .and_then(|point| point.value().to_cow_str(self).parse::<usize>().ok())
34            .unwrap_or(0);
35
36        if let Some(line) = line {
37            Ok(Some((line, point)))
38        } else {
39            Ok(None)
40        }
41    }
42}