feat(input): hanging indent for soft-wrapped list lines
- set_hanging_indents(markers) on textarea and editor states - continuation rows wrap at wrap_width minus the marker width and start under the marker end - caret, selection, hit testing and up/down moves follow via the existing wrap_indent path Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -11,13 +11,17 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in
11
11
| `src/input/editor/display_map/text_wrapper.rs` | `font_families` on `TextWrapper`, `split_run_by_font_families()`, `set_font_families()` / `adjust_font_families()`, `measured_wrap_boundaries` measures by range, shared `changed_ranges()` / `rewrap_rows_of()` | soft wrap measures font-family ranges in their own font |
12
12
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs`, `mod.rs` | pass-through for `set_font_families`, export `split_run_by_font_families` | plumbing |
13
13
| `src/input/base/element.rs` | prepaint pushes font-family spans into the display map; render runs split by font family | glyphs, caret, selection and hit testing use the same shaped runs |
14
| `src/input/base/state.rs` | `set_hanging_indents(markers)` on multi-line states (textarea and editor) | list lines: continuation rows start under the text after `•`, `◦`, `12.` |
15
| `src/input/editor/display_map/text_wrapper.rs` | `hanging_indents` on `TextWrapper`, `hanging_indent_at()`, `measured_wrap_boundaries(.., hanging_indent, ..)`, `shift_span()` shared with inline metrics; a line with a marker always wraps as `WrappingIndent::Same` | wrap continuation rows at `wrap_width - marker width`; the existing `LineItem.indent` / `LineLayout.wrap_indent` path then shifts rendering, caret, selection, hit testing and up/down moves |
16
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs` | pass-through for `set_hanging_indents`, adjust on edit | plumbing |
14
17
15
18
## Limits
16
19
17
20
- Only the font family changes wrapping. Bold/italic `HighlightStyle` decorations still wrap with the regular-weight font.
18
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only.
21
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only and ignore their hanging indent.
22
- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.
19
23
- The unwrapped longest-line width (soft wrap off) ignores font families.
20
- Decorations exist on `EditorState` only, not `TextareaState`.
24
- Text decorations (and so font families) exist on `EditorState` only, not `TextareaState`.
21
25
22
26
## Re-apply on a gpui-kit upgrade
23
27
@@ -11,13 +11,17 @@ Upstream: crates.io `gpui-base 0.7.1` (git `87d10ae5`, `crates/base`). Wired in11
| `src/input/editor/display_map/text_wrapper.rs` | `font_families` on `TextWrapper`, `split_run_by_font_families()`, `set_font_families()` / `adjust_font_families()`, `measured_wrap_boundaries` measures by range, shared `changed_ranges()` / `rewrap_rows_of()` | soft wrap measures font-family ranges in their own font |11
| `src/input/editor/display_map/text_wrapper.rs` | `font_families` on `TextWrapper`, `split_run_by_font_families()`, `set_font_families()` / `adjust_font_families()`, `measured_wrap_boundaries` measures by range, shared `changed_ranges()` / `rewrap_rows_of()` | soft wrap measures font-family ranges in their own font |12
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs`, `mod.rs` | pass-through for `set_font_families`, export `split_run_by_font_families` | plumbing |12
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs`, `mod.rs` | pass-through for `set_font_families`, export `split_run_by_font_families` | plumbing |13
| `src/input/base/element.rs` | prepaint pushes font-family spans into the display map; render runs split by font family | glyphs, caret, selection and hit testing use the same shaped runs |13
| `src/input/base/element.rs` | prepaint pushes font-family spans into the display map; render runs split by font family | glyphs, caret, selection and hit testing use the same shaped runs |14
| `src/input/base/state.rs` | `set_hanging_indents(markers)` on multi-line states (textarea and editor) | list lines: continuation rows start under the text after `•`, `◦`, `12.` |15
| `src/input/editor/display_map/text_wrapper.rs` | `hanging_indents` on `TextWrapper`, `hanging_indent_at()`, `measured_wrap_boundaries(.., hanging_indent, ..)`, `shift_span()` shared with inline metrics; a line with a marker always wraps as `WrappingIndent::Same` | wrap continuation rows at `wrap_width - marker width`; the existing `LineItem.indent` / `LineLayout.wrap_indent` path then shifts rendering, caret, selection, hit testing and up/down moves |16
| `src/input/editor/display_map/wrap_map.rs`, `display_map.rs` | pass-through for `set_hanging_indents`, adjust on edit | plumbing |14
17
15
## Limits18
## Limits16
19
17
- Only the font family changes wrapping. Bold/italic `HighlightStyle` decorations still wrap with the regular-weight font.20
- Only the font family changes wrapping. Bold/italic `HighlightStyle` decorations still wrap with the regular-weight font.18
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only.21
- Lines containing inline tokens wrap through gpui's `LineWrapper` with the base font only and ignore their hanging indent.22
- Hanging-indent markers are dropped by an edit inside them; the app sets them again on change.19
- The unwrapped longest-line width (soft wrap off) ignores font families.23
- The unwrapped longest-line width (soft wrap off) ignores font families.20
- Decorations exist on `EditorState` only, not `TextareaState`.24
- Text decorations (and so font families) exist on `EditorState` only, not `TextareaState`.21
25
22
## Re-apply on a gpui-kit upgrade26
## Re-apply on a gpui-kit upgrade23
27
@@ -8697,6 +8697,59 @@ mod tests {
8697
8697
});
8698
8698
}
8699
8699
8700
#[gpui::test]
8701
fn test_hanging_indent_shifts_wrapped_rows_caret_hit_testing_and_moves(
8702
cx: &mut TestAppContext,
8703
) {
8704
cx.update(crate::init);
8705
let text = format!("• {}", "a ".repeat(300));
8706
let view = InputView::build_textarea(cx, move |state| state.rows(4).default_value(text));
8707
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);
8708
visual.update(|window, cx| window.draw(cx).clear(cx));
8709
let plain_rows = view.input.read_with(&visual, |state, _| {
8710
let line = &state.last_layout.as_ref().unwrap().lines[0];
8711
assert_eq!(line.wrap_indent, px(0.));
8712
line.wrapped_lines
8713
.iter()
8714
.map(|row| row.len)
8715
.collect::<Vec<_>>()
8716
});
8717
8718
visual.update(|_, cx| {
8719
view.input
8720
.update(cx, |state, cx| state.set_hanging_indents(vec![0..4], cx))
8721
});
8722
visual.update(|window, cx| window.draw(cx).clear(cx));
8723
visual.update(|window, cx| {
8724
view.input.update(cx, |state, cx| {
8725
let layout = state.last_layout.as_ref().unwrap();
8726
let line = &layout.lines[0];
8727
assert_eq!(line.wrapped_lines[0].len, plain_rows[0]);
8728
assert!(line.wrapped_lines[1].len < plain_rows[1]);
8729
let marker_x = line.wrapped_lines[0].x_for_index(4);
8730
assert!(marker_x > px(0.));
8731
assert_eq!(line.wrap_indent, marker_x);
8732
8733
let row_start = line.wrapped_lines[0].len;
8734
assert_eq!(
8735
line.position_for_index(row_start, layout, false),
8736
Some(point(marker_x, layout.line_height))
8737
);
8738
let (hit, _) = line
8739
.closest_index_for_position(
8740
point(marker_x + px(1.), layout.line_height + px(1.)),
8741
layout,
8742
)
8743
.unwrap();
8744
assert_eq!(hit, row_start);
8745
8746
state.set_selected_range(row_start..row_start, cx);
8747
state.up(&MoveUp, window, cx);
8748
assert_eq!(state.cursor(), 4);
8749
});
8750
});
8751
}
8752
8700
8753
#[gpui::test]
8701
8754
fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {
8702
8755
let view = InputView::<EditorMode>::new(cx);
@@ -10697,6 +10750,30 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {
10697
10750
self.display_map.set_wrapping_indent(wrapping_indent, cx);
10698
10751
cx.notify();
10699
10752
}
10753
10754
/// Hang soft-wrapped continuation rows under the end of a list marker.
10755
///
10756
/// Each range is a marker in UTF-8 bytes, e.g. `0..4` for `"• "` at the
10757
/// start of `"• Run the tests"`; that line's continuation rows start at the
10758
/// x of byte 4 instead of 0. One marker per line, the first wins. A marker
10759
/// wider than the wrap width is ignored. Markers shift with edits before
10760
/// them and are dropped by edits inside them; set them again on change.
10761
/// Lines with inline tokens ignore their marker.
10762
pub fn set_hanging_indents(&mut self, markers: Vec<Range<usize>>, cx: &mut Context<Self>) {
10763
let mut markers: Vec<Range<usize>> = markers
10764
.into_iter()
10765
.filter(|marker| !marker.is_empty())
10766
.map(|marker| {
10767
self.text.clip_offset(marker.start, Bias::Left)
10768
..self.text.clip_offset(marker.end, Bias::Right)
10769
})
10770
.filter(|marker| !marker.is_empty())
10771
.collect();
10772
markers.sort_by_key(|marker| marker.start);
10773
markers.dedup_by_key(|marker| self.text.offset_to_point(marker.start).row);
10774
self.display_map.set_hanging_indents(markers.into(), cx);
10775
cx.notify();
10776
}
10700
10777
}
10701
10778
10702
10779
/// Methods that only ordinary multi-line text offers.
@@ -8697,6 +8697,59 @@ mod tests {8697
});8697
});8698
}8698
}8699
8699
8700
#[gpui::test]8701
fn test_hanging_indent_shifts_wrapped_rows_caret_hit_testing_and_moves(8702
cx: &mut TestAppContext,8703
) {8704
cx.update(crate::init);8705
let text = format!("• {}", "a ".repeat(300));8706
let view = InputView::build_textarea(cx, move |state| state.rows(4).default_value(text));8707
let mut visual = VisualTestContext::from_window(view.window_handle.into(), cx);8708
visual.update(|window, cx| window.draw(cx).clear(cx));8709
let plain_rows = view.input.read_with(&visual, |state, _| {8710
let line = &state.last_layout.as_ref().unwrap().lines[0];8711
assert_eq!(line.wrap_indent, px(0.));8712
line.wrapped_lines8713
.iter()8714
.map(|row| row.len)8715
.collect::<Vec<_>>()8716
});8717
8718
visual.update(|_, cx| {8719
view.input8720
.update(cx, |state, cx| state.set_hanging_indents(vec![0..4], cx))8721
});8722
visual.update(|window, cx| window.draw(cx).clear(cx));8723
visual.update(|window, cx| {8724
view.input.update(cx, |state, cx| {8725
let layout = state.last_layout.as_ref().unwrap();8726
let line = &layout.lines[0];8727
assert_eq!(line.wrapped_lines[0].len, plain_rows[0]);8728
assert!(line.wrapped_lines[1].len < plain_rows[1]);8729
let marker_x = line.wrapped_lines[0].x_for_index(4);8730
assert!(marker_x > px(0.));8731
assert_eq!(line.wrap_indent, marker_x);8732
8733
let row_start = line.wrapped_lines[0].len;8734
assert_eq!(8735
line.position_for_index(row_start, layout, false),8736
Some(point(marker_x, layout.line_height))8737
);8738
let (hit, _) = line8739
.closest_index_for_position(8740
point(marker_x + px(1.), layout.line_height + px(1.)),8741
layout,8742
)8743
.unwrap();8744
assert_eq!(hit, row_start);8745
8746
state.set_selected_range(row_start..row_start, cx);8747
state.up(&MoveUp, window, cx);8748
assert_eq!(state.cursor(), 4);8749
});8750
});8751
}8752
8700
#[gpui::test]8753
#[gpui::test]8701
fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {8754
fn test_editor_decorations_follow_typing(cx: &mut TestAppContext) {8702
let view = InputView::<EditorMode>::new(cx);8755
let view = InputView::<EditorMode>::new(cx);@@ -10697,6 +10750,30 @@ impl<M: crate::input::MultiLineMode> InputBaseState<M> {10697
self.display_map.set_wrapping_indent(wrapping_indent, cx);10750
self.display_map.set_wrapping_indent(wrapping_indent, cx);10698
cx.notify();10751
cx.notify();10699
}10752
}10753
10754
/// Hang soft-wrapped continuation rows under the end of a list marker.10755
///10756
/// Each range is a marker in UTF-8 bytes, e.g. `0..4` for `"• "` at the10757
/// start of `"• Run the tests"`; that line's continuation rows start at the10758
/// x of byte 4 instead of 0. One marker per line, the first wins. A marker10759
/// wider than the wrap width is ignored. Markers shift with edits before10760
/// them and are dropped by edits inside them; set them again on change.10761
/// Lines with inline tokens ignore their marker.10762
pub fn set_hanging_indents(&mut self, markers: Vec<Range<usize>>, cx: &mut Context<Self>) {10763
let mut markers: Vec<Range<usize>> = markers10764
.into_iter()10765
.filter(|marker| !marker.is_empty())10766
.map(|marker| {10767
self.text.clip_offset(marker.start, Bias::Left)10768
..self.text.clip_offset(marker.end, Bias::Right)10769
})10770
.filter(|marker| !marker.is_empty())10771
.collect();10772
markers.sort_by_key(|marker| marker.start);10773
markers.dedup_by_key(|marker| self.text.offset_to_point(marker.start).row);10774
self.display_map.set_hanging_indents(markers.into(), cx);10775
cx.notify();10776
}10700
}10777
}10701
10778
10702
/// Methods that only ordinary multi-line text offers.10779
/// Methods that only ordinary multi-line text offers.@@ -245,6 +245,16 @@ impl DisplayMap {
245
245
self.rebuild_fold_projection();
246
246
}
247
247
248
/// Hang continuation rows of each marker's line under the marker's end.
249
pub(crate) fn set_hanging_indents(
250
&mut self,
251
hanging_indents: std::rc::Rc<[Range<usize>]>,
252
cx: &mut App,
253
) {
254
self.wrap_map.set_hanging_indents(hanging_indents, cx);
255
self.rebuild_fold_projection();
256
}
257
248
258
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
249
259
self.wrap_map.on_layout_changed(wrap_width, cx);
250
260
self.rebuild_fold_projection();
@@ -245,6 +245,16 @@ impl DisplayMap {245
self.rebuild_fold_projection();245
self.rebuild_fold_projection();246
}246
}247
247
248
/// Hang continuation rows of each marker's line under the marker's end.249
pub(crate) fn set_hanging_indents(250
&mut self,251
hanging_indents: std::rc::Rc<[Range<usize>]>,252
cx: &mut App,253
) {254
self.wrap_map.set_hanging_indents(hanging_indents, cx);255
self.rebuild_fold_projection();256
}257
248
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {258
pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {249
self.wrap_map.on_layout_changed(wrap_width, cx);259
self.wrap_map.on_layout_changed(wrap_width, cx);250
self.rebuild_fold_projection();260
self.rebuild_fold_projection();@@ -30,21 +30,28 @@ pub enum WrappingIndent {
30
30
31
31
/// Choose Unicode line-break opportunities using the same shaped widths as
32
32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.
33
/// `hanging_indent` is a byte offset continuation rows align under; it wins over `wrapping_indent`.
33
34
fn measured_wrap_boundaries(
34
35
text: &str,
35
36
width: Pixels,
36
37
wrapping_indent: WrappingIndent,
38
hanging_indent: Option<usize>,
37
39
mut measure: impl FnMut(Range<usize>) -> Pixels,
38
40
) -> Vec<gpui::Boundary> {
39
let indent = if wrapping_indent == WrappingIndent::Same {
40
text.chars()
41
let mut indent = match hanging_indent {
42
Some(hanging_indent) => hanging_indent,
43
None if wrapping_indent == WrappingIndent::Same => text
44
.chars()
41
45
.take_while(|&c| c == ' ')
42
46
.count()
43
.min(gpui::LineWrapper::MAX_INDENT as usize)
44
} else {
45
0
47
.min(gpui::LineWrapper::MAX_INDENT as usize),
48
None => 0,
46
49
};
47
let indent_width = measure(0..indent);
50
let mut indent_width = measure(0..indent);
51
if hanging_indent.is_some() && indent_width >= width {
52
indent = 0;
53
indent_width = px(0.);
54
}
48
55
let ends: Vec<usize> = text
49
56
.grapheme_indices(true)
50
57
.map(|(ix, grapheme)| ix + grapheme.len())
@@ -95,7 +102,7 @@ fn measured_wrap_boundaries(
95
102
.unwrap_or(fitting_end);
96
103
result.push(gpui::Boundary {
97
104
ix: end,
98
next_indent: indent as u32,
105
next_indent: text[..indent].chars().count() as u32,
99
106
});
100
107
first = ends.partition_point(|&ix| ix <= end);
101
108
start = end;
@@ -142,6 +149,30 @@ pub(crate) fn split_run_by_font_families(
142
149
runs
143
150
}
144
151
152
/// `span` after replacing `edit` with `new_len` bytes, or `None` when the edit touches its inside.
153
fn shift_span(span: &Range<usize>, edit: &Range<usize>, new_len: usize) -> Option<Range<usize>> {
154
if span.start < edit.end && edit.start < span.end {
155
return None;
156
}
157
if span.start < edit.end {
158
return Some(span.clone());
159
}
160
let shift = new_len as isize - edit.len() as isize;
161
Some(span.start.checked_add_signed(shift)?..span.end.checked_add_signed(shift)?)
162
}
163
164
/// Byte offset within the line at `line_start` that its continuation rows hang under.
165
fn hanging_indent_at(
166
hanging_indents: &[Range<usize>],
167
line_start: usize,
168
line_len: usize,
169
) -> Option<usize> {
170
let first = hanging_indents.partition_point(|marker| marker.start < line_start);
171
let marker = hanging_indents.get(first)?;
172
(marker.start <= line_start + line_len)
173
.then(|| marker.end.min(line_start + line_len) - line_start)
174
}
175
145
176
/// Ranges whose entry differs between two sorted span lists.
146
177
fn changed_ranges<T: PartialEq>(
147
178
old: &[(Range<usize>, T)],
@@ -301,6 +332,8 @@ pub(crate) struct TextWrapper {
301
332
inline_metrics: Rc<[(Range<usize>, Pixels)]>,
302
333
/// Sorted, non-overlapping document byte ranges measured in another font family.
303
334
font_families: Rc<[(Range<usize>, SharedString)]>,
335
/// Sorted list marker ranges, at most one per line; continuation rows start under their end.
336
hanging_indents: Rc<[Range<usize>]>,
304
337
_initialized: bool,
305
338
}
306
339
@@ -316,6 +349,7 @@ impl TextWrapper {
316
349
lines: SumTree::new(&()),
317
350
inline_metrics: Rc::from([]),
318
351
font_families: Rc::from([]),
352
hanging_indents: Rc::from([]),
319
353
_initialized: false,
320
354
}
321
355
}
@@ -448,6 +482,7 @@ impl TextWrapper {
448
482
.line_wrapper(self.font.clone(), self.font_size);
449
483
let metrics = self.inline_metrics.clone();
450
484
let font_families = self.font_families.clone();
485
let hanging_indents = self.hanging_indents.clone();
451
486
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());
452
487
let font = self.font.clone();
453
488
let font_size = self.font_size;
@@ -484,6 +519,7 @@ impl TextWrapper {
484
519
line_str,
485
520
wrap_width,
486
521
wrapping_indent,
522
hanging_indent_at(&hanging_indents, line_start, line_str.len()),
487
523
|range| {
488
524
let runs = split_run_by_font_families(
489
525
TextRun {
@@ -544,24 +580,43 @@ impl TextWrapper {
544
580
if self.inline_metrics.is_empty() {
545
581
return;
546
582
}
547
let shift = new_len as isize - range.len() as isize;
548
583
self.inline_metrics = self
549
584
.inline_metrics
550
585
.iter()
551
.filter_map(|(token, width)| {
552
if token.start < range.end && range.start < token.end {
553
return None;
554
}
555
let token = if token.start >= range.end {
556
token.start.checked_add_signed(shift)?..token.end.checked_add_signed(shift)?
557
} else {
558
token.clone()
559
};
560
Some((token, *width))
561
})
586
.filter_map(|(token, width)| Some((shift_span(token, range, new_len)?, *width)))
587
.collect();
588
}
589
590
pub(crate) fn adjust_hanging_indents(&mut self, range: &Range<usize>, new_len: usize) {
591
if self.hanging_indents.is_empty() {
592
return;
593
}
594
self.hanging_indents = self
595
.hanging_indents
596
.iter()
597
.filter_map(|marker| shift_span(marker, range, new_len))
562
598
.collect();
563
599
}
564
600
601
pub(crate) fn set_hanging_indents(
602
&mut self,
603
hanging_indents: Rc<[Range<usize>]>,
604
cx: &mut App,
605
) {
606
if self.hanging_indents == hanging_indents {
607
return;
608
}
609
let as_spans = |markers: &[Range<usize>]| -> Vec<(Range<usize>, ())> {
610
markers.iter().map(|marker| (marker.clone(), ())).collect()
611
};
612
let affected = changed_ranges(
613
&as_spans(&self.hanging_indents),
614
&as_spans(&hanging_indents),
615
);
616
self.hanging_indents = hanging_indents;
617
self.rewrap_rows_of(&affected, cx);
618
}
619
565
620
pub(crate) fn set_inline_metrics(
566
621
&mut self,
567
622
metrics: Rc<[(Range<usize>, Pixels)]>,
@@ -628,6 +683,13 @@ impl TextWrapper {
628
683
// line not contains `\n`.
629
684
for row in new_start_row..=new_end_row {
630
685
let line = changed_text.slice_line(row);
686
let line_start = changed_text.line_start_offset(row);
687
let wrapping_indent =
688
if hanging_indent_at(&self.hanging_indents, line_start, line.len()).is_some() {
689
WrappingIndent::Same
690
} else {
691
self.wrapping_indent
692
};
631
693
let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();
632
694
let mut prev_boundary_ix = 0;
633
695
let mut indent_chars = 0;
@@ -636,7 +698,7 @@ impl TextWrapper {
636
698
if let Some(wrap_width) = wrap_width {
637
699
// Borrowed for lines within a single rope chunk.
638
700
let line_str: Cow<str> = line.into();
639
match self.wrapping_indent {
701
match wrapping_indent {
640
702
WrappingIndent::Same => {
641
703
// Here only have wrapped line, if there is no wrap meet, the `line_wraps`
642
704
// result will empty.
@@ -1363,7 +1425,7 @@ mod tests {
1363
1425
&(start..previous.len()),
1364
1426
&inserted,
1365
1427
&mut |line, width, _| {
1366
measured_wrap_boundaries(line, width, WrappingIndent::None, |range| {
1428
measured_wrap_boundaries(line, width, WrappingIndent::None, None, |range| {
1367
1429
measure(&line[range])
1368
1430
})
1369
1431
},
@@ -1383,7 +1445,7 @@ mod tests {
1383
1445
#[test]
1384
1446
fn measured_wrap_preserves_words_graphemes_and_indentation() {
1385
1447
let wrap = |text: &str, width, indent| {
1386
measured_wrap_boundaries(text, px(width), indent, |range| {
1448
measured_wrap_boundaries(text, px(width), indent, None, |range| {
1387
1449
px(text[range].graphemes(true).count() as f32)
1388
1450
})
1389
1451
.into_iter()
@@ -1400,6 +1462,34 @@ mod tests {
1400
1462
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);
1401
1463
}
1402
1464
1465
#[test]
1466
fn measured_wrap_hangs_continuation_rows_under_the_marker() {
1467
let wrap = |text: &str, hanging_indent| {
1468
measured_wrap_boundaries(
1469
text,
1470
px(8.),
1471
WrappingIndent::None,
1472
hanging_indent,
1473
|range| px(text[range].graphemes(true).count() as f32),
1474
)
1475
.into_iter()
1476
.map(|boundary| (boundary.ix, boundary.next_indent))
1477
.collect::<Vec<_>>()
1478
};
1479
assert_eq!(wrap("• aaa bbb ccc", None), [(8, 0)]);
1480
assert_eq!(wrap("• aaa bbb ccc", Some(4)), [(8, 2), (12, 2)]);
1481
assert_eq!(wrap("• aaa bbb ccc", Some(10)), [(8, 0)]);
1482
assert_eq!(hanging_indent_at(&[0..4, 10..13], 0, 8), Some(4));
1483
assert_eq!(hanging_indent_at(&[0..4, 10..13], 9, 8), Some(4));
1484
1485
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);
1486
wrapper.hanging_indents = Rc::from([0..4, 10..13]);
1487
wrapper.adjust_hanging_indents(&(0..0), 1);
1488
wrapper.adjust_hanging_indents(&(12..12), 1);
1489
assert_eq!(&*wrapper.hanging_indents, [1..5]);
1490
assert_eq!(hanging_indent_at(&[0..4], 5, 8), None);
1491
}
1492
1403
1493
#[test]
1404
1494
fn test_update() {
1405
1495
let font = gpui::Font {
@@ -30,21 +30,28 @@ pub enum WrappingIndent {30
30
31
/// Choose Unicode line-break opportunities using the same shaped widths as31
/// Choose Unicode line-break opportunities using the same shaped widths as32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.32
/// painting. Oversized words fall back to complete graphemes, never UTF-8 bytes.33
/// `hanging_indent` is a byte offset continuation rows align under; it wins over `wrapping_indent`.33
fn measured_wrap_boundaries(34
fn measured_wrap_boundaries(34
text: &str,35
text: &str,35
width: Pixels,36
width: Pixels,36
wrapping_indent: WrappingIndent,37
wrapping_indent: WrappingIndent,38
hanging_indent: Option<usize>,37
mut measure: impl FnMut(Range<usize>) -> Pixels,39
mut measure: impl FnMut(Range<usize>) -> Pixels,38
) -> Vec<gpui::Boundary> {40
) -> Vec<gpui::Boundary> {39
let indent = if wrapping_indent == WrappingIndent::Same {41
let mut indent = match hanging_indent {40
text.chars()42
Some(hanging_indent) => hanging_indent,43
None if wrapping_indent == WrappingIndent::Same => text44
.chars()41
.take_while(|&c| c == ' ')45
.take_while(|&c| c == ' ')42
.count()46
.count()43
.min(gpui::LineWrapper::MAX_INDENT as usize)47
.min(gpui::LineWrapper::MAX_INDENT as usize),44
} else {48
None => 0,45
046
};49
};47
let indent_width = measure(0..indent);50
let mut indent_width = measure(0..indent);51
if hanging_indent.is_some() && indent_width >= width {52
indent = 0;53
indent_width = px(0.);54
}48
let ends: Vec<usize> = text55
let ends: Vec<usize> = text49
.grapheme_indices(true)56
.grapheme_indices(true)50
.map(|(ix, grapheme)| ix + grapheme.len())57
.map(|(ix, grapheme)| ix + grapheme.len())@@ -95,7 +102,7 @@ fn measured_wrap_boundaries(95
.unwrap_or(fitting_end);102
.unwrap_or(fitting_end);96
result.push(gpui::Boundary {103
result.push(gpui::Boundary {97
ix: end,104
ix: end,98
next_indent: indent as u32,105
next_indent: text[..indent].chars().count() as u32,99
});106
});100
first = ends.partition_point(|&ix| ix <= end);107
first = ends.partition_point(|&ix| ix <= end);101
start = end;108
start = end;@@ -142,6 +149,30 @@ pub(crate) fn split_run_by_font_families(142
runs149
runs143
}150
}144
151
152
/// `span` after replacing `edit` with `new_len` bytes, or `None` when the edit touches its inside.153
fn shift_span(span: &Range<usize>, edit: &Range<usize>, new_len: usize) -> Option<Range<usize>> {154
if span.start < edit.end && edit.start < span.end {155
return None;156
}157
if span.start < edit.end {158
return Some(span.clone());159
}160
let shift = new_len as isize - edit.len() as isize;161
Some(span.start.checked_add_signed(shift)?..span.end.checked_add_signed(shift)?)162
}163
164
/// Byte offset within the line at `line_start` that its continuation rows hang under.165
fn hanging_indent_at(166
hanging_indents: &[Range<usize>],167
line_start: usize,168
line_len: usize,169
) -> Option<usize> {170
let first = hanging_indents.partition_point(|marker| marker.start < line_start);171
let marker = hanging_indents.get(first)?;172
(marker.start <= line_start + line_len)173
.then(|| marker.end.min(line_start + line_len) - line_start)174
}175
145
/// Ranges whose entry differs between two sorted span lists.176
/// Ranges whose entry differs between two sorted span lists.146
fn changed_ranges<T: PartialEq>(177
fn changed_ranges<T: PartialEq>(147
old: &[(Range<usize>, T)],178
old: &[(Range<usize>, T)],@@ -301,6 +332,8 @@ pub(crate) struct TextWrapper {301
inline_metrics: Rc<[(Range<usize>, Pixels)]>,332
inline_metrics: Rc<[(Range<usize>, Pixels)]>,302
/// Sorted, non-overlapping document byte ranges measured in another font family.333
/// Sorted, non-overlapping document byte ranges measured in another font family.303
font_families: Rc<[(Range<usize>, SharedString)]>,334
font_families: Rc<[(Range<usize>, SharedString)]>,335
/// Sorted list marker ranges, at most one per line; continuation rows start under their end.336
hanging_indents: Rc<[Range<usize>]>,304
_initialized: bool,337
_initialized: bool,305
}338
}306
339
@@ -316,6 +349,7 @@ impl TextWrapper {316
lines: SumTree::new(&()),349
lines: SumTree::new(&()),317
inline_metrics: Rc::from([]),350
inline_metrics: Rc::from([]),318
font_families: Rc::from([]),351
font_families: Rc::from([]),352
hanging_indents: Rc::from([]),319
_initialized: false,353
_initialized: false,320
}354
}321
}355
}@@ -448,6 +482,7 @@ impl TextWrapper {448
.line_wrapper(self.font.clone(), self.font_size);482
.line_wrapper(self.font.clone(), self.font_size);449
let metrics = self.inline_metrics.clone();483
let metrics = self.inline_metrics.clone();450
let font_families = self.font_families.clone();484
let font_families = self.font_families.clone();485
let hanging_indents = self.hanging_indents.clone();451
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());486
let text_system = gpui::WindowTextSystem::new(cx.text_system().clone());452
let font = self.font.clone();487
let font = self.font.clone();453
let font_size = self.font_size;488
let font_size = self.font_size;@@ -484,6 +519,7 @@ impl TextWrapper {484
line_str,519
line_str,485
wrap_width,520
wrap_width,486
wrapping_indent,521
wrapping_indent,522
hanging_indent_at(&hanging_indents, line_start, line_str.len()),487
|range| {523
|range| {488
let runs = split_run_by_font_families(524
let runs = split_run_by_font_families(489
TextRun {525
TextRun {@@ -544,24 +580,43 @@ impl TextWrapper {544
if self.inline_metrics.is_empty() {580
if self.inline_metrics.is_empty() {545
return;581
return;546
}582
}547
let shift = new_len as isize - range.len() as isize;548
self.inline_metrics = self583
self.inline_metrics = self549
.inline_metrics584
.inline_metrics550
.iter()585
.iter()551
.filter_map(|(token, width)| {586
.filter_map(|(token, width)| Some((shift_span(token, range, new_len)?, *width)))552
if token.start < range.end && range.start < token.end {587
.collect();553
return None;588
}554
}589
555
let token = if token.start >= range.end {590
pub(crate) fn adjust_hanging_indents(&mut self, range: &Range<usize>, new_len: usize) {556
token.start.checked_add_signed(shift)?..token.end.checked_add_signed(shift)?591
if self.hanging_indents.is_empty() {557
} else {592
return;558
token.clone()593
}559
};594
self.hanging_indents = self560
Some((token, *width))595
.hanging_indents561
})596
.iter()597
.filter_map(|marker| shift_span(marker, range, new_len))562
.collect();598
.collect();563
}599
}564
600
601
pub(crate) fn set_hanging_indents(602
&mut self,603
hanging_indents: Rc<[Range<usize>]>,604
cx: &mut App,605
) {606
if self.hanging_indents == hanging_indents {607
return;608
}609
let as_spans = |markers: &[Range<usize>]| -> Vec<(Range<usize>, ())> {610
markers.iter().map(|marker| (marker.clone(), ())).collect()611
};612
let affected = changed_ranges(613
&as_spans(&self.hanging_indents),614
&as_spans(&hanging_indents),615
);616
self.hanging_indents = hanging_indents;617
self.rewrap_rows_of(&affected, cx);618
}619
565
pub(crate) fn set_inline_metrics(620
pub(crate) fn set_inline_metrics(566
&mut self,621
&mut self,567
metrics: Rc<[(Range<usize>, Pixels)]>,622
metrics: Rc<[(Range<usize>, Pixels)]>,@@ -628,6 +683,13 @@ impl TextWrapper {628
// line not contains `\n`.683
// line not contains `\n`.629
for row in new_start_row..=new_end_row {684
for row in new_start_row..=new_end_row {630
let line = changed_text.slice_line(row);685
let line = changed_text.slice_line(row);686
let line_start = changed_text.line_start_offset(row);687
let wrapping_indent =688
if hanging_indent_at(&self.hanging_indents, line_start, line.len()).is_some() {689
WrappingIndent::Same690
} else {691
self.wrapping_indent692
};631
let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();693
let mut wrapped_lines = SmallVec::<[Range<usize>; 1]>::new();632
let mut prev_boundary_ix = 0;694
let mut prev_boundary_ix = 0;633
let mut indent_chars = 0;695
let mut indent_chars = 0;@@ -636,7 +698,7 @@ impl TextWrapper {636
if let Some(wrap_width) = wrap_width {698
if let Some(wrap_width) = wrap_width {637
// Borrowed for lines within a single rope chunk.699
// Borrowed for lines within a single rope chunk.638
let line_str: Cow<str> = line.into();700
let line_str: Cow<str> = line.into();639
match self.wrapping_indent {701
match wrapping_indent {640
WrappingIndent::Same => {702
WrappingIndent::Same => {641
// Here only have wrapped line, if there is no wrap meet, the `line_wraps`703
// Here only have wrapped line, if there is no wrap meet, the `line_wraps`642
// result will empty.704
// result will empty.@@ -1363,7 +1425,7 @@ mod tests {1363
&(start..previous.len()),1425
&(start..previous.len()),1364
&inserted,1426
&inserted,1365
&mut |line, width, _| {1427
&mut |line, width, _| {1366
measured_wrap_boundaries(line, width, WrappingIndent::None, |range| {1428
measured_wrap_boundaries(line, width, WrappingIndent::None, None, |range| {1367
measure(&line[range])1429
measure(&line[range])1368
})1430
})1369
},1431
},@@ -1383,7 +1445,7 @@ mod tests {1383
#[test]1445
#[test]1384
fn measured_wrap_preserves_words_graphemes_and_indentation() {1446
fn measured_wrap_preserves_words_graphemes_and_indentation() {1385
let wrap = |text: &str, width, indent| {1447
let wrap = |text: &str, width, indent| {1386
measured_wrap_boundaries(text, px(width), indent, |range| {1448
measured_wrap_boundaries(text, px(width), indent, None, |range| {1387
px(text[range].graphemes(true).count() as f32)1449
px(text[range].graphemes(true).count() as f32)1388
})1450
})1389
.into_iter()1451
.into_iter()@@ -1400,6 +1462,34 @@ mod tests {1400
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);1462
assert_eq!(wrap("你好,世界", 2., WrappingIndent::None), vec![3, 9]);1401
}1463
}1402
1464
1465
#[test]1466
fn measured_wrap_hangs_continuation_rows_under_the_marker() {1467
let wrap = |text: &str, hanging_indent| {1468
measured_wrap_boundaries(1469
text,1470
px(8.),1471
WrappingIndent::None,1472
hanging_indent,1473
|range| px(text[range].graphemes(true).count() as f32),1474
)1475
.into_iter()1476
.map(|boundary| (boundary.ix, boundary.next_indent))1477
.collect::<Vec<_>>()1478
};1479
assert_eq!(wrap("• aaa bbb ccc", None), [(8, 0)]);1480
assert_eq!(wrap("• aaa bbb ccc", Some(4)), [(8, 2), (12, 2)]);1481
assert_eq!(wrap("• aaa bbb ccc", Some(10)), [(8, 0)]);1482
assert_eq!(hanging_indent_at(&[0..4, 10..13], 0, 8), Some(4));1483
assert_eq!(hanging_indent_at(&[0..4, 10..13], 9, 8), Some(4));1484
1485
let mut wrapper = TextWrapper::new(test_font(), px(14.), None);1486
wrapper.hanging_indents = Rc::from([0..4, 10..13]);1487
wrapper.adjust_hanging_indents(&(0..0), 1);1488
wrapper.adjust_hanging_indents(&(12..12), 1);1489
assert_eq!(&*wrapper.hanging_indents, [1..5]);1490
assert_eq!(hanging_indent_at(&[0..4], 5, 8), None);1491
}1492
1403
#[test]1493
#[test]1404
fn test_update() {1494
fn test_update() {1405
let font = gpui::Font {1495
let font = gpui::Font {@@ -109,6 +109,7 @@ impl WrapMap {
109
109
) {
110
110
self.wrapper.adjust_inline_metrics(range, new_text.len());
111
111
self.wrapper.adjust_font_families(range, new_text.len());
112
self.wrapper.adjust_hanging_indents(range, new_text.len());
112
113
self.wrapper.update(changed_text, range, new_text, cx);
113
114
}
114
115
@@ -129,6 +130,14 @@ impl WrapMap {
129
130
self.wrapper.set_font_families(font_families, cx);
130
131
}
131
132
133
pub(super) fn set_hanging_indents(
134
&mut self,
135
hanging_indents: std::rc::Rc<[Range<usize>]>,
136
cx: &mut App,
137
) {
138
self.wrapper.set_hanging_indents(hanging_indents, cx);
139
}
140
132
141
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
133
142
self.wrapper.set_wrap_width(wrap_width, cx);
134
143
}
@@ -109,6 +109,7 @@ impl WrapMap {109
) {109
) {110
self.wrapper.adjust_inline_metrics(range, new_text.len());110
self.wrapper.adjust_inline_metrics(range, new_text.len());111
self.wrapper.adjust_font_families(range, new_text.len());111
self.wrapper.adjust_font_families(range, new_text.len());112
self.wrapper.adjust_hanging_indents(range, new_text.len());112
self.wrapper.update(changed_text, range, new_text, cx);113
self.wrapper.update(changed_text, range, new_text, cx);113
}114
}114
115
@@ -129,6 +130,14 @@ impl WrapMap {129
self.wrapper.set_font_families(font_families, cx);130
self.wrapper.set_font_families(font_families, cx);130
}131
}131
132
133
pub(super) fn set_hanging_indents(134
&mut self,135
hanging_indents: std::rc::Rc<[Range<usize>]>,136
cx: &mut App,137
) {138
self.wrapper.set_hanging_indents(hanging_indents, cx);139
}140
132
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {141
pub(super) fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {133
self.wrapper.set_wrap_width(wrap_width, cx);142
self.wrapper.set_wrap_width(wrap_width, cx);134
}143
}