From 3bc1159ffc141942e2cf36fb7cbd66916ffb8deb Mon Sep 17 00:00:00 2001 From: alemi Date: Fri, 24 Nov 2023 11:04:42 +0100 Subject: [PATCH] feat: utility fn to convert from index to rowcol --- src/api/change.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/api/change.rs b/src/api/change.rs index 95e34fa..4f077d2 100644 --- a/src/api/change.rs +++ b/src/api/change.rs @@ -3,6 +3,8 @@ //! an editor-friendly representation of a text change in a buffer //! to easily interface with codemp from various editors +use crate::proto::RowCol; + /// an editor-friendly representation of a text change in a buffer /// /// this represent a range in the previous state of the string and a new content which should be @@ -56,4 +58,12 @@ impl TextChange { content: after[start..end_after].to_string(), } } + + /// convert from byte index to row and column + /// txt must be the whole content of the buffer, in order to count lines + pub fn index_to_rowcol(txt: &str, index: usize) -> RowCol { + let row = txt[..index].matches('\n').count() as i32; + let col = txt[..index].split('\n').last().unwrap_or("").len() as i32; + RowCol { row, col } + } }