use super::inline_line::InputLine;
mod char_widths;
mod measurements;
mod monospace;
mod wrap_width;
use char_widths::{CharWidths, LineWidths};
use gpui::Half;
use measurements::WidthMeasurements;
use monospace::{MonospaceWidths, is_printable_ascii};
use std::borrow::Cow;
use std::ops::Range;
use std::rc::Rc;
use wrap_width::{MeasuredWrap, WidthRange};
use gpui::{
App, Bounds, ContentMask, Font, LineFragment, Pixels, Point, ShapedLine, Size, TextAlign,
Window, point, px, size,
};
use ropey::Rope;
use smallvec::SmallVec;
use sum_tree::{Bias, Dimensions, SumTree};
use unicode_segmentation::UnicodeSegmentation as _;
use crate::input::{
Point as TreeSitterPoint, RopeExt, TabSize,
layout::{LastLayout, WhitespaceIndicators},
tab_stops::{expanded_width, tab_stop_width},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WrappingIndent {
None,
#[default]
Same,
}
#[cfg(test)]
fn measured_wrap_boundaries(
text: &str,
width: Pixels,
wrapping_indent: WrappingIndent,
mut measure: impl FnMut(&str) -> Pixels,
) -> Vec<gpui::Boundary> {
let indent = if wrapping_indent == WrappingIndent::Same {
text.chars()
.take_while(|&c| c == ' ')
.count()
.min(gpui::LineWrapper::MAX_INDENT as usize)
} else {
0
};
let indent_width = measure(&text[..indent]);
let ends: Vec<usize> = text
.grapheme_indices(true)
.map(|(ix, grapheme)| ix + grapheme.len())
.collect();
let opportunities: Vec<usize> = unicode_linebreak::linebreaks(text)
.map(|(ix, _)| ix)
.filter(|ix| ends.binary_search(ix).is_ok())
.collect();
let mut result = Vec::new();
let mut first = 0;
let mut start = 0;
while first < ends.len() {
let available = if start == 0 {
width
} else {
width - indent_width
};
let remaining = ends.len() - first;
let mut low = 0;
let mut high = 1;
while measure(&text[start..ends[first + high - 1]]) <= available {
low = high;
if high == remaining {
break;
}
high = (high * 2).min(remaining);
}
while low + 1 < high {
let mid = (low + high) / 2;
if measure(&text[start..ends[first + mid - 1]]) <= available {
low = mid;
} else {
high = mid;
}
}
let fitting_end = ends[first + low.max(1) - 1];
if fitting_end == text.len() {
break;
}
let candidate = opportunities.partition_point(|&ix| ix <= fitting_end);
let end = candidate
.checked_sub(1)
.map(|ix| opportunities[ix])
.filter(|&ix| ix > start && (start != 0 || ix > indent))
.unwrap_or(fitting_end);
result.push(gpui::Boundary {
ix: end,
next_indent: indent as u32,
});
first = ends.partition_point(|&ix| ix <= end);
start = end;
}
result
}
fn monospace_wrap(
text: &str,
width: Pixels,
wrapping_indent: WrappingIndent,
scratch: &mut WrapScratch,
widths: &MonospaceWidths,
mut shaped: impl FnMut(&str) -> Pixels,
) -> MeasuredWrap {
if text.is_empty() {
return MeasuredWrap::unbroken(WidthRange::all());
}
if let Some(line_width) = widths.width(text.len())
&& line_width <= width
{
let mut valid_widths = WidthRange::all();
valid_widths.fits(line_width, width, px(0.));
return MeasuredWrap::unbroken(valid_widths);
}
measured_wrap(text, width, wrapping_indent, scratch, |text| {
widths.width(text.len()).unwrap_or_else(|| shaped(text))
})
}
fn fast_wrap(
text: &str,
width: Pixels,
wrapping_indent: WrappingIndent,
scratch: &mut WrapScratch,
widths: &LineWidths<'_>,
) -> MeasuredWrap {
let line_width = widths.width(0..text.len());
if line_width <= width {
let mut valid_widths = WidthRange::all();
valid_widths.fits(line_width, width, px(0.));
return MeasuredWrap::unbroken(valid_widths);
}
measured_wrap_ranges(text, width, wrapping_indent, scratch, |range| {
widths.width(range)
})
}
fn measured_wrap(
text: &str,
width: Pixels,
wrapping_indent: WrappingIndent,
scratch: &mut WrapScratch,
mut measure: impl FnMut(&str) -> Pixels,
) -> MeasuredWrap {
measured_wrap_ranges(text, width, wrapping_indent, scratch, |range| {
measure(&text[range])
})
}
fn measured_wrap_ranges(
text: &str,
width: Pixels,
wrapping_indent: WrappingIndent,
scratch: &mut WrapScratch,
mut measure: impl FnMut(Range<usize>) -> Pixels,
) -> MeasuredWrap {
#[cfg(test)]
wrap_width::MEASURED_LINES.with(|count| count.set(count.get() + 1));
let mut valid_widths = WidthRange::all();
let indent = if wrapping_indent == WrappingIndent::Same {
text.chars()
.take_while(|&c| c == ' ')
.count()
.min(gpui::LineWrapper::MAX_INDENT as usize)
} else {
0
};
let indent_width = measure(0..indent);
let WrapScratch {
ends,
opportunities,
} = scratch;
let ends = GraphemeEnds::new(text, ends);
opportunities.clear();
opportunities.extend(
unicode_linebreak::linebreaks(text)
.map(|(ix, _)| ix)
.filter(|&ix| ends.contains(ix)),
);
let opportunities = opportunities.as_slice();
let mut result = Vec::new();
let mut first = 0;
let mut start = 0;
while first < ends.len() {
let available = if start == 0 {
width
} else {
width - indent_width
};
const MAX_WORD_PROBE_GRAPHEMES: usize = 256;
let word_probe_end = if first + MAX_WORD_PROBE_GRAPHEMES <= ends.len() {
ends.get(first + MAX_WORD_PROBE_GRAPHEMES - 1)
} else {
text.len()
};
let mut fits = |end: usize, limit: Option<usize>| {
if limit.is_some_and(|limit| end > limit) {
return None;
}
Some(valid_widths.fits(
measure(start..end),
available,
if start == 0 { px(0.) } else { indent_width },
))
};
let first_word =
opportunities.partition_point(|&ix| ix <= start || (start == 0 && ix <= indent));
let words = &opportunities[first_word..];
let end = if let Some(word_count) =
fitting_count(words.len(), |ix| fits(words[ix], Some(word_probe_end)))
&& word_count > 0
{
words[word_count - 1]
} else {
let count =
fitting_count(ends.len() - first, |ix| fits(ends.get(first + ix), None)).unwrap();
let fitting_end = ends.get(first + count.max(1) - 1);
if fitting_end == text.len() {
break;
}
let word_count = words.partition_point(|&ix| ix <= fitting_end);
word_count
.checked_sub(1)
.map(|ix| words[ix])
.unwrap_or(fitting_end)
};
if end == text.len() {
break;
}
result.push(gpui::Boundary {
ix: end,
next_indent: indent as u32,
});
first = ends.count_through(end);
start = end;
}
MeasuredWrap {
boundaries: result,
valid_widths,
}
}
fn fitting_count(count: usize, mut fits: impl FnMut(usize) -> Option<bool>) -> Option<usize> {
let mut low = 0;
let mut high = 1;
while high <= count && fits(high - 1)? {
low = high;
if high == count {
break;
}
high = (high * 2).min(count);
}
while low + 1 < high {
let mid = (low + high) / 2;
if fits(mid - 1)? {
low = mid;
} else {
high = mid;
}
}
Some(low)
}
#[derive(Default)]
struct WrapScratch {
ends: Vec<usize>,
opportunities: Vec<usize>,
}
impl WrapScratch {
fn release_excess(&mut self) {
const MAX_RETAINED: usize = 64 * 1024;
if self.ends.capacity() > MAX_RETAINED || self.opportunities.capacity() > MAX_RETAINED {
*self = Self::default();
}
}
}
#[derive(Clone, Copy)]
enum GraphemeEnds<'a> {
Bytes(usize),
Segmented(&'a [usize]),
}
impl<'a> GraphemeEnds<'a> {
fn new(text: &str, buffer: &'a mut Vec<usize>) -> Self {
if is_printable_ascii(text) {
return Self::Bytes(text.len());
}
buffer.clear();
buffer.extend(
text.grapheme_indices(true)
.map(|(ix, grapheme)| ix + grapheme.len()),
);
Self::Segmented(buffer.as_slice())
}
fn len(self) -> usize {
match self {
Self::Bytes(len) => len,
Self::Segmented(ends) => ends.len(),
}
}
fn get(self, index: usize) -> usize {
match self {
Self::Bytes(_) => index + 1,
Self::Segmented(ends) => ends[index],
}
}
fn count_through(self, offset: usize) -> usize {
match self {
Self::Bytes(len) => offset.min(len),
Self::Segmented(ends) => ends.partition_point(|&ix| ix <= offset),
}
}
fn contains(self, offset: usize) -> bool {
match self {
Self::Bytes(len) => (1..=len).contains(&offset),
Self::Segmented(ends) => ends.binary_search(&offset).is_ok(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Reuse {
Nothing,
Widths,
Measurements,
}
const ROWS_PER_STALE_ROW: usize = 64;
#[derive(Debug, Clone)]
pub(crate) struct LineItem {
len: usize,
pub(crate) indent: u32,
pub(crate) wrapped_lines: SmallVec<[Range<usize>; 1]>,
valid_widths: WidthRange,
}
impl LineItem {
#[inline]
pub(crate) fn len(&self) -> usize {
self.len
}
#[inline]
pub(crate) fn lines_len(&self) -> usize {
self.wrapped_lines.len()
}
}
#[derive(Debug, Clone)]
pub(crate) struct LineSummary {
buffer_rows: usize,
wrap_rows: usize,
bytes: usize,
max_line_len: usize,
longest_row: usize,
valid_widths: WidthRange,
}
impl sum_tree::Summary for LineSummary {
type Context<'a> = &'a ();
fn zero(_: &()) -> Self {
LineSummary {
buffer_rows: 0,
wrap_rows: 0,
bytes: 0,
max_line_len: 0,
longest_row: 0,
valid_widths: WidthRange::all(),
}
}
fn add_summary(&mut self, other: &Self, _: &()) {
if other.max_line_len > self.max_line_len {
self.longest_row = self.buffer_rows + other.longest_row;
self.max_line_len = other.max_line_len;
}
self.buffer_rows += other.buffer_rows;
self.wrap_rows += other.wrap_rows;
self.bytes += other.bytes;
self.valid_widths.intersect(other.valid_widths);
}
}
impl sum_tree::Item for LineItem {
type Summary = LineSummary;
fn summary(&self, _: &()) -> LineSummary {
LineSummary {
buffer_rows: 1,
wrap_rows: self.lines_len(),
bytes: self.len(),
max_line_len: self.len(),
longest_row: 0,
valid_widths: self.valid_widths,
}
}
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct BufferRows(pub usize);
impl<'a> sum_tree::Dimension<'a, LineSummary> for BufferRows {
fn zero(_: &()) -> Self {
BufferRows(0)
}
fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
self.0 += summary.buffer_rows;
}
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct WrapRows(pub usize);
impl<'a> sum_tree::Dimension<'a, LineSummary> for WrapRows {
fn zero(_: &()) -> Self {
WrapRows(0)
}
fn add_summary(&mut self, summary: &'a LineSummary, _: &()) {
self.0 += summary.wrap_rows;
}
}
pub(crate) struct TextWrapper {
text: Rope,
font: Font,
font_size: Pixels,
wrap_width: Option<Pixels>,
wrapping_indent: WrappingIndent,
tab_size: usize,
pub(crate) lines: SumTree<LineItem>,
inline_metrics: Rc<[(Range<usize>, Pixels)]>,
width_measurements: Rc<std::cell::RefCell<WidthMeasurements>>,
monospace: Option<Option<Rc<MonospaceWidths>>>,
scratch: WrapScratch,
char_widths: CharWidths,
#[cfg(test)]
fast_non_ascii: bool,
_initialized: bool,
}
#[allow(unused)]
impl TextWrapper {
pub(crate) fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
Self {
text: Rope::new(),
font,
font_size,
wrap_width,
wrapping_indent: WrappingIndent::default(),
tab_size: TabSize::default().tab_size,
lines: SumTree::new(&()),
inline_metrics: Rc::from([]),
width_measurements: Rc::default(),
monospace: None,
scratch: WrapScratch::default(),
char_widths: CharWidths::default(),
#[cfg(test)]
fast_non_ascii: true,
_initialized: false,
}
}
#[inline]
pub(crate) fn is_prepared(&self) -> bool {
self._initialized
}
#[inline]
pub(crate) fn set_default_text(&mut self, text: &Rope) {
self.text = text.clone();
}
#[inline]
pub(crate) fn text(&self) -> &Rope {
&self.text
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.lines.summary().wrap_rows
}
#[inline]
pub(crate) fn lines_count(&self) -> usize {
self.lines.summary().buffer_rows
}
#[inline]
pub(crate) fn longest_row(&self) -> usize {
self.lines.summary().longest_row
}
#[inline]
pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
let mut cursor = self.lines.cursor::<BufferRows>(&());
cursor.seek(&BufferRows(row), Bias::Right);
cursor.item()
}
#[inline]
pub(crate) fn iter_lines(&self) -> impl Iterator<Item = &LineItem> {
self.lines.iter()
}
pub(crate) fn buffer_line_to_first_wrap_row(&self, row: usize) -> usize {
let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
cursor.seek(&BufferRows(row), Bias::Right);
cursor.start().1.0
}
pub(crate) fn buffer_line_to_wrap_row_range(&self, row: usize) -> Range<usize> {
let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
cursor.seek(&BufferRows(row), Bias::Right);
let start = cursor.start().1.0;
let len = cursor.item().map(|l| l.lines_len()).unwrap_or(0);
start..start + len
}
pub(crate) fn wrap_row_to_buffer_line(&self, wrap_row: usize) -> usize {
let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
cursor.seek(&WrapRows(wrap_row), Bias::Right);
match cursor.item() {
Some(_) => cursor.start().1.0,
None => self.lines_count().saturating_sub(1),
}
}
pub(crate) fn wrap_width(&self) -> Option<Pixels> {
self.wrap_width
}
pub(crate) fn font(&self) -> (&Font, Pixels) {
(&self.font, self.font_size)
}
pub(crate) fn prepare_wrap_width(&mut self, wrap_width: Pixels) {
if self.wrap_width.is_some() {
self.wrap_width = Some(wrap_width);
}
}
pub(crate) fn set_wrap_width(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
if wrap_width == self.wrap_width {
return;
}
let width_only = self.wrap_width.is_some() && wrap_width.is_some();
self.wrap_width = wrap_width;
let text = self.text.clone();
let Some(width) = wrap_width.filter(|_| width_only) else {
self.update_wrapped(&text, &(0..text.len()), &text, Reuse::Nothing, cx);
return;
};
if self.lines.summary().valid_widths.contains(width) {
return;
}
match self.stale_rows(width) {
Some(stale_rows) => {
let edits: Vec<(Range<usize>, Rope)> = stale_rows
.into_iter()
.map(|rows| {
let range =
text.line_start_offset(rows.start)..text.line_end_offset(rows.end - 1);
let new_text = Rope::from(text.slice(range.clone()));
(range, new_text)
})
.collect();
self.update_wrapped_ranges(&text, &edits, Reuse::Measurements, cx);
}
None => self.update_wrapped(&text, &(0..text.len()), &text, Reuse::Widths, cx),
}
}
fn stale_rows(&self, wrap_width: Pixels) -> Option<Vec<Range<usize>>> {
let limit = self.lines_count() / ROWS_PER_STALE_ROW;
let mut runs: Vec<Range<usize>> = Vec::new();
let mut stale_count = 0;
let mut cursor = self
.lines
.filter::<_, BufferRows>(&(), |summary: &LineSummary| {
!summary.valid_widths.contains(wrap_width)
});
cursor.next();
while cursor.item().is_some() {
stale_count += 1;
if stale_count > limit {
return None;
}
let row = cursor.start().0;
match runs.last_mut() {
Some(run) if run.end == row => run.end += 1,
_ => runs.push(row..row + 1),
}
cursor.next();
}
Some(runs)
}
pub(crate) fn set_wrapping_indent(&mut self, wrapping_indent: WrappingIndent, cx: &mut App) {
if wrapping_indent == self.wrapping_indent {
return;
}
self.wrapping_indent = wrapping_indent;
self.update_all(&self.text.clone(), cx);
}
pub(crate) fn set_tab_size(&mut self, tab_size: usize, cx: &mut App) -> bool {
if tab_size == self.tab_size {
return false;
}
self.tab_size = tab_size;
self.char_widths.clear();
self.update_all(&self.text.clone(), cx);
true
}
#[cfg(test)]
pub(super) fn set_fast_non_ascii(&mut self, enabled: bool) {
self.fast_non_ascii = enabled;
}
pub(crate) fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
if self.font.eq(&font) && self.font_size == font_size {
return;
}
self.font = font;
self.font_size = font_size;
self.monospace = None;
self.char_widths.clear();
self.update_all(&self.text.clone(), cx);
}
pub(crate) fn prepare_if_need(&mut self, text: &Rope, cx: &mut App) -> bool {
if self._initialized {
return false;
}
self._initialized = true;
self.update_all(text, cx);
true
}
pub(crate) fn update(
&mut self,
changed_text: &Rope,
range: &Range<usize>,
new_text: &Rope,
cx: &mut App,
) {
self.update_wrapped(changed_text, range, new_text, Reuse::Nothing, cx);
}
fn update_wrapped(
&mut self,
changed_text: &Rope,
range: &Range<usize>,
new_text: &Rope,
reuse: Reuse,
cx: &mut App,
) {
self.update_wrapped_ranges(
changed_text,
&[(range.clone(), new_text.clone())],
reuse,
cx,
);
}
fn update_wrapped_ranges(
&mut self,
changed_text: &Rope,
edits: &[(Range<usize>, Rope)],
reuse: Reuse,
cx: &mut App,
) {
debug_assert!(reuse != Reuse::Widths || edits.len() == 1);
let mut line_wrapper = cx
.text_system()
.line_wrapper(self.font.clone(), self.font_size);
let metrics = self.inline_metrics.clone();
let measurements = self.width_measurements.clone();
if reuse == Reuse::Nothing {
measurements.borrow_mut().clear();
}
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
let font = self.font.clone();
let font_size = self.font_size;
let wrapping_indent = self.wrapping_indent;
let tab_stop = tab_stop_width(&text_system, &font, font_size, self.tab_size);
let layout = |text: &str| {
text_system.layout_line(
text,
font_size,
&[gpui::TextRun {
len: text.len(),
font: font.clone(),
color: gpui::black(),
background_color: None,
underline: None,
strikethrough: None,
}],
None,
)
};
let shaped = |text: &str| expanded_width(&layout(text), text, tab_stop);
let cached = |text: &str| measurements.borrow_mut().measure(text, || shaped(text));
let glyph_starts = |text: &str| {
let layout = layout(text);
let glyphs = layout.runs.iter().flat_map(|run| &run.glyphs);
let mut starts: Vec<Pixels> = glyphs.map(|glyph| glyph.position.x).collect();
starts.push(layout.width);
starts
};
let monospace = if self.wrap_width.is_some() {
if self.monospace.is_none() {
self.monospace = Some(MonospaceWidths::cached(
&font,
font_size,
glyph_starts,
shaped,
cx,
));
}
self.monospace.clone().flatten()
} else {
None
};
let mut scratch = std::mem::take(&mut self.scratch);
let mut char_widths = std::mem::take(&mut self.char_widths);
#[cfg(test)]
let fast_non_ascii = self.fast_non_ascii;
let mut wrap_line = |line_str: &str, wrap_width: Pixels, line_start: usize| {
let mut fragments = Vec::new();
let mut offset = 0;
let first = metrics.partition_point(|(r, _)| r.end <= line_start);
for (range, width) in &metrics[first..] {
if range.start >= line_start + line_str.len() {
break;
}
if range.start < line_start || range.end > line_start + line_str.len() {
continue;
}
let range = range.start - line_start..range.end - line_start;
if !line_str.is_char_boundary(range.start) || !line_str.is_char_boundary(range.end)
{
continue;
}
if offset < range.start {
fragments.push(LineFragment::text(&line_str[offset..range.start]));
}
fragments.push(LineFragment::element(*width, range.len()));
offset = range.end;
}
if fragments.is_empty() {
if let Some(monospace) = &monospace
&& is_printable_ascii(line_str)
{
return monospace_wrap(
line_str,
wrap_width,
wrapping_indent,
&mut scratch,
monospace,
cached,
);
}
#[cfg(test)]
let fast = fast_non_ascii;
#[cfg(not(test))]
let fast = true;
if fast
&& let Some(monospace) = &monospace
&& let Some(widths) = char_widths.line_widths(
line_str,
monospace,
tab_stop,
&mut |text: &str| shaped(text),
&mut |text: &str| glyph_starts(text),
)
{
return fast_wrap(line_str, wrap_width, wrapping_indent, &mut scratch, &widths);
}
return measured_wrap(line_str, wrap_width, wrapping_indent, &mut scratch, cached);
}
if offset < line_str.len() {
fragments.push(LineFragment::text(&line_str[offset..]));
}
MeasuredWrap::uncached(
line_wrapper
.wrap_line(&fragments, wrap_width, gpui::IndentAdjustment::SameIndent)
.collect(),
)
};
for (range, new_text) in edits {
self.update_lines(
changed_text,
range,
new_text,
reuse == Reuse::Widths,
&mut wrap_line,
);
}
drop(wrap_line);
scratch.release_excess();
self.scratch = scratch;
char_widths.release_excess();
self.char_widths = char_widths;
}
pub(crate) fn adjust_inline_metrics(&mut self, range: &Range<usize>, new_len: usize) {
if self.inline_metrics.is_empty() {
return;
}
let shift = new_len as isize - range.len() as isize;
self.inline_metrics = self
.inline_metrics
.iter()
.filter_map(|(token, width)| {
if token.start < range.end && range.start < token.end {
return None;
}
let token = if token.start >= range.end {
token.start.checked_add_signed(shift)?..token.end.checked_add_signed(shift)?
} else {
token.clone()
};
Some((token, *width))
})
.collect();
}
pub(crate) fn set_inline_metrics(
&mut self,
metrics: Rc<[(Range<usize>, Pixels)]>,
cx: &mut App,
) {
if self.inline_metrics == metrics {
return;
}
let mut affected = Vec::new();
let (mut old, mut new) = (
self.inline_metrics.iter().peekable(),
metrics.iter().peekable(),
);
while old.peek().is_some() || new.peek().is_some() {
match (old.peek(), new.peek()) {
(Some(a), Some(b)) if a == b => {
old.next();
new.next();
}
(Some(a), Some(b)) if a.0.start <= b.0.start => {
affected.push(a.0.clone());
old.next();
}
(Some(_), Some(b)) | (None, Some(b)) => {
affected.push(b.0.clone());
new.next();
}
(Some(a), None) => {
affected.push(a.0.clone());
old.next();
}
(None, None) => break,
}
}
self.inline_metrics = metrics;
let text = self.text.clone();
let mut rows: Vec<usize> = affected
.iter()
.map(|r| text.offset_to_point(r.start.min(text.len())).row)
.collect();
rows.sort_unstable();
rows.dedup();
for row in rows {
let start = text.line_start_offset(row);
let end = text.line_end_offset(row);
self.update(
&text,
&(start..end),
&Rope::from(text.slice(start..end).to_string()),
cx,
);
}
}
#[cfg(test)]
fn _update<F>(
&mut self,
changed_text: &Rope,
range: &Range<usize>,
new_text: &Rope,
wrap_line: &mut F,
) where
F: FnMut(&str, Pixels, usize) -> Vec<gpui::Boundary>,
{
self.update_lines(
changed_text,
range,
new_text,
false,
&mut |text, width, start| MeasuredWrap::uncached(wrap_line(text, width, start)),
);
}
fn update_lines<F>(
&mut self,
changed_text: &Rope,
range: &Range<usize>,
new_text: &Rope,
reuse_rows: bool,
wrap_line: &mut F,
) where
F: FnMut(&str, Pixels, usize) -> MeasuredWrap,
{
let buffer_line_count = self.lines_count();
let start_row = self.text.offset_to_point(range.start).row;
let start_row = start_row.min(buffer_line_count.saturating_sub(1));
let end_row = self.text.offset_to_point(range.end).row;
let end_row = end_row.min(buffer_line_count.saturating_sub(1));
let new_start_row = changed_text.offset_to_point(range.start).row;
let new_end_row = changed_text
.offset_to_point(range.start + new_text.len())
.row;
let mut new_lines = Vec::with_capacity(new_end_row.saturating_sub(new_start_row) + 1);
let wrap_width = self.wrap_width;
let mut previous = self.lines.iter();
debug_assert!(!reuse_rows || (new_start_row == 0 && range == &(0..self.text.len())));
let mut lines = LinesFrom::new(changed_text, new_start_row);
for _ in new_start_row..=new_end_row {
let (line_start, line_str) = lines
.next()
.unwrap_or((changed_text.len(), Cow::Borrowed("")));
if reuse_rows {
if let Some(previous) = previous.next()
&& wrap_width.is_some_and(|width| previous.valid_widths.contains(width))
{
new_lines.push(previous.clone());
continue;
}
}
let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();
let mut prev_boundary_ix = 0;
let mut indent_chars = 0;
let mut valid_widths = WidthRange::all();
if let Some(wrap_width) = wrap_width {
match self.wrapping_indent {
WrappingIndent::Same => {
let measured = wrap_line(&line_str, wrap_width, line_start);
valid_widths.intersect(measured.valid_widths);
for boundary in measured.boundaries {
wrapped_lines.push(prev_boundary_ix..boundary.ix);
prev_boundary_ix = boundary.ix;
indent_chars = boundary.next_indent;
}
}
WrappingIndent::None => {
let boundaries = wrap_line(&line_str, wrap_width, line_start);
valid_widths.intersect(boundaries.valid_widths);
if let Some(first_ix) = boundaries.boundaries.first().map(|b| b.ix) {
wrapped_lines.push(prev_boundary_ix..first_ix);
prev_boundary_ix = first_ix;
let continuation =
wrap_line(&line_str[first_ix..], wrap_width, line_start + first_ix);
valid_widths.intersect(continuation.valid_widths);
for boundary in continuation.boundaries {
let ix = first_ix + boundary.ix;
wrapped_lines.push(prev_boundary_ix..ix);
prev_boundary_ix = ix;
}
}
}
}
}
if prev_boundary_ix < line_str.len() || prev_boundary_ix == 0 {
wrapped_lines.push(prev_boundary_ix..line_str.len());
}
new_lines.push(LineItem {
len: line_str.len(),
indent: indent_chars,
wrapped_lines,
valid_widths,
});
}
drop(previous);
if self.lines.is_empty() {
self.lines = SumTree::from_iter(new_lines, &());
} else {
let mut cursor = self.lines.cursor::<BufferRows>(&());
let mut new_tree = cursor.slice(&BufferRows(start_row), Bias::Right);
cursor.seek_forward(&BufferRows(end_row + 1), Bias::Right);
new_tree.extend(new_lines, &());
new_tree.append(cursor.suffix(), &());
drop(cursor);
self.lines = new_tree;
}
self.text = changed_text.clone();
}
fn update_all(&mut self, text: &Rope, cx: &mut App) {
self.update(text, &(0..text.len()), &text, cx);
}
pub(crate) fn offset_to_display_point(&self, offset: usize) -> WrapDisplayPoint {
self.offset_to_display_point_with_affinity(offset, false)
}
pub(crate) fn offset_to_display_point_with_affinity(
&self,
offset: usize,
line_end_affinity: bool,
) -> WrapDisplayPoint {
let row = self.text.offset_to_point(offset).row;
let start = self.text.line_start_offset(row);
let mut cursor = self.lines.cursor::<Dimensions<BufferRows, WrapRows>>(&());
cursor.seek(&BufferRows(row), Bias::Right);
let wrapped_row = cursor.start().1.0;
let Some(line) = cursor.item() else {
return WrapDisplayPoint::new(wrapped_row, 0, 0);
};
let local_offset = offset.saturating_sub(start);
for (ix, range) in line.wrapped_lines.iter().enumerate() {
let matches =
range.contains(&local_offset) || (line_end_affinity && local_offset == range.end);
if matches {
return WrapDisplayPoint::new(
wrapped_row + ix,
ix,
local_offset.saturating_sub(range.start),
);
}
}
let last_range = line.wrapped_lines.last().unwrap_or(&(0..0));
let ix = line.lines_len().saturating_sub(1);
return WrapDisplayPoint::new(wrapped_row + ix, ix, last_range.len());
}
pub(crate) fn display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
let mut cursor = self.lines.cursor::<Dimensions<WrapRows, BufferRows>>(&());
cursor.seek(&WrapRows(point.row), Bias::Right);
let Some(line) = cursor.item() else {
return self.text.len();
};
let wrapped_row = cursor.start().0.0;
let row = cursor.start().1.0;
let line_start = self.text.line_start_offset(row);
let local_row = point.row.saturating_sub(wrapped_row);
if let Some(range) = line.wrapped_lines.get(local_row) {
line_start + (range.start + point.column).min(range.end)
} else {
line_start + line.len()
}
}
pub(crate) fn display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
let offset = self.display_point_to_offset(point);
self.text.offset_to_point(offset)
}
pub(crate) fn point_to_display_point(&self, point: TreeSitterPoint) -> WrapDisplayPoint {
let offset = self.text.point_to_offset(point);
self.offset_to_display_point(offset)
}
}
struct LinesFrom<'a> {
chunks: ropey::iter::Chunks<'a>,
rest: &'a str,
pending: Option<String>,
offset: usize,
done: bool,
}
impl<'a> LinesFrom<'a> {
fn new(text: &'a Rope, row: usize) -> Self {
let offset = text.line_start_offset(row);
let (mut chunks, chunk_start) = text.chunks_at(offset);
let rest = chunks
.next()
.map_or("", |chunk| &chunk[offset - chunk_start..]);
Self {
chunks,
rest,
pending: None,
offset,
done: false,
}
}
}
impl<'a> Iterator for LinesFrom<'a> {
type Item = (usize, Cow<'a, str>);
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(newline) = self.rest.find('\n') {
let piece = &self.rest[..newline];
self.rest = &self.rest[newline + 1..];
return Some(self.line(piece));
}
match self.chunks.next() {
Some(chunk) => {
if !self.rest.is_empty() {
self.pending
.get_or_insert_with(String::new)
.push_str(self.rest);
}
self.rest = chunk;
}
None if !self.done => {
self.done = true;
let piece = std::mem::take(&mut self.rest);
return Some(self.line(piece));
}
None => return None,
}
}
}
}
impl<'a> LinesFrom<'a> {
fn line(&mut self, piece: &'a str) -> (usize, Cow<'a, str>) {
let line = match self.pending.take() {
Some(mut pending) => {
pending.push_str(piece);
Cow::Owned(pending)
}
None => Cow::Borrowed(piece),
};
let start = self.offset;
self.offset += line.len() + 1;
(start, line)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct WrapDisplayPoint {
pub row: usize,
pub local_row: usize,
pub column: usize,
}
impl WrapDisplayPoint {
pub(crate) fn new(row: usize, local_row: usize, column: usize) -> Self {
Self {
row,
local_row,
column,
}
}
}
pub(crate) struct LineLayout {
len: usize,
pub(crate) wrapped_lines: SmallVec<[InputLine; 1]>,
pub(crate) wrap_indent: Pixels,
pub(crate) longest_width: Pixels,
pub(crate) align: TextAlign,
pub(crate) whitespace_indicators: Option<WhitespaceIndicators>,
pub(crate) whitespace_chars: Vec<(usize, Pixels, Option<Pixels>)>,
has_background: bool,
}
impl LineLayout {
pub(crate) fn new() -> Self {
Self {
len: 0,
longest_width: px(0.),
align: TextAlign::Left,
wrapped_lines: SmallVec::new(),
wrap_indent: px(0.),
whitespace_chars: Vec::new(),
whitespace_indicators: None,
has_background: false,
}
}
pub(crate) fn with_background(mut self, has_background: bool) -> Self {
self.has_background = has_background;
self
}
pub(crate) fn wrap_indent(mut self, wrap_indent: Pixels) -> Self {
self.wrap_indent = wrap_indent;
self
}
#[inline]
fn line_indent(&self, line_index: usize) -> Pixels {
if line_index == 0 {
px(0.)
} else {
self.wrap_indent
}
}
pub(crate) fn start_align(&self) -> TextAlign {
let direction = self
.wrapped_lines
.iter()
.map(|row| unicode_bidi::get_base_direction(row.text.as_ref()))
.find(|direction| *direction != unicode_bidi::Direction::Mixed);
if direction == Some(unicode_bidi::Direction::Rtl) {
TextAlign::Right
} else {
TextAlign::Left
}
}
pub(crate) fn row_x(&self, line_index: usize, content_width: Pixels) -> Pixels {
let indent = self.line_indent(line_index);
let width = self
.wrapped_lines
.get(line_index)
.map_or(px(0.), |line| line.width);
indent
+ match self.align {
TextAlign::Left => px(0.),
TextAlign::Center => (content_width - width).half().max(px(0.)),
TextAlign::Right => (content_width - width).max(px(0.)),
}
}
pub(crate) fn lines(mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) -> Self {
self.set_wrapped_lines(wrapped_lines);
self
}
pub(crate) fn set_wrapped_lines(&mut self, wrapped_lines: SmallVec<[ShapedLine; 1]>) {
self.len = wrapped_lines.iter().map(|l| l.len).sum();
let width = wrapped_lines
.iter()
.map(|l| l.width)
.max()
.unwrap_or_default();
self.longest_width = width;
self.wrapped_lines = wrapped_lines.into_iter().map(InputLine::from).collect();
}
pub(crate) fn inline_lines(mut self, lines: SmallVec<[InputLine; 1]>) -> Self {
self.len = lines.iter().map(|line| line.len).sum();
self.longest_width = lines
.iter()
.map(|line| line.width)
.max()
.unwrap_or_default();
self.wrapped_lines = lines;
self
}
pub(crate) fn with_whitespaces(mut self, indicators: Option<WhitespaceIndicators>) -> Self {
self.whitespace_indicators = indicators;
let Some(indicators) = self.whitespace_indicators.as_ref() else {
return self;
};
let space_indicator_offset = indicators.space.width.half();
for (line_index, wrapped_line) in self.wrapped_lines.iter().enumerate() {
for (relative_offset, c) in wrapped_line.text.char_indices() {
if matches!(c, ' ' | '\t') {
let is_tab = c == '\t';
let start_x = wrapped_line.x_for_index(relative_offset);
let end_x = wrapped_line.x_for_index(relative_offset + c.len_utf8());
let x_position = if c == ' ' {
(start_x + end_x).half() - space_indicator_offset
} else {
start_x
};
self.whitespace_chars.push((
line_index,
x_position,
is_tab.then_some(end_x - start_x),
));
}
}
}
self
}
#[inline]
pub(crate) fn len(&self) -> usize {
self.len
}
pub(crate) fn position_for_index(
&self,
offset: usize,
last_layout: &LastLayout,
line_end_affinity: bool,
) -> Option<Point<Pixels>> {
let mut acc_len = 0;
let mut offset_y = px(0.);
for (i, line) in self.wrapped_lines.iter().enumerate() {
let is_last = i + 1 == self.wrapped_lines.len();
let matches = if line.len == 0 {
offset == acc_len
} else if is_last || line_end_affinity {
offset >= acc_len && offset <= acc_len + line.len
} else {
offset >= acc_len && offset < acc_len + line.len
};
if matches {
let x = line.x_for_index(offset.saturating_sub(acc_len))
+ self.row_x(i, last_layout.content_width);
return Some(point(x, offset_y));
}
acc_len += if is_last { line.len + 1 } else { line.len };
offset_y += last_layout.line_height;
}
None
}
pub(crate) fn closest_index_for_x(&self, x: Pixels, last_layout: &LastLayout) -> usize {
let mut acc_len = 0;
for (i, line) in self.wrapped_lines.iter().enumerate() {
let x = x - self.row_x(i, last_layout.content_width);
if x <= line.width {
return acc_len + line.closest_index_for_x(x);
}
acc_len += line.len;
}
acc_len
}
fn wrapped_line_at(
&self,
pos: Point<Pixels>,
last_layout: &LastLayout,
) -> Option<(usize, usize, Pixels)> {
let mut offset = 0;
let mut line_top = px(0.);
for (i, line) in self.wrapped_lines.iter().enumerate() {
let line_bottom = line_top + last_layout.line_height;
if pos.y >= line_top && pos.y < line_bottom {
return Some((i, offset, pos.x - self.row_x(i, last_layout.content_width)));
}
offset += line.len;
line_top = line_bottom;
}
None
}
pub(crate) fn closest_index_for_position(
&self,
pos: Point<Pixels>,
last_layout: &LastLayout,
) -> Option<(usize, bool)> {
let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
let line = &self.wrapped_lines[i];
let ix = line.closest_index_for_x(x);
let line_end_affinity = i + 1 < self.wrapped_lines.len() && ix == line.len;
Some((offset + ix, line_end_affinity))
}
pub(crate) fn columns_past_line_end(
&self,
pos: Point<Pixels>,
last_layout: &LastLayout,
) -> usize {
let Some((i, _, x)) = self.wrapped_line_at(pos, last_layout) else {
return 0;
};
if i + 1 < self.wrapped_lines.len() || last_layout.space_width <= px(0.) {
return 0;
}
let past_end = x - self.wrapped_lines[i].width;
if past_end <= px(0.) {
return 0;
}
(past_end / last_layout.space_width).round() as usize
}
pub(crate) fn index_for_position(
&self,
pos: Point<Pixels>,
last_layout: &LastLayout,
) -> Option<usize> {
let (i, offset, x) = self.wrapped_line_at(pos, last_layout)?;
Some(offset + self.wrapped_lines[i].index_for_x(x)?)
}
pub(crate) fn size(&self, line_height: Pixels) -> Size<Pixels> {
let width = self
.wrapped_lines
.iter()
.enumerate()
.map(|(ix, line)| line.width + self.line_indent(ix))
.max()
.unwrap_or(self.longest_width);
size(width, self.wrapped_lines.len() * line_height)
}
pub(crate) fn paint_background(
&self,
pos: Point<Pixels>,
line_height: Pixels,
content_width: Pixels,
window: &mut Window,
cx: &mut App,
) {
if !self.has_background {
return;
}
for (ix, line) in self.wrapped_lines.iter().enumerate() {
_ = line.paint_background(
pos + point(self.row_x(ix, content_width), ix * line_height),
line_height,
TextAlign::Left,
None,
window,
cx,
);
}
}
pub(crate) fn paint(
&self,
pos: Point<Pixels>,
line_height: Pixels,
content_width: Pixels,
window: &mut Window,
cx: &mut App,
) {
for (ix, line) in self.wrapped_lines.iter().enumerate() {
_ = line.paint(
pos + point(self.row_x(ix, content_width), ix * line_height),
line_height,
TextAlign::Left,
None,
window,
cx,
);
}
if let Some(indicators) = self.whitespace_indicators.as_ref() {
for (line_index, x_position, tab_width) in &self.whitespace_chars {
let origin = point(
pos.x + *x_position + self.row_x(*line_index, content_width),
pos.y + *line_index as f32 * line_height,
);
match tab_width {
Some(tab_width) => {
let tab_cell = ContentMask {
bounds: Bounds::new(origin, size(*tab_width, line_height)),
};
window.with_content_mask(Some(tab_cell), |window| {
_ = indicators.tab.paint(
origin,
line_height,
TextAlign::Left,
None,
window,
cx,
);
});
}
None => {
_ = indicators.space.paint(
origin,
line_height,
TextAlign::Left,
None,
window,
cx,
);
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::rc::Rc;
#[cfg(target_os = "linux")]
use gpui::TestAppContext;
use gpui::{Boundary, FontFeatures, FontStyle, FontWeight, px};
#[cfg(target_os = "linux")]
fn shaped_width(text: &str, font: &Font, font_size: Pixels, cx: &App) -> Pixels {
gpui::WindowTextSystem::new(cx.text_system().clone())
.layout_line(
text,
font_size,
&[gpui::TextRun {
len: text.len(),
font: font.clone(),
color: gpui::black(),
background_color: None,
underline: None,
strikethrough: None,
}],
None,
)
.width
}
#[cfg(target_os = "linux")]
fn shaping_test_context() -> TestAppContext {
let platform = gpui_platform::current_platform(true);
TestAppContext::build_with_text_system(
gpui::TestDispatcher::new(0),
None,
platform.text_system(),
)
}
#[cfg(target_os = "linux")]
#[test]
fn production_wrap_keeps_shaped_cjk_latin_boundary_during_edits() {
let cx = shaping_test_context();
cx.update(|cx| {
let font = test_font();
let font_size = px(14.);
let prefix = "abcd的";
let width = shaped_width(prefix, &font, font_size, cx);
assert!(shaped_width("abcd的s", &font, font_size, cx) > width);
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
let mut previous = Rope::new();
for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
let text = Rope::from(value);
let start = previous.len().min(text.len());
let inserted = Rope::from(text.slice(start..).to_string());
wrapper.update(&text, &(start..previous.len()), &inserted, cx);
let expected = if value.ends_with('s') {
vec![0..prefix.len(), prefix.len()..value.len()]
} else {
vec![0..prefix.len()]
};
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
for range in &wrapper.line(0).unwrap().wrapped_lines {
assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
}
assert_eq!(
wrapper.offset_to_display_point(value.len()).row,
usize::from(value.ends_with('s'))
);
previous = text;
}
});
}
#[cfg(target_os = "linux")]
#[test]
fn production_wrap_preserves_words_and_complete_graphemes() {
let cx = shaping_test_context();
cx.update(|cx| {
let font = test_font();
let font_size = px(14.);
for (value, prefix) in [("hello world", "hello "), ("a👩💻b", "a👩💻")] {
let width = shaped_width(prefix, &font, font_size, cx).max(shaped_width(
&value[prefix.len()..],
&font,
font_size,
cx,
));
assert!(shaped_width(value, &font, font_size, cx) > width);
let text = Rope::from(value);
let mut wrapper = TextWrapper::new(font.clone(), font_size, Some(width));
wrapper.update(&text, &(0..0), &text, cx);
assert_eq!(
wrapper.line(0).unwrap().wrapped_lines.as_slice(),
[0..prefix.len(), prefix.len()..value.len()]
);
for range in &wrapper.line(0).unwrap().wrapped_lines {
assert!(shaped_width(&value[range.clone()], &font, font_size, cx) <= width);
}
}
});
}
#[test]
fn measured_wrap_keeps_cjk_latin_boundary_stable_during_edits() {
let measure = |text: &str| {
px(text
.chars()
.map(|c| if c.is_ascii() { 1. } else { 2. })
.sum())
};
let mut wrapper = TextWrapper::new(gpui::font("Arial"), px(14.), Some(px(6.)));
let mut previous = Rope::new();
for value in ["abcd的", "abcd的s", "abcd的ss", "abcd的s", "abcd的"] {
let text = Rope::from(value);
let start = previous.len().min(text.len());
let inserted = Rope::from(text.slice(start..).to_string());
wrapper._update(
&text,
&(start..previous.len()),
&inserted,
&mut |line, width, _| {
measured_wrap_boundaries(line, width, WrappingIndent::None, measure)
},
);
let expected = if value.ends_with('s') {
vec![0..7, 7..value.len()]
} else {
vec![0..7]
};
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), expected);
let cursor = wrapper.offset_to_display_point(value.len());
assert_eq!(cursor.row, usize::from(value.ends_with('s')));
previous = text;
}
}
#[test]
fn measured_wrap_preserves_words_graphemes_and_indentation() {
let wrap = |text: &str, width, indent| {
measured_wrap_boundaries(text, px(width), indent, |s| {
px(s.graphemes(true).count() as f32)
})
.into_iter()
.map(|b| b.ix)
.collect::<Vec<_>>()
};
assert_eq!(wrap("hello world", 8., WrappingIndent::None), vec![6]);
assert_eq!(wrap("a👩💻b", 2., WrappingIndent::None), vec!["a👩💻".len()]);
assert_eq!(wrap(" abcdefgh", 5., WrappingIndent::Same), vec![5, 8]);
assert_eq!(wrap(" abcdefgh", 5., WrappingIndent::None), vec![2, 7]);
assert!(wrap("", 0., WrappingIndent::None).is_empty());
assert_eq!(wrap("abc", 0., WrappingIndent::None), vec![1, 2]);
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);
}
#[test]
fn rope_lines_walk_matches_line_lookups() {
let long = "x".repeat(5000);
let texts = [
String::new(),
"\n".into(),
"a\n\nb".into(),
"Hello, 世界!\r\nsecond\nthird\n".into(),
format!("{long}\n{long}é{long}\n\n中{long}"),
format!("{long}\n").repeat(40),
];
for text in texts {
let rope = Rope::from(text.as_str());
for row in 0..rope.lines_len() {
let walked: Vec<(usize, String)> = LinesFrom::new(&rope, row)
.map(|(start, line)| (start, line.into_owned()))
.collect();
let looked_up: Vec<(usize, String)> = (row..rope.lines_len())
.map(|row| {
(
rope.line_start_offset(row),
rope.slice_line(row).to_string(),
)
})
.collect();
assert_eq!(walked, looked_up, "{text:?} from row {row}");
}
}
}
#[test]
fn test_update() {
let font = gpui::Font {
family: "Arial".into(),
weight: FontWeight::default(),
style: FontStyle::Normal,
features: FontFeatures::default(),
fallbacks: None,
};
let mut wrapper = TextWrapper::new(font, px(14.), None);
let mut text = Rope::from(
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
);
fn fake_wrap_line(_line: &str, _wrap_width: Pixels, _: usize) -> Vec<Boundary> {
vec![]
}
#[track_caller]
fn assert_wrapper_lines(text: &Rope, wrapper: &TextWrapper, expected_lines: &[&[&str]]) {
let mut actual_lines = vec![];
let mut offset = 0;
for line in wrapper.iter_lines() {
actual_lines.push(
line.wrapped_lines
.iter()
.map(|range| text.slice(offset + range.start..offset + range.end))
.collect::<Vec<_>>(),
);
offset += line.len() + 1;
}
assert_eq!(actual_lines, expected_lines);
}
wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
assert_eq!(wrapper.lines_count(), 4);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["Hello, 世界!\r"],
&["This is second line."],
&["This is third line."],
&["这里是第 4 行。"],
],
);
let range = text.len()..text.len();
let new_text = "New text";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
);
assert_eq!(wrapper.lines_count(), 4);
assert_eq!(wrapper.lines_count(), 4);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["Hello, 世界!\r"],
&["This is second line."],
&["This is third line."],
&["这里是第 4 行。New text"],
],
);
let range = 0..5;
let new_text = "AAA";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"AAA, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。New text"
);
assert_eq!(wrapper.lines_count(), 4);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["AAA, 世界!\r"],
&["This is second line."],
&["This is third line."],
&["这里是第 4 行。New text"],
],
);
let start_offset = text.line_start_offset(1);
let end_offset = text.line_end_offset(1);
let range = start_offset..end_offset + 1;
text.replace(range.clone(), "");
wrapper._update(&text, &range, &Rope::from(""), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"AAA, 世界!\r\nThis is third line.\n这里是第 4 行。New text"
);
assert_eq!(wrapper.lines_count(), 3);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["AAA, 世界!\r"],
&["This is third line."],
&["这里是第 4 行。New text"],
],
);
let range = text.line_start_offset(0)..text.line_end_offset(1) + 1;
let new_text = "This is a new line.\nThis is new line 2.\n";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"This is a new line.\nThis is new line 2.\n这里是第 4 行。New text"
);
assert_eq!(wrapper.lines_count(), 3);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["This is a new line."],
&["This is new line 2."],
&["这里是第 4 行。New text"],
],
);
let range = text.len()..text.len();
let new_text = "\nThis is a new line at the end.";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"This is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
);
assert_eq!(wrapper.lines_count(), 4);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["This is a new line."],
&["This is new line 2."],
&["这里是第 4 行。New text"],
&["This is a new line at the end."],
],
);
let range = 0..0;
let new_text = "This is a new line at the beginning.\n";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"This is a new line at the beginning.\nThis is a new line.\nThis is new line 2.\n这里是第 4 行。New text\nThis is a new line at the end."
);
assert_eq!(wrapper.lines_count(), 5);
assert_wrapper_lines(
&text,
&wrapper,
&[
&["This is a new line at the beginning."],
&["This is a new line."],
&["This is new line 2."],
&["这里是第 4 行。New text"],
&["This is a new line at the end."],
],
);
let range = 0..text.len();
let new_text = "";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(text.to_string(), "");
assert_eq!(wrapper.lines_count(), 1);
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
let range = 0..text.len();
let new_text = "This is a full text.\nThis is a second line.";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &text, &mut fake_wrap_line);
assert_eq!(
text.to_string(),
"This is a full text.\nThis is a second line."
);
assert_eq!(wrapper.lines_count(), 2);
}
fn test_font() -> gpui::Font {
gpui::Font {
family: "Arial".into(),
weight: FontWeight::default(),
style: FontStyle::Normal,
features: FontFeatures::default(),
fallbacks: None,
}
}
#[test]
fn test_longest_row_after_shrink() {
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
let mut text = Rope::from("aa\nthis is the longest line\nbb");
wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
assert_eq!(wrapper.longest_row(), 1);
let start = text.line_start_offset(0);
let end = text.line_end_offset(0);
let range = start..end;
let new_text = "a very very long first line now";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
assert_eq!(wrapper.longest_row(), 0);
}
#[test]
fn test_edit_last_line_and_full_delete() {
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
let mut text = Rope::from("one\ntwo\nthree");
wrapper._update(&text, &(0..text.len()), &text, &mut |_, _, _| vec![]);
assert_eq!(wrapper.lines_count(), 3);
let start = text.line_start_offset(2);
let range = start..text.len();
let new_text = "THREE EDITED";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut |_, _, _| vec![]);
assert_eq!(wrapper.lines_count(), 3);
assert_eq!(wrapper.line(2).unwrap().len(), "THREE EDITED".len());
let range = 0..text.len();
text.replace(range.clone(), "");
wrapper._update(&text, &range, &Rope::from(""), &mut |_, _, _| vec![]);
assert_eq!(wrapper.lines_count(), 1);
assert_eq!(wrapper.len(), 1);
assert_eq!(wrapper.line(0).unwrap().wrapped_lines.as_slice(), [0..0]);
}
#[test]
fn test_wrap_row_buffer_line_boundaries() {
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
wrapper.text = Rope::from("aa\nbbbb\nc");
wrapper.lines = SumTree::from_iter(
vec![
LineItem {
len: 2,
indent: 0,
wrapped_lines: smallvec::smallvec![0..2],
valid_widths: WidthRange::empty(),
},
LineItem {
len: 4,
indent: 0,
wrapped_lines: smallvec::smallvec![0..2, 2..4],
valid_widths: WidthRange::empty(),
},
LineItem {
len: 1,
indent: 0,
wrapped_lines: smallvec::smallvec![0..1],
valid_widths: WidthRange::empty(),
},
],
&(),
);
assert_eq!(wrapper.lines_count(), 3);
assert_eq!(wrapper.len(), 4);
assert_eq!(wrapper.buffer_line_to_first_wrap_row(0), 0);
assert_eq!(wrapper.buffer_line_to_first_wrap_row(1), 1);
assert_eq!(wrapper.buffer_line_to_first_wrap_row(2), 3);
assert_eq!(wrapper.buffer_line_to_first_wrap_row(3), 4);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..4);
assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
assert_eq!(wrapper.wrap_row_to_buffer_line(2), 1);
assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
assert_eq!(wrapper.wrap_row_to_buffer_line(4), 2);
}
#[test]
fn test_wrap_row_queries_after_incremental_splice() {
let mut wrapper = TextWrapper::new(test_font(), px(14.), Some(px(10.)));
let mut text = Rope::from("aa\nbbbb\nc");
let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
if line.len() > 2 {
vec![Boundary {
ix: 2,
next_indent: 0,
}]
} else {
vec![]
}
};
wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..3);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 3..4);
let range = text.line_start_offset(1)..text.line_end_offset(1);
let new_text = "dd\neeee";
text.replace(range.clone(), new_text);
wrapper._update(&text, &range, &Rope::from(new_text), &mut fake_wrap_line);
assert_eq!(wrapper.lines_count(), 4);
assert_eq!(wrapper.len(), 5);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(0), 0..1);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(1), 1..2);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(2), 2..4);
assert_eq!(wrapper.buffer_line_to_wrap_row_range(3), 4..5);
assert_eq!(wrapper.wrap_row_to_buffer_line(0), 0);
assert_eq!(wrapper.wrap_row_to_buffer_line(1), 1);
assert_eq!(wrapper.wrap_row_to_buffer_line(2), 2);
assert_eq!(wrapper.wrap_row_to_buffer_line(3), 2);
assert_eq!(wrapper.wrap_row_to_buffer_line(4), 3);
}
#[test]
fn test_line_layout() {
let mut line_layout = LineLayout::new();
let line1 = ShapedLine::default().with_len(100);
let line2 = ShapedLine::default().with_len(50);
let wrapped_lines = smallvec::smallvec![line1, line2];
line_layout.set_wrapped_lines(wrapped_lines);
assert_eq!(line_layout.len(), 150);
assert_eq!(line_layout.wrapped_lines.len(), 2);
}
fn test_last_layout(line_height: Pixels) -> LastLayout {
LastLayout {
visible_range: 0..1,
visible_buffer_lines: vec![0],
visible_line_byte_offsets: vec![0],
visible_top: px(0.),
anchor_display_row: 0,
visible_range_offset: 0..0,
lines: Rc::new(vec![]),
line_height,
wrap_width: None,
wrapping_indent: WrappingIndent::default(),
line_number_width: px(0.),
space_width: px(0.),
cursor_bounds: None,
text_align: TextAlign::Left,
content_width: px(0.),
}
}
#[test]
fn test_position_for_index_prefers_first_leading_empty_visual_line() {
let mut line_layout = LineLayout::new();
line_layout.set_wrapped_lines(smallvec::smallvec![
ShapedLine::default(),
ShapedLine::default(),
ShapedLine::default().with_len(3),
]);
assert_eq!(
line_layout.position_for_index(0, &test_last_layout(px(20.)), false),
Some(point(px(0.), px(0.)))
);
}
#[test]
fn clicking_past_a_wrapped_row_keeps_the_caret_on_that_row() {
let mut line_layout = LineLayout::new();
line_layout.set_wrapped_lines(smallvec::smallvec![
ShapedLine::default().with_len(10),
ShapedLine::default().with_len(5),
]);
let last_layout = test_last_layout(px(20.));
let (ix, line_end_affinity) = line_layout
.closest_index_for_position(point(px(999.), px(5.)), &last_layout)
.unwrap();
assert_eq!(ix, 10);
assert!(line_end_affinity);
assert_eq!(
line_layout
.position_for_index(ix, &last_layout, line_end_affinity)
.map(|pos| pos.y),
Some(px(0.))
);
assert_eq!(
line_layout
.position_for_index(ix, &last_layout, false)
.map(|pos| pos.y),
Some(px(20.))
);
let (ix, line_end_affinity) = line_layout
.closest_index_for_position(point(px(999.), px(25.)), &last_layout)
.unwrap();
assert_eq!(ix, 15);
assert!(!line_end_affinity);
}
#[test]
fn a_wrap_boundary_offset_resolves_to_the_row_the_caret_is_drawn_on() {
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
wrapper.text = Rope::from("first line\nthis one wraps");
wrapper.lines = SumTree::from_iter(
vec![
LineItem {
len: Rope::from("first line").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..10],
valid_widths: WidthRange::empty(),
},
LineItem {
len: Rope::from("this one wraps").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..9, 9..14],
valid_widths: WidthRange::empty(),
},
],
&(),
);
assert_eq!(
wrapper.offset_to_display_point_with_affinity(20, true),
WrapDisplayPoint::new(1, 0, 9)
);
assert_eq!(
wrapper.offset_to_display_point_with_affinity(20, false),
WrapDisplayPoint::new(2, 1, 0)
);
assert_eq!(
wrapper.offset_to_display_point(20),
wrapper.offset_to_display_point_with_affinity(20, false)
);
for line_end_affinity in [false, true] {
assert_eq!(
wrapper.offset_to_display_point_with_affinity(23, line_end_affinity),
WrapDisplayPoint::new(2, 1, 3)
);
}
}
#[test]
fn test_offset_to_display_point() {
let font = gpui::Font {
family: "Arial".into(),
weight: FontWeight::default(),
style: FontStyle::Normal,
features: FontFeatures::default(),
fallbacks: None,
};
let mut wrapper = TextWrapper::new(font, px(14.), None);
wrapper.text = Rope::from(
"Hello, 世界!\r\nThis is second line.\nThis is third line.\n这里是第 4 行。",
);
wrapper.lines = SumTree::from_iter(
vec![
LineItem {
len: Rope::from("Hello, 世界!\r").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..15],
valid_widths: WidthRange::empty(),
},
LineItem {
len: Rope::from("This is second line.\n").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..10, 10..20],
valid_widths: WidthRange::empty(),
},
LineItem {
len: Rope::from("This is third line.\n").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..9, 9..15, 15..20],
valid_widths: WidthRange::empty(),
},
LineItem {
len: Rope::from("这里是第 4 行。").len(),
indent: 0,
wrapped_lines: smallvec::smallvec![0..22],
valid_widths: WidthRange::empty(),
},
],
&(),
);
assert_eq!(
wrapper.offset_to_display_point(12),
WrapDisplayPoint::new(0, 0, 12)
);
assert_eq!(
wrapper.offset_to_display_point(15),
WrapDisplayPoint::new(0, 0, 15)
);
assert_eq!(
wrapper.offset_to_display_point(16),
WrapDisplayPoint::new(1, 0, 0)
);
assert_eq!(
wrapper.offset_to_display_point(21),
WrapDisplayPoint::new(1, 0, 5)
);
assert_eq!(
wrapper.offset_to_display_point(27),
WrapDisplayPoint::new(2, 1, 1)
);
assert_eq!(
wrapper.offset_to_display_point(37),
WrapDisplayPoint::new(3, 0, 0)
);
assert_eq!(
wrapper.offset_to_display_point(54),
WrapDisplayPoint::new(5, 2, 2)
);
assert_eq!(
wrapper.offset_to_display_point(59),
WrapDisplayPoint::new(6, 0, 2)
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(6, 0, 2)),
59
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(5, 2, 2)),
54
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(3, 0, 0)),
37
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(2, 1, 1)),
27
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 5)),
21
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(1, 0, 0)),
16
);
assert_eq!(
wrapper.display_point_to_offset(WrapDisplayPoint::new(0, 0, 15)),
15
);
}
#[test]
fn test_wrapping_indent_same_keeps_indent_reserved() {
let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
wrapper.wrapping_indent = WrappingIndent::Same;
let text = Rope::from(" abcdefghijklmnopqrstuv");
let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
if line.starts_with(' ') {
vec![Boundary {
ix: 5,
next_indent: 2,
}]
} else {
let mut boundaries = vec![];
let mut i = 8;
while i < line.len() {
boundaries.push(Boundary {
ix: i,
next_indent: 0,
});
i += 8;
}
boundaries
}
};
wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
let line = wrapper.line(0).unwrap();
assert_eq!(line.indent, 2);
assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..24]);
}
#[test]
fn test_wrapping_indent_none_continuation_lines_wrapped_at_full_width() {
let mut wrapper = TextWrapper::new(test_font(), px(14.0), Some(px(10.)));
wrapper.wrapping_indent = WrappingIndent::None;
let text = Rope::from(" abcdefghijklmnopqrstuv");
let mut fake_wrap_line = |line: &str, _wrap_width: Pixels, _: usize| {
if line.starts_with(' ') {
vec![Boundary {
ix: 5,
next_indent: 2,
}]
} else {
let mut boundaries = vec![];
let mut i = 8;
while i < line.len() {
boundaries.push(Boundary {
ix: i,
next_indent: 0,
});
i += 8;
}
boundaries
}
};
wrapper._update(&text, &(0..text.len()), &text, &mut fake_wrap_line);
let line = wrapper.line(0).unwrap();
assert_eq!(line.indent, 0);
assert_eq!(line.wrapped_lines.as_slice(), [0..5, 5..13, 13..21, 21..24]);
}
#[test]
fn a_paragraph_starts_at_the_edge_it_reads_from() {
let row = |text: &str, width: f32| {
let mut row = InputLine::from(ShapedLine::default());
row.text = text.to_owned().into();
row.width = px(width);
row
};
let mut arabic = LineLayout::new()
.inline_lines(smallvec::smallvec![row("١٢ مرحبا", 60.), row("hello", 40.)]);
assert_eq!(arabic.start_align(), TextAlign::Right);
arabic.align = arabic.start_align();
assert_eq!(
arabic.row_x(0, px(100.)),
px(40.),
"each row by its own width"
);
assert_eq!(arabic.row_x(1, px(100.)), px(60.));
let english = LineLayout::new().inline_lines(smallvec::smallvec![row("hi مرحبا", 60.)]);
assert_eq!(english.start_align(), TextAlign::Left);
let neutral = LineLayout::new().inline_lines(smallvec::smallvec![row("12 !", 30.)]);
assert_eq!(neutral.start_align(), TextAlign::Left);
}
#[test]
fn test_wrap_indent_offsets_continuation_lines() {
let mut line_layout = LineLayout::new();
line_layout.set_wrapped_lines(smallvec::smallvec![
ShapedLine::default().with_len(5),
ShapedLine::default().with_len(10),
]);
line_layout = line_layout.wrap_indent(px(20.0));
let last_layout = LastLayout {
visible_range: 0..1,
visible_buffer_lines: vec![0],
visible_line_byte_offsets: vec![0],
visible_top: px(0.),
anchor_display_row: 0,
visible_range_offset: 0..0,
lines: Rc::new(vec![]),
line_height: px(20.0),
wrap_width: Some(px(10.)),
wrapping_indent: WrappingIndent::Same,
line_number_width: px(0.),
space_width: px(0.),
cursor_bounds: None,
text_align: TextAlign::Left,
content_width: px(0.),
};
assert_eq!(
line_layout.position_for_index(0, &last_layout, false),
Some(point(px(0.), px(0.))),
);
assert_eq!(
line_layout.position_for_index(6, &last_layout, false),
Some(point(px(20.), px(20.))),
)
}
}