From a64a2ec3e9cc4b59e3724f6a7aa1b1f7a0b5443d Mon Sep 17 00:00:00 2001 From: Willians Faria Date: Tue, 21 May 2024 17:11:52 -0300 Subject: [PATCH] feat: adding scope aware newline above --- reqtui/src/text_object/text_object.rs | 27 +++++++++++-------- tui/src/components/api_explorer/req_editor.rs | 3 ++- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/reqtui/src/text_object/text_object.rs b/reqtui/src/text_object/text_object.rs index ef951d3..a60fc2d 100644 --- a/reqtui/src/text_object/text_object.rs +++ b/reqtui/src/text_object/text_object.rs @@ -356,23 +356,17 @@ impl TextObject { } pub fn insert_line_below(&mut self, cursor: &Cursor, tree: Option<&Tree>) { - let indentation = if let Some(tree) = tree { - let line_byte_idx = self.content.line_to_byte(cursor.row()); - let cursor_byte_idx = line_byte_idx.add(cursor.col()); - let indentation_level = Highlighter::find_indentation_level(tree, cursor_byte_idx); - tracing::debug!("{indentation_level}"); - " ".repeat(indentation_level) - } else { - String::new() - }; + let indentation = self.get_scope_aware_indentation(cursor, tree); let next_line = self.content.line_to_char(cursor.row().add(1)); let line_with_indentation = format!("{}{}", indentation, &self.line_break.to_string()); self.content.insert(next_line, &line_with_indentation); } - pub fn insert_line_above(&mut self, cursor: &Cursor) { + pub fn insert_line_above(&mut self, cursor: &Cursor, tree: Option<&Tree>) { + let indentation = self.get_scope_aware_indentation(cursor, tree); let curr_line = self.content.line_to_char(cursor.row()); - self.content.insert(curr_line, &self.line_break.to_string()); + let line_with_indentation = format!("{}{}", indentation, &self.line_break.to_string()); + self.content.insert(curr_line, &line_with_indentation); } pub fn find_oposing_token(&mut self, cursor: &Cursor) -> (usize, usize) { @@ -456,6 +450,17 @@ impl TextObject { (curr_col, curr_row) } } + + fn get_scope_aware_indentation(&self, cursor: &Cursor, tree: Option<&Tree>) -> String { + if let Some(tree) = tree { + let line_byte_idx = self.content.line_to_byte(cursor.row()); + let cursor_byte_idx = line_byte_idx.add(cursor.col()); + let indentation_level = Highlighter::find_indentation_level(tree, cursor_byte_idx); + " ".repeat(indentation_level) + } else { + String::new() + } + } } impl std::fmt::Display for TextObject { diff --git a/tui/src/components/api_explorer/req_editor.rs b/tui/src/components/api_explorer/req_editor.rs index 79315a8..da84dcc 100644 --- a/tui/src/components/api_explorer/req_editor.rs +++ b/tui/src/components/api_explorer/req_editor.rs @@ -423,7 +423,8 @@ impl<'re> ReqEditor<'re> { } fn insert_line_above(&mut self) { - self.body.insert_line_above(&self.cursor); + self.body + .insert_line_above(&self.cursor, self.tree.as_ref()); self.maybe_scroll_view(); let line_len = self.body.line_len(self.cursor.row()); self.cursor.maybe_snap_to_col(line_len);