From 7646989d6f5b0d2bfe32a123e10fe13693d7c89c Mon Sep 17 00:00:00 2001 From: Vancha Date: Wed, 16 Jul 2025 22:39:48 +0200 Subject: [PATCH] Fixed Tab indenting the line instead of adding Tab or spaces (#403) * Update editor.rs * Makes sure indent_required is calculated according to the selection type removed the redundant check for required_indent == 0, introduced a slightly different path for when no selection = None, and calculated the required tab width and indent position accordingly. * Undo typo undid an accidental move of a redraw call outside of a loop * Corrected indenting with rustfmt formatted the code with rustfmt to pass the failing CI checks --- src/edit/editor.rs | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/edit/editor.rs b/src/edit/editor.rs index c1b63d8..36fb92d 100644 --- a/src/edit/editor.rs +++ b/src/edit/editor.rs @@ -697,22 +697,32 @@ impl<'buffer> Edit<'buffer> for Editor<'buffer> { self.with_buffer(|buffer| { let line = &buffer.lines[line_i]; let text = line.text(); - // Default to end of line if no non-whitespace found - after_whitespace = text.len(); - for (count, (index, c)) in text.char_indices().enumerate() { - if !c.is_whitespace() { - after_whitespace = index; - required_indent = tab_width - (count % tab_width); - break; + + if self.selection == Selection::None { + //Selection::None counts whitespace from the cursor backwards + let whitespace_length = match line.text()[0..self.cursor.index] + .chars() + .rev() + .position(|c| !c.is_whitespace()) + { + Some(length) => length, + // The whole line is whitespace + None => self.cursor.index, + }; + required_indent = tab_width - (whitespace_length % tab_width); + after_whitespace = self.cursor.index; + } else { + // Other selections count whitespace from the start of the line + for (count, (index, c)) in text.char_indices().enumerate() { + if !c.is_whitespace() { + after_whitespace = index; + required_indent = tab_width - (count % tab_width); + break; + } } } }); - // No indent required (not possible?) - if required_indent == 0 { - required_indent = tab_width; - } - self.insert_at( Cursor::new(line_i, after_whitespace), &" ".repeat(required_indent), @@ -739,7 +749,6 @@ impl<'buffer> Edit<'buffer> for Editor<'buffer> { } } } - // Request redraw self.with_buffer_mut(|buffer| buffer.set_redraw(true)); }