From 9cc9729ed9a1b3ea259b8529a4fdf0d53a81f4bc Mon Sep 17 00:00:00 2001 From: Joshua Barretto Date: Tue, 23 Sep 2025 13:47:18 +0100 Subject: [PATCH] Added automatic commenting --- src/action.rs | 7 +++++++ src/state.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/ui/input.rs | 4 ++++ 3 files changed, 51 insertions(+) diff --git a/src/action.rs b/src/action.rs index 7e1b5a8..17b830b 100644 --- a/src/action.rs +++ b/src/action.rs @@ -49,6 +49,7 @@ pub enum Action { Cut, Paste, Duplicate, + Comment, } /// How far should movement go? @@ -471,6 +472,12 @@ impl RawEvent { kind: KeyEventKind::Press, .. }) => Some(Action::Duplicate), + TerminalEvent::Key(KeyEvent { + code: KeyCode::Char('7'), // ????? + modifiers: KeyModifiers::CONTROL, + kind: KeyEventKind::Press, + .. + }) => Some(Action::Comment), _ => None, } } diff --git a/src/state.rs b/src/state.rs index 91a98f1..77e4ce8 100644 --- a/src/state.rs +++ b/src/state.rs @@ -791,6 +791,46 @@ impl Buffer { } } + pub fn comment(&mut self, cursor_id: CursorId) { + let Some(cursor) = self.cursors.get_mut(cursor_id) else { + return; + }; + let lines = cursor + .selection() + .map(|s| self.text.to_coord(s.start)[1]..=self.text.to_coord(s.end)[1]) + .unwrap_or_else(|| { + let coord = self.text.to_coord(cursor.pos); + coord[1]..=coord[1] + }); + let mut indent: Option<&[char]> = None; + for line_idx in lines.clone() { + indent = Some(match (indent, self.text.indent_of_line(line_idx)) { + (Some(indent), new_indent) => { + &new_indent[..indent + .iter() + .zip(new_indent) + .take_while(|(x, y)| x == y) + .count()] + } + (None, new_indent) => new_indent, + }); + } + let indent = indent.unwrap_or(&[]).to_vec(); + for line_idx in lines { + let pos = self.text.to_pos([indent.len() as isize, line_idx]); + if self + .text + .chars() + .get(pos..) + .map_or(false, |l| l.starts_with(&['/', '/', ' '])) + { + self.remove(pos..pos + 3); + } else { + self.insert(pos, "// ".chars()); + } + } + } + pub fn start_session(&mut self) -> CursorId { self.cursors.insert(Cursor::default()) } diff --git a/src/ui/input.rs b/src/ui/input.rs index baf6e3a..a4449dc 100644 --- a/src/ui/input.rs +++ b/src/ui/input.rs @@ -193,6 +193,10 @@ impl Input { self.refocus(buffer, cursor_id); Ok(Resp::handled(None)) } + Some(Action::Comment) => { + buffer.comment(cursor_id); + Ok(Resp::handled(None)) + } _ => Err(event), } }