Skip to main content

shrub_core/shell/
readline.rs

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