Something went wrong. Try again.
wip text editor
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685use std::{ num, ops::{ self, Range, RangeInclusive, },};
use ropey::{ LineType, RopeSlice,};use unicode_segmentation::{ GraphemeCursor, GraphemeIncomplete, UnicodeSegmentation as _,};use unicode_width::UnicodeWidthStr as _;
use crate::{ grapheme_layout::{ GraphemeLayoutIterator, RowStart, WrapBehavior, }, ui::{ Columns, NonZeroColumns, },};
const LINE_TYPE: LineType = LineType::LF_CR;
pub(crate) trait RopeSliceExt<'rope> { fn line_idx_containing_byte(&self, byte: ByteIndex) -> LineIndex;
/// Gets the [`ByteIndex`] of the start of the line at the given /// [`LineIndex`]. /// /// # Panics /// /// Panics if `line > self.len_lines()`. fn line_start_byte(&self, line: LineIndex) -> ByteIndex;
/// Non-panicking version of [`RopeSliceExt::line_start_byte`]. fn get_line_start_byte(&self, line: LineIndex) -> Option<ByteIndex>;
fn line_at(&self, line_index: LineIndex) -> RopeSlice<'rope>;
/// Non-panicking version of [`RopeSliceExt::line_at`]. fn get_line_at(&self, line_index: LineIndex) -> Option<RopeSlice<'rope>>;
/// Gets the byte index of the first byte of the previous grapheme from the /// given byte index. fn previous_grapheme_position(&self, from: ByteIndex) -> ByteIndex;
/// Gets the byte index of the first byte of the next grapheme from the /// given byte index. fn next_grapheme_position(&self, from: ByteIndex) -> ByteIndex;
fn graphemes(&self) -> impl Iterator<Item = &'rope str> + use<'rope, Self>;
fn line_count(&self) -> usize;
fn last_line_idx(&self) -> LineIndex;
fn is_whitespace(&self) -> bool;
/// Gets the byte index of either: /// * the byte index corresponding to the given column; or: /// * the byte index corresponding to the last column (if the text is /// narrower than the given column) /// /// NOTE: the returned byte index is relative to the start of the text /// slice. fn byte_at_column(&self, target_column: Columns) -> ByteIndex;
/// Gets the line break information for the line at the given `line_index`. fn line_break(&self, line_index: LineIndex) -> LineBreakOutcome;
/// Converts an inclusive byte range to a half-open one containing the /// grapheme starting at the end of the given range. fn inclusive_to_exclusive_range(&self, range: RangeInclusive<ByteIndex>) -> Range<ByteIndex>;
/// Gets the byte offset of the first non-whitespace character in the slice, /// or 0 if it's all whitespace. fn first_non_blank_offset(&self) -> ByteIndex;
/// Gets the byte index of the start of the visual row that contains the /// given `byte_index`. fn row_start_containing_byte(&self, byte_index: ByteIndex, width: NonZeroColumns) -> RowStart;
/// Byte indices of the start of the **visual** lines (rows) produced by the /// text line. These indices are relative to the start of the text slice. /// /// A line can have multiple rows due to text wrapping. fn row_starts_for_line( &self, line_index: LineIndex, text_width: NonZeroColumns, ) -> impl Iterator<Item = RowStart>;}
impl<'rope> RopeSliceExt<'rope> for RopeSlice<'rope> { fn line_idx_containing_byte(&self, byte: ByteIndex) -> LineIndex { LineIndex::from(self.byte_to_line_idx(byte.value(), LINE_TYPE)) }
fn line_start_byte(&self, line: LineIndex) -> ByteIndex { self.get_line_start_byte(line).unwrap() }
fn get_line_start_byte(&self, line: LineIndex) -> Option<ByteIndex> { (line.value() <= self.len_lines(LINE_TYPE)) .then(|| ByteIndex::new(self.line_to_byte_idx(line.value(), LINE_TYPE))) }
fn line_at(&self, line_index: LineIndex) -> Self { self.line(line_index.value(), LINE_TYPE) }
fn get_line_at(&self, line_index: LineIndex) -> Option<Self> { self.get_line(line_index.value(), LINE_TYPE) }
fn previous_grapheme_position(&self, from: ByteIndex) -> ByteIndex { let text_slice = self.slice(..from.value());
let (mut chunk, mut chunk_start_index) = text_slice.chunk(from.value());
let mut grapheme_cursor = GraphemeCursor::new(from.value(), text_slice.len(), true);
loop { match grapheme_cursor.prev_boundary(chunk, chunk_start_index) { Ok(None) => break ByteIndex::from(0), Ok(Some(index)) => break ByteIndex::from(index),
Err(GraphemeIncomplete::PrevChunk) => { assert!( chunk_start_index > 0, "docs assert that `chunk_start_index` will be non-zero in this branch" ); (chunk, chunk_start_index) = text_slice.chunk(chunk_start_index - 1); }
Err(GraphemeIncomplete::PreContext(offset)) => { assert!( offset > 0, "there should be a chunk that ends at `offset`, and therefore it must be \ non-zero" );
let (context_chunk, context_chunk_start) = text_slice.chunk(offset - 1); grapheme_cursor.provide_context(context_chunk, context_chunk_start); }
Err(GraphemeIncomplete::NextChunk | GraphemeIncomplete::InvalidOffset) => { unreachable!() } } } }
fn next_grapheme_position(&self, from: ByteIndex) -> ByteIndex { from + self .slice(from.value()..) .graphemes() .next() .map_or(0, str::len) }
fn graphemes(&self) -> impl Iterator<Item = &'rope str> + use<'rope> { self.chunks().flat_map(|chunk| chunk.graphemes(true)) }
fn line_count(&self) -> usize { // NOTE: we are doing this because of: // https://docs.rs/ropey/2.0.0-beta.1/ropey/#a-note-about-line-breaks. if the file // has a trailing line break, ropey counts that in the line count, but // we want to act as if it doesn't exist. so, if the last line // is empty, we'll lower the line count let lines = self.len_lines(LINE_TYPE);
let last_line = self.line(lines.saturating_sub(1), LINE_TYPE);
if last_line.len() == 0 { lines.saturating_sub(1) } else { lines } }
fn last_line_idx(&self) -> LineIndex { LineIndex::new(self.line_count().saturating_sub(1)) }
fn is_whitespace(&self) -> bool { self.chars().all(char::is_whitespace) }
fn byte_at_column(&self, target_column: Columns) -> ByteIndex { let mut column = Columns::new(0); let mut byte_index = ByteIndex::new(0);
for raw in self.graphemes() { if column >= target_column { break; }
let grapheme = Grapheme::from(raw);
match grapheme { Grapheme::LineBreak => break, Grapheme::Tab | Grapheme::ZeroWidth | Grapheme::Text(_) => { column += grapheme.width(); byte_index += raw.len(); } } }
byte_index }
fn line_break(&self, line_index: LineIndex) -> LineBreakOutcome { let line = self.line_at(line_index); let line_start = self.line_start_byte(line_index);
let (offset, has_linebreak) = match line.trailing_line_break_idx(LINE_TYPE) { Some(offset) => (ByteIndex::new(offset), true), None => (ByteIndex::new(line.len()), false), };
LineBreakOutcome { position: line_start + offset, has_linebreak, } }
fn inclusive_to_exclusive_range(&self, range: RangeInclusive<ByteIndex>) -> Range<ByteIndex> { let (start, end) = range.into_inner(); assert!(start <= end, "range must be ordered");
start..self.next_grapheme_position(end) }
fn first_non_blank_offset(&self) -> ByteIndex { self.graphemes() .scan(ByteIndex::new(0), |offset, grapheme| { let start = *offset; *offset += grapheme.len(); Some((start, grapheme)) }) .find_map(|(start, grapheme)| (!grapheme.trim().is_empty()).then_some(start)) .unwrap_or_default() }
fn row_start_containing_byte( &self, byte_index: ByteIndex, text_width: NonZeroColumns, ) -> RowStart { let line = self.line_idx_containing_byte(byte_index);
self.row_starts_for_line(line, text_width) .take_while(|row_start| row_start.byte_index() <= byte_index) .last() .unwrap_or_else(|| RowStart::from_line(*self, line)) }
fn row_starts_for_line( &self, line_index: LineIndex, max_width: NonZeroColumns, ) -> impl Iterator<Item = RowStart> { GraphemeLayoutIterator::new(self.line_at(line_index).graphemes(), WrapBehavior::Wrap { max_width, }) .starting_at(RowStart::from_line(*self, line_index)) .filter(|grapheme| grapheme.position().left() == Columns::new(0)) .map(|grapheme| RowStart::new_unchecked(grapheme.byte_index())) }}
#[derive( Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, derive_more::From, derive_more::Add, derive_more::AddAssign, derive_more::Sum, derive_more::Sub,)]pub(crate) struct ByteIndex(usize);
impl ByteIndex { pub(crate) const fn new(value: usize) -> Self { Self(value) }
pub(crate) const fn value(self) -> usize { self.0 }
#[must_use = "`saturating_sub` does not mutate the current value, but returns a new value"] pub(crate) const fn saturating_sub(self, rhs: usize) -> Self { Self(self.0.saturating_sub(rhs)) }}
impl ops::Add<usize> for ByteIndex { type Output = Self;
fn add(self, rhs: usize) -> Self::Output { Self(self.0 + rhs) }}
impl ops::AddAssign<usize> for ByteIndex { fn add_assign(&mut self, rhs: usize) { self.0 += rhs; }}
#[derive( Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, derive_more::From, derive_more::Add, derive_more::AddAssign, derive_more::Display,)]pub(crate) struct LineIndex(usize);
impl LineIndex { pub(crate) const fn new(value: usize) -> Self { Self(value) }
pub(crate) const fn value(self) -> usize { self.0 }
#[must_use = "`saturating_sub` does not mutate the current value, but returns a new value"] pub(crate) fn saturating_sub(self, rhs: impl Into<usize>) -> Self { Self(self.0.saturating_sub(rhs.into())) }
#[must_use = "`checked_sub` does not mutate the current value, but returns an `Option`"] pub(crate) fn checked_sub(self, rhs: usize) -> Option<Self> { Some(Self(self.0.checked_sub(rhs)?)) }
pub(crate) const fn abs_diff(self, other: Self) -> Self { Self(self.0.abs_diff(other.0)) }}
impl ops::Add<usize> for LineIndex { type Output = Self;
fn add(self, rhs: usize) -> Self::Output { Self(self.0 + rhs) }}
impl TryFrom<u32> for LineIndex { type Error = num::TryFromIntError;
fn try_from(value: u32) -> Result<Self, Self::Error> { usize::try_from(value).map(Self) }}
#[derive(Debug)]pub(crate) struct VisualLineInfo<'text> { text: RopeSlice<'text>, line_index: LineIndex, /// Byte indices of the start of the **visual** lines produced by the text /// line. These indices are relative to the start of the text slice. /// /// A line can have multiple visual lines due to text wrapping. visual_line_starts: Vec<ByteIndex>, /// The maximum visual width of a line before the text needs to wrap. max_width: NonZeroColumns,}
impl<'text> VisualLineInfo<'text> { pub(crate) fn new( text: RopeSlice<'text>, line_index: LineIndex, max_width: NonZeroColumns, ) -> Self { let mut visual_line_starts = Vec::new();
for grapheme in GraphemeLayoutIterator::new(text.line_at(line_index).graphemes(), WrapBehavior::Wrap { max_width, }) .starting_at(RowStart::from_line(text, line_index)) { if grapheme.position().left() == Columns::new(0) { visual_line_starts.push(grapheme.byte_index()); } }
Self { text, line_index, visual_line_starts, max_width, } }
/// Attempts to get the byte index of the target column (or lower if the /// line isn't wide enough) on the **previous visual line** from the /// given `byte_index`. If the visual line doesn't exist, simply returns /// `None`. pub(crate) fn prev_at_column( &self, byte_index: ByteIndex, column: Columns, ) -> Option<ByteIndex> { let start = self.prev_visual_line(byte_index)?; Some(start + self.text.slice(start.value()..).byte_at_column(column)) }
/// Attempts to get the byte index of the target column (or lower if the /// line isn't wide enough) on the **next visual line** from the given /// `byte_index`. If the visual line doesn't exist, simply returns /// `None`. pub(crate) fn next_at_column( &self, byte_index: ByteIndex, column: Columns, ) -> Option<ByteIndex> { let start = self.next_visual_line(byte_index)?; Some(start + self.text.slice(start.value()..).byte_at_column(column)) }
/// Gets the **start byte** of the **visual** line above the visual line /// that contains the given byte index. This could either be part of the /// current text line (if it's wrapped) or the previous text line (if it /// exists). fn prev_visual_line(&self, byte_index: ByteIndex) -> Option<ByteIndex> { debug_assert!( self.visual_line_starts.is_sorted(), "`partition_point` will only work properly if the indices are sorted" );
let partition = self .visual_line_starts .partition_point(|start_index| *start_index <= byte_index);
// the partition logic actually gets the index of the **next** visual // line (if it exists), and so we have to subtract two from the // result. this works even if there isn't a visual line below // the current one, since `partition_point` returns the length // of `visual_line_starts` if the predicate matches for all // elements if partition >= 2 { self.visual_line_starts.get(partition - 2).copied() } else { Self::new(self.text, self.line_index.checked_sub(1)?, self.max_width) .bottom_visual_line() } }
/// Gets the **start byte** of the **visual** line below the visual line /// that contains the given byte index. This could either be part of the /// current text line (if it's wrapped) or the next text line (if it /// exists). fn next_visual_line(&self, byte_index: ByteIndex) -> Option<ByteIndex> { debug_assert!( self.visual_line_starts.is_sorted(), "`partition_point` will only work properly if the indices are sorted" );
let partition = self .visual_line_starts .partition_point(|start_index| *start_index <= byte_index);
self.visual_line_starts.get(partition).copied().or_else(|| { if self.text.last_line_idx() == self.line_index { None } else { Self::new(self.text, self.line_index + 1, self.max_width).top_visual_line() } }) }
/// Gets the **start byte** of the bottom **visual** line of the text line. fn bottom_visual_line(&self) -> Option<ByteIndex> { self.visual_line_starts.last().copied() }
/// Gets the **start byte** of the top **visual** line of the text line. fn top_visual_line(&self) -> Option<ByteIndex> { self.visual_line_starts.first().copied() }}
#[derive(Debug, PartialEq, Eq)]enum WordBoundaryKind { /// letters, digits, underscores. WordPart, Whitespace, Other,}
impl From<char> for WordBoundaryKind { fn from(ch: char) -> Self { if ch.is_whitespace() { Self::Whitespace } else if ch.is_alphanumeric() || ch == '_' { Self::WordPart } else { Self::Other } }}
impl From<LeftChar> for WordBoundaryKind { fn from(left: LeftChar) -> Self { Self::from(left.0) }}
impl From<RightChar> for WordBoundaryKind { fn from(right: RightChar) -> Self { Self::from(right.0) }}
/// A semantic wrapper around a `char` - only meaningful when paired with a/// corresponding [`RightChar`].#[derive(Debug, Clone, Copy)]pub(crate) struct LeftChar(char);
impl LeftChar { pub(crate) const fn new(ch: char) -> Self { Self(ch) }
pub(crate) const fn ch(self) -> char { self.0 }
pub(crate) fn is_word_end(self, right: RightChar) -> bool { let left_kind = WordBoundaryKind::from(self); let right_kind = WordBoundaryKind::from(right);
left_kind != right_kind && left_kind != WordBoundaryKind::Whitespace }}
/// A semantic wrapper around a `char` - only meaningful when paired with a/// corresponding [`LeftChar`].#[derive(Debug, Clone, Copy)]pub(crate) struct RightChar(char);
impl RightChar { pub(crate) const fn new(ch: char) -> Self { Self(ch) }
pub(crate) fn is_word_start(self, left: LeftChar) -> bool { let left_kind = WordBoundaryKind::from(left); let right_kind = WordBoundaryKind::from(self);
left_kind != right_kind && right_kind != WordBoundaryKind::Whitespace }
pub(crate) const fn ch(self) -> char { self.0 }}
#[derive(Debug)]pub(crate) struct LineBreakOutcome { /// The byte index of the slice that the line break appears (or should /// appear, if it doesn't exist). pub(crate) position: ByteIndex, /// The last line of a file may not have a line break, and this often /// requires special handling. pub(crate) has_linebreak: bool,}
const TAB_VISUAL_WIDTH: Columns = Columns::new(4);
#[derive(Debug)]pub(crate) enum Grapheme<'grapheme> { LineBreak, Tab, ZeroWidth, Text(&'grapheme str),}
impl Grapheme<'_> { const TAB_STR: &'static str = match str::from_utf8(&[b' '; TAB_VISUAL_WIDTH.value()]) { Ok(s) => s, Err(_) => unreachable!(), };
pub(crate) const fn display(&self) -> &str { match *self { Grapheme::LineBreak => " ", Grapheme::Tab => Self::TAB_STR, Grapheme::ZeroWidth => "\u{25cc}", Grapheme::Text(text) => text, } }
pub(crate) fn width(&self) -> Columns { Columns::new(self.display().width()) }}
impl<'grapheme> From<&'grapheme str> for Grapheme<'grapheme> { fn from(value: &'grapheme str) -> Self { match value { "\n" | "\r\n" => Self::LineBreak, "\t" => Self::Tab, _ if value.width() == 0 => Self::ZeroWidth, _ => Self::Text(value), } }}
/// Display width of the given text.pub(crate) fn text_width(text: &str) -> Columns { text.graphemes(true) .map(|grapheme| Grapheme::from(grapheme).width()) .sum()}
/// Works out the width of an integer (one column for each digit).pub(crate) fn number_width(value: usize) -> Columns { Columns::new((value.checked_ilog10().unwrap_or(0) + 1) as usize)}
#[cfg(test)]mod tests { use ropey::Rope;
use super::{ ByteIndex, RopeSliceExt as _, };
#[test] fn first_non_blank_offset() { for (text, expected) in [ ("", 0), ("hello", 0), ("0 0", 0), (" hello", 3), ("\t hello", 2), (" ", 0), (" \n", 0), (" \u{1F3FB}", 0), (" \u{1F3FB}x", 0), (" \u{1F3FB}x", 1), ] { assert_eq!( Rope::from_str(text).slice(..).first_non_blank_offset(), ByteIndex::new(expected), "text: {text:?}" ); } }}