From c656dc0931be5ef9b34302042e58d4bf25bb9181 Mon Sep 17 00:00:00 2001 From: CrispyPin Date: Sun, 26 Feb 2023 01:02:10 +0100 Subject: [PATCH] render cursor position properly after tabs --- .gitignore | 2 +- src/editor.rs | 20 ++++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index e49dec6..9f2a7dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ /target -err +err.log diff --git a/src/editor.rs b/src/editor.rs index 0b46b54..86ab9e1 100644 --- a/src/editor.rs +++ b/src/editor.rs @@ -9,6 +9,8 @@ use termion::{ raw::IntoRawMode, }; +const TAB_SIZE: usize = 4; + pub struct Editor { text: String, lines: Vec, @@ -100,8 +102,8 @@ impl Editor { } } - fn current_line(&self) -> &Line { - self.lines.get(self.cursor.line).unwrap_or(&(0..0)) + fn current_line(&self) -> Line { + self.lines.get(self.cursor.line).unwrap_or(&(0..0)).clone() } fn find_lines(&mut self) { @@ -124,12 +126,15 @@ impl Editor { print!( "{}{}", cursor::Goto(1, row as u16 + 1), - text.replace('\t', " ") + text.replace('\t', &" ".repeat(TAB_SIZE)) ); } print!( "{}", - cursor::Goto(self.cursor.column as u16 + 1, self.cursor.line as u16 + 1) + cursor::Goto( + self.physical_column() as u16 + 1, + self.cursor.line as u16 + 1 + ) ); stdout().flush().unwrap(); } @@ -154,4 +159,11 @@ impl Editor { fn index(&self) -> usize { self.current_line().start + self.cursor.column } + + fn physical_column(&self) -> usize { + let start = self.current_line().start; + let end = self.current_line().start + self.cursor.column; + let preceding_tabs = self.text[start..end].chars().filter(|&c| c == '\t').count(); + self.cursor.column + preceding_tabs * (TAB_SIZE - 1) + } }