Skip to main content

photon_ui/
kill_ring.rs

1/// A kill-ring (clipboard history) for Emacs-style yank operations.
2///
3/// Stores deleted text in a ring buffer. [`yank`](KillRing::yank) returns the
4/// most recent entry, and [`yank_pop`](KillRing::yank_pop) cycles backwards
5/// through older entries.
6#[derive(Debug, Clone, Default)]
7pub struct KillRing {
8    entries: Vec<String>,
9    index: usize,
10}
11
12impl KillRing {
13    /// Create an empty kill ring.
14    pub fn new() -> Self {
15        Self::default()
16    }
17
18    /// Add text to the kill ring.
19    ///
20    /// Empty strings are ignored. The internal index is reset to the newest
21    /// entry.
22    pub fn push(&mut self, text: String) {
23        if !text.is_empty() {
24            self.entries.push(text);
25            self.index = self.entries.len().saturating_sub(1);
26        }
27    }
28
29    /// Return the most recently killed text.
30    pub fn yank(&self) -> Option<&str> {
31        self.entries.last().map(|s| s.as_str())
32    }
33
34    /// Cycle backwards through the kill ring and return the text at the new
35    /// position.
36    pub fn yank_pop(&mut self) -> Option<&str> {
37        if self.entries.is_empty() {
38            return None;
39        }
40        self.index = self.index.checked_sub(1).unwrap_or(self.entries.len() - 1);
41        Some(&self.entries[self.index])
42    }
43}