1mod block_map;
2mod fold_map;
3mod inlay_map;
4mod tab_map;
5mod wrap_map;
6
7use crate::{
8 link_go_to_definition::InlayHighlight, movement::TextLayoutDetails, Anchor, AnchorRangeExt,
9 EditorStyle, InlayId, MultiBuffer, MultiBufferSnapshot, ToOffset, ToPoint,
10};
11pub use block_map::{BlockMap, BlockPoint};
12use collections::{BTreeMap, HashMap, HashSet};
13use fold_map::FoldMap;
14use gpui::{
15 color::Color,
16 fonts::{FontId, HighlightStyle, Underline},
17 text_layout::{Line, RunStyle},
18 Entity, ModelContext, ModelHandle,
19};
20use inlay_map::InlayMap;
21use language::{
22 language_settings::language_settings, OffsetUtf16, Point, Subscription as BufferSubscription,
23};
24use lsp::DiagnosticSeverity;
25use std::{any::TypeId, borrow::Cow, fmt::Debug, num::NonZeroU32, ops::Range, sync::Arc};
26use sum_tree::{Bias, TreeMap};
27use tab_map::TabMap;
28use wrap_map::WrapMap;
29
30pub use block_map::{
31 BlockBufferRows as DisplayBufferRows, BlockChunks as DisplayChunks, BlockContext,
32 BlockDisposition, BlockId, BlockProperties, BlockStyle, RenderBlock, TransformBlock,
33};
34
35pub use self::fold_map::FoldPoint;
36pub use self::inlay_map::{Inlay, InlayOffset, InlayPoint};
37
38#[derive(Copy, Clone, Debug, PartialEq, Eq)]
39pub enum FoldStatus {
40 Folded,
41 Foldable,
42}
43
44pub trait ToDisplayPoint {
45 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint;
46}
47
48type TextHighlights = TreeMap<Option<TypeId>, Arc<(HighlightStyle, Vec<Range<Anchor>>)>>;
49type InlayHighlights = BTreeMap<TypeId, HashMap<InlayId, (HighlightStyle, InlayHighlight)>>;
50
51pub struct DisplayMap {
52 buffer: ModelHandle<MultiBuffer>,
53 buffer_subscription: BufferSubscription,
54 fold_map: FoldMap,
55 inlay_map: InlayMap,
56 tab_map: TabMap,
57 wrap_map: ModelHandle<WrapMap>,
58 block_map: BlockMap,
59 text_highlights: TextHighlights,
60 inlay_highlights: InlayHighlights,
61 pub clip_at_line_ends: bool,
62}
63
64impl Entity for DisplayMap {
65 type Event = ();
66}
67
68impl DisplayMap {
69 pub fn new(
70 buffer: ModelHandle<MultiBuffer>,
71 font_id: FontId,
72 font_size: f32,
73 wrap_width: Option<f32>,
74 buffer_header_height: u8,
75 excerpt_header_height: u8,
76 cx: &mut ModelContext<Self>,
77 ) -> Self {
78 let buffer_subscription = buffer.update(cx, |buffer, _| buffer.subscribe());
79
80 let tab_size = Self::tab_size(&buffer, cx);
81 let (inlay_map, snapshot) = InlayMap::new(buffer.read(cx).snapshot(cx));
82 let (fold_map, snapshot) = FoldMap::new(snapshot);
83 let (tab_map, snapshot) = TabMap::new(snapshot, tab_size);
84 let (wrap_map, snapshot) = WrapMap::new(snapshot, font_id, font_size, wrap_width, cx);
85 let block_map = BlockMap::new(snapshot, buffer_header_height, excerpt_header_height);
86 cx.observe(&wrap_map, |_, _, cx| cx.notify()).detach();
87 DisplayMap {
88 buffer,
89 buffer_subscription,
90 fold_map,
91 inlay_map,
92 tab_map,
93 wrap_map,
94 block_map,
95 text_highlights: Default::default(),
96 inlay_highlights: Default::default(),
97 clip_at_line_ends: false,
98 }
99 }
100
101 pub fn snapshot(&mut self, cx: &mut ModelContext<Self>) -> DisplaySnapshot {
102 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
103 let edits = self.buffer_subscription.consume().into_inner();
104 let (inlay_snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
105 let (fold_snapshot, edits) = self.fold_map.read(inlay_snapshot.clone(), edits);
106 let tab_size = Self::tab_size(&self.buffer, cx);
107 let (tab_snapshot, edits) = self.tab_map.sync(fold_snapshot.clone(), edits, tab_size);
108 let (wrap_snapshot, edits) = self
109 .wrap_map
110 .update(cx, |map, cx| map.sync(tab_snapshot.clone(), edits, cx));
111 let block_snapshot = self.block_map.read(wrap_snapshot.clone(), edits);
112
113 DisplaySnapshot {
114 buffer_snapshot: self.buffer.read(cx).snapshot(cx),
115 fold_snapshot,
116 inlay_snapshot,
117 tab_snapshot,
118 wrap_snapshot,
119 block_snapshot,
120 text_highlights: self.text_highlights.clone(),
121 inlay_highlights: self.inlay_highlights.clone(),
122 clip_at_line_ends: self.clip_at_line_ends,
123 }
124 }
125
126 pub fn set_state(&mut self, other: &DisplaySnapshot, cx: &mut ModelContext<Self>) {
127 self.fold(
128 other
129 .folds_in_range(0..other.buffer_snapshot.len())
130 .map(|fold| fold.to_offset(&other.buffer_snapshot)),
131 cx,
132 );
133 }
134
135 pub fn fold<T: ToOffset>(
136 &mut self,
137 ranges: impl IntoIterator<Item = Range<T>>,
138 cx: &mut ModelContext<Self>,
139 ) {
140 let snapshot = self.buffer.read(cx).snapshot(cx);
141 let edits = self.buffer_subscription.consume().into_inner();
142 let tab_size = Self::tab_size(&self.buffer, cx);
143 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
144 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
145 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
146 let (snapshot, edits) = self
147 .wrap_map
148 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
149 self.block_map.read(snapshot, edits);
150 let (snapshot, edits) = fold_map.fold(ranges);
151 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
152 let (snapshot, edits) = self
153 .wrap_map
154 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
155 self.block_map.read(snapshot, edits);
156 }
157
158 pub fn unfold<T: ToOffset>(
159 &mut self,
160 ranges: impl IntoIterator<Item = Range<T>>,
161 inclusive: bool,
162 cx: &mut ModelContext<Self>,
163 ) {
164 let snapshot = self.buffer.read(cx).snapshot(cx);
165 let edits = self.buffer_subscription.consume().into_inner();
166 let tab_size = Self::tab_size(&self.buffer, cx);
167 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
168 let (mut fold_map, snapshot, edits) = self.fold_map.write(snapshot, edits);
169 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
170 let (snapshot, edits) = self
171 .wrap_map
172 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
173 self.block_map.read(snapshot, edits);
174 let (snapshot, edits) = fold_map.unfold(ranges, inclusive);
175 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
176 let (snapshot, edits) = self
177 .wrap_map
178 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
179 self.block_map.read(snapshot, edits);
180 }
181
182 pub fn insert_blocks(
183 &mut self,
184 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
185 cx: &mut ModelContext<Self>,
186 ) -> Vec<BlockId> {
187 let snapshot = self.buffer.read(cx).snapshot(cx);
188 let edits = self.buffer_subscription.consume().into_inner();
189 let tab_size = Self::tab_size(&self.buffer, cx);
190 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
191 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
192 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
193 let (snapshot, edits) = self
194 .wrap_map
195 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
196 let mut block_map = self.block_map.write(snapshot, edits);
197 block_map.insert(blocks)
198 }
199
200 pub fn replace_blocks(&mut self, styles: HashMap<BlockId, RenderBlock>) {
201 self.block_map.replace(styles);
202 }
203
204 pub fn remove_blocks(&mut self, ids: HashSet<BlockId>, cx: &mut ModelContext<Self>) {
205 let snapshot = self.buffer.read(cx).snapshot(cx);
206 let edits = self.buffer_subscription.consume().into_inner();
207 let tab_size = Self::tab_size(&self.buffer, cx);
208 let (snapshot, edits) = self.inlay_map.sync(snapshot, edits);
209 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
210 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
211 let (snapshot, edits) = self
212 .wrap_map
213 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
214 let mut block_map = self.block_map.write(snapshot, edits);
215 block_map.remove(ids);
216 }
217
218 pub fn highlight_text(
219 &mut self,
220 type_id: TypeId,
221 ranges: Vec<Range<Anchor>>,
222 style: HighlightStyle,
223 ) {
224 self.text_highlights
225 .insert(Some(type_id), Arc::new((style, ranges)));
226 }
227
228 pub fn highlight_inlays(
229 &mut self,
230 type_id: TypeId,
231 highlights: Vec<InlayHighlight>,
232 style: HighlightStyle,
233 ) {
234 for highlight in highlights {
235 self.inlay_highlights
236 .entry(type_id)
237 .or_default()
238 .insert(highlight.inlay, (style, highlight));
239 }
240 }
241
242 pub fn text_highlights(&self, type_id: TypeId) -> Option<(HighlightStyle, &[Range<Anchor>])> {
243 let highlights = self.text_highlights.get(&Some(type_id))?;
244 Some((highlights.0, &highlights.1))
245 }
246 pub fn clear_highlights(&mut self, type_id: TypeId) -> bool {
247 let mut cleared = self.text_highlights.remove(&Some(type_id)).is_some();
248 cleared |= self.inlay_highlights.remove(&type_id).is_none();
249 cleared
250 }
251
252 pub fn set_font(&self, font_id: FontId, font_size: f32, cx: &mut ModelContext<Self>) -> bool {
253 self.wrap_map
254 .update(cx, |map, cx| map.set_font(font_id, font_size, cx))
255 }
256
257 pub fn set_fold_ellipses_color(&mut self, color: Color) -> bool {
258 self.fold_map.set_ellipses_color(color)
259 }
260
261 pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut ModelContext<Self>) -> bool {
262 self.wrap_map
263 .update(cx, |map, cx| map.set_wrap_width(width, cx))
264 }
265
266 pub fn current_inlays(&self) -> impl Iterator<Item = &Inlay> {
267 self.inlay_map.current_inlays()
268 }
269
270 pub fn splice_inlays(
271 &mut self,
272 to_remove: Vec<InlayId>,
273 to_insert: Vec<Inlay>,
274 cx: &mut ModelContext<Self>,
275 ) {
276 if to_remove.is_empty() && to_insert.is_empty() {
277 return;
278 }
279 let buffer_snapshot = self.buffer.read(cx).snapshot(cx);
280 let edits = self.buffer_subscription.consume().into_inner();
281 let (snapshot, edits) = self.inlay_map.sync(buffer_snapshot, edits);
282 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
283 let tab_size = Self::tab_size(&self.buffer, cx);
284 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
285 let (snapshot, edits) = self
286 .wrap_map
287 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
288 self.block_map.read(snapshot, edits);
289
290 let (snapshot, edits) = self.inlay_map.splice(to_remove, to_insert);
291 let (snapshot, edits) = self.fold_map.read(snapshot, edits);
292 let (snapshot, edits) = self.tab_map.sync(snapshot, edits, tab_size);
293 let (snapshot, edits) = self
294 .wrap_map
295 .update(cx, |map, cx| map.sync(snapshot, edits, cx));
296 self.block_map.read(snapshot, edits);
297 }
298
299 fn tab_size(buffer: &ModelHandle<MultiBuffer>, cx: &mut ModelContext<Self>) -> NonZeroU32 {
300 let language = buffer
301 .read(cx)
302 .as_singleton()
303 .and_then(|buffer| buffer.read(cx).language());
304 language_settings(language.as_deref(), None, cx).tab_size
305 }
306
307 #[cfg(test)]
308 pub fn is_rewrapping(&self, cx: &gpui::AppContext) -> bool {
309 self.wrap_map.read(cx).is_rewrapping()
310 }
311}
312
313#[derive(Debug, Default)]
314pub struct Highlights<'a> {
315 pub text_highlights: Option<&'a TextHighlights>,
316 pub inlay_highlights: Option<&'a InlayHighlights>,
317 pub inlay_highlight_style: Option<HighlightStyle>,
318 pub suggestion_highlight_style: Option<HighlightStyle>,
319}
320
321pub struct HighlightedChunk<'a> {
322 pub chunk: &'a str,
323 pub style: Option<HighlightStyle>,
324 pub is_tab: bool,
325}
326
327pub struct DisplaySnapshot {
328 pub buffer_snapshot: MultiBufferSnapshot,
329 pub fold_snapshot: fold_map::FoldSnapshot,
330 inlay_snapshot: inlay_map::InlaySnapshot,
331 tab_snapshot: tab_map::TabSnapshot,
332 wrap_snapshot: wrap_map::WrapSnapshot,
333 block_snapshot: block_map::BlockSnapshot,
334 text_highlights: TextHighlights,
335 inlay_highlights: InlayHighlights,
336 clip_at_line_ends: bool,
337}
338
339impl DisplaySnapshot {
340 #[cfg(test)]
341 pub fn fold_count(&self) -> usize {
342 self.fold_snapshot.fold_count()
343 }
344
345 pub fn is_empty(&self) -> bool {
346 self.buffer_snapshot.len() == 0
347 }
348
349 pub fn buffer_rows(&self, start_row: u32) -> DisplayBufferRows {
350 self.block_snapshot.buffer_rows(start_row)
351 }
352
353 pub fn max_buffer_row(&self) -> u32 {
354 self.buffer_snapshot.max_buffer_row()
355 }
356
357 pub fn prev_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
358 loop {
359 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
360 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Left);
361 fold_point.0.column = 0;
362 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
363 point = self.inlay_snapshot.to_buffer_point(inlay_point);
364
365 let mut display_point = self.point_to_display_point(point, Bias::Left);
366 *display_point.column_mut() = 0;
367 let next_point = self.display_point_to_point(display_point, Bias::Left);
368 if next_point == point {
369 return (point, display_point);
370 }
371 point = next_point;
372 }
373 }
374
375 pub fn next_line_boundary(&self, mut point: Point) -> (Point, DisplayPoint) {
376 loop {
377 let mut inlay_point = self.inlay_snapshot.to_inlay_point(point);
378 let mut fold_point = self.fold_snapshot.to_fold_point(inlay_point, Bias::Right);
379 fold_point.0.column = self.fold_snapshot.line_len(fold_point.row());
380 inlay_point = fold_point.to_inlay_point(&self.fold_snapshot);
381 point = self.inlay_snapshot.to_buffer_point(inlay_point);
382
383 let mut display_point = self.point_to_display_point(point, Bias::Right);
384 *display_point.column_mut() = self.line_len(display_point.row());
385 let next_point = self.display_point_to_point(display_point, Bias::Right);
386 if next_point == point {
387 return (point, display_point);
388 }
389 point = next_point;
390 }
391 }
392
393 // used by line_mode selections and tries to match vim behaviour
394 pub fn expand_to_line(&self, range: Range<Point>) -> Range<Point> {
395 let new_start = if range.start.row == 0 {
396 Point::new(0, 0)
397 } else if range.start.row == self.max_buffer_row()
398 || (range.end.column > 0 && range.end.row == self.max_buffer_row())
399 {
400 Point::new(range.start.row - 1, self.line_len(range.start.row - 1))
401 } else {
402 self.prev_line_boundary(range.start).0
403 };
404
405 let new_end = if range.end.column == 0 {
406 range.end
407 } else if range.end.row < self.max_buffer_row() {
408 self.buffer_snapshot
409 .clip_point(Point::new(range.end.row + 1, 0), Bias::Left)
410 } else {
411 self.buffer_snapshot.max_point()
412 };
413
414 new_start..new_end
415 }
416
417 fn point_to_display_point(&self, point: Point, bias: Bias) -> DisplayPoint {
418 let inlay_point = self.inlay_snapshot.to_inlay_point(point);
419 let fold_point = self.fold_snapshot.to_fold_point(inlay_point, bias);
420 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
421 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
422 let block_point = self.block_snapshot.to_block_point(wrap_point);
423 DisplayPoint(block_point)
424 }
425
426 fn display_point_to_point(&self, point: DisplayPoint, bias: Bias) -> Point {
427 self.inlay_snapshot
428 .to_buffer_point(self.display_point_to_inlay_point(point, bias))
429 }
430
431 pub fn display_point_to_inlay_offset(&self, point: DisplayPoint, bias: Bias) -> InlayOffset {
432 self.inlay_snapshot
433 .to_offset(self.display_point_to_inlay_point(point, bias))
434 }
435
436 pub fn anchor_to_inlay_offset(&self, anchor: Anchor) -> InlayOffset {
437 self.inlay_snapshot
438 .to_inlay_offset(anchor.to_offset(&self.buffer_snapshot))
439 }
440
441 fn display_point_to_inlay_point(&self, point: DisplayPoint, bias: Bias) -> InlayPoint {
442 let block_point = point.0;
443 let wrap_point = self.block_snapshot.to_wrap_point(block_point);
444 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
445 let fold_point = self.tab_snapshot.to_fold_point(tab_point, bias).0;
446 fold_point.to_inlay_point(&self.fold_snapshot)
447 }
448
449 pub fn display_point_to_fold_point(&self, point: DisplayPoint, bias: Bias) -> FoldPoint {
450 let block_point = point.0;
451 let wrap_point = self.block_snapshot.to_wrap_point(block_point);
452 let tab_point = self.wrap_snapshot.to_tab_point(wrap_point);
453 self.tab_snapshot.to_fold_point(tab_point, bias).0
454 }
455
456 pub fn fold_point_to_display_point(&self, fold_point: FoldPoint) -> DisplayPoint {
457 let tab_point = self.tab_snapshot.to_tab_point(fold_point);
458 let wrap_point = self.wrap_snapshot.tab_point_to_wrap_point(tab_point);
459 let block_point = self.block_snapshot.to_block_point(wrap_point);
460 DisplayPoint(block_point)
461 }
462
463 pub fn max_point(&self) -> DisplayPoint {
464 DisplayPoint(self.block_snapshot.max_point())
465 }
466
467 /// Returns text chunks starting at the given display row until the end of the file
468 pub fn text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
469 self.block_snapshot
470 .chunks(
471 display_row..self.max_point().row() + 1,
472 false,
473 Highlights::default(),
474 )
475 .map(|h| h.text)
476 }
477
478 /// Returns text chunks starting at the end of the given display row in reverse until the start of the file
479 pub fn reverse_text_chunks(&self, display_row: u32) -> impl Iterator<Item = &str> {
480 (0..=display_row).into_iter().rev().flat_map(|row| {
481 self.block_snapshot
482 .chunks(row..row + 1, false, Highlights::default())
483 .map(|h| h.text)
484 .collect::<Vec<_>>()
485 .into_iter()
486 .rev()
487 })
488 }
489
490 pub fn chunks<'a>(
491 &'a self,
492 display_rows: Range<u32>,
493 language_aware: bool,
494 inlay_highlight_style: Option<HighlightStyle>,
495 suggestion_highlight_style: Option<HighlightStyle>,
496 ) -> DisplayChunks<'a> {
497 self.block_snapshot.chunks(
498 display_rows,
499 language_aware,
500 Highlights {
501 text_highlights: Some(&self.text_highlights),
502 inlay_highlights: Some(&self.inlay_highlights),
503 inlay_highlight_style,
504 suggestion_highlight_style,
505 },
506 )
507 }
508
509 pub fn highlighted_chunks<'a>(
510 &'a self,
511 display_rows: Range<u32>,
512 style: &'a EditorStyle,
513 ) -> impl Iterator<Item = HighlightedChunk<'a>> {
514 self.chunks(
515 display_rows,
516 true,
517 Some(style.theme.hint),
518 Some(style.theme.suggestion),
519 )
520 .map(|chunk| {
521 let mut highlight_style = chunk
522 .syntax_highlight_id
523 .and_then(|id| id.style(&style.syntax));
524
525 if let Some(chunk_highlight) = chunk.highlight_style {
526 if let Some(highlight_style) = highlight_style.as_mut() {
527 highlight_style.highlight(chunk_highlight);
528 } else {
529 highlight_style = Some(chunk_highlight);
530 }
531 }
532
533 let mut diagnostic_highlight = HighlightStyle::default();
534
535 if chunk.is_unnecessary {
536 diagnostic_highlight.fade_out = Some(style.unnecessary_code_fade);
537 }
538
539 if let Some(severity) = chunk.diagnostic_severity {
540 // Omit underlines for HINT/INFO diagnostics on 'unnecessary' code.
541 if severity <= DiagnosticSeverity::WARNING || !chunk.is_unnecessary {
542 let diagnostic_style = super::diagnostic_style(severity, true, style);
543 diagnostic_highlight.underline = Some(Underline {
544 color: Some(diagnostic_style.message.text.color),
545 thickness: 1.0.into(),
546 squiggly: true,
547 });
548 }
549 }
550
551 if let Some(highlight_style) = highlight_style.as_mut() {
552 highlight_style.highlight(diagnostic_highlight);
553 } else {
554 highlight_style = Some(diagnostic_highlight);
555 }
556
557 HighlightedChunk {
558 chunk: chunk.text,
559 style: highlight_style,
560 is_tab: chunk.is_tab,
561 }
562 })
563 }
564
565 fn layout_line_for_row(
566 &self,
567 display_row: u32,
568 TextLayoutDetails {
569 font_cache,
570 text_layout_cache,
571 editor_style,
572 }: &TextLayoutDetails,
573 ) -> Line {
574 let mut styles = Vec::new();
575 let mut line = String::new();
576
577 let range = display_row..display_row + 1;
578 for chunk in self.highlighted_chunks(range, editor_style) {
579 line.push_str(chunk.chunk);
580
581 let text_style = if let Some(style) = chunk.style {
582 editor_style
583 .text
584 .clone()
585 .highlight(style, font_cache)
586 .map(Cow::Owned)
587 .unwrap_or_else(|_| Cow::Borrowed(&editor_style.text))
588 } else {
589 Cow::Borrowed(&editor_style.text)
590 };
591
592 styles.push((
593 chunk.chunk.len(),
594 RunStyle {
595 font_id: text_style.font_id,
596 color: text_style.color,
597 underline: text_style.underline,
598 },
599 ));
600 }
601
602 text_layout_cache.layout_str(&line, editor_style.text.font_size, &styles)
603 }
604
605 pub fn x_for_point(
606 &self,
607 display_point: DisplayPoint,
608 text_layout_details: &TextLayoutDetails,
609 ) -> f32 {
610 let layout_line = self.layout_line_for_row(display_point.row(), text_layout_details);
611 layout_line.x_for_index(display_point.column() as usize)
612 }
613
614 pub fn column_for_x(
615 &self,
616 display_row: u32,
617 x_coordinate: f32,
618 text_layout_details: &TextLayoutDetails,
619 ) -> u32 {
620 let layout_line = self.layout_line_for_row(display_row, text_layout_details);
621 layout_line.closest_index_for_x(x_coordinate) as u32
622 }
623
624 pub fn chars_at(
625 &self,
626 mut point: DisplayPoint,
627 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
628 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
629 self.text_chunks(point.row())
630 .flat_map(str::chars)
631 .skip_while({
632 let mut column = 0;
633 move |char| {
634 let at_point = column >= point.column();
635 column += char.len_utf8() as u32;
636 !at_point
637 }
638 })
639 .map(move |ch| {
640 let result = (ch, point);
641 if ch == '\n' {
642 *point.row_mut() += 1;
643 *point.column_mut() = 0;
644 } else {
645 *point.column_mut() += ch.len_utf8() as u32;
646 }
647 result
648 })
649 }
650
651 pub fn reverse_chars_at(
652 &self,
653 mut point: DisplayPoint,
654 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
655 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
656 self.reverse_text_chunks(point.row())
657 .flat_map(|chunk| chunk.chars().rev())
658 .skip_while({
659 let mut column = self.line_len(point.row());
660 if self.max_point().row() > point.row() {
661 column += 1;
662 }
663
664 move |char| {
665 let at_point = column <= point.column();
666 column = column.saturating_sub(char.len_utf8() as u32);
667 !at_point
668 }
669 })
670 .map(move |ch| {
671 if ch == '\n' {
672 *point.row_mut() -= 1;
673 *point.column_mut() = self.line_len(point.row());
674 } else {
675 *point.column_mut() = point.column().saturating_sub(ch.len_utf8() as u32);
676 }
677 (ch, point)
678 })
679 }
680
681 pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
682 let mut count = 0;
683 let mut column = 0;
684 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
685 if column >= target {
686 break;
687 }
688 count += 1;
689 column += c.len_utf8() as u32;
690 }
691 count
692 }
693
694 pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
695 let mut column = 0;
696
697 for (count, (c, _)) in self.chars_at(DisplayPoint::new(display_row, 0)).enumerate() {
698 if c == '\n' || count >= char_count as usize {
699 break;
700 }
701 column += c.len_utf8() as u32;
702 }
703
704 column
705 }
706
707 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
708 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
709 if self.clip_at_line_ends {
710 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
711 }
712 DisplayPoint(clipped)
713 }
714
715 pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
716 let mut point = point.0;
717 if point.column == self.line_len(point.row) {
718 point.column = point.column.saturating_sub(1);
719 point = self.block_snapshot.clip_point(point, Bias::Left);
720 }
721 DisplayPoint(point)
722 }
723
724 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
725 where
726 T: ToOffset,
727 {
728 self.fold_snapshot.folds_in_range(range)
729 }
730
731 pub fn blocks_in_range(
732 &self,
733 rows: Range<u32>,
734 ) -> impl Iterator<Item = (u32, &TransformBlock)> {
735 self.block_snapshot.blocks_in_range(rows)
736 }
737
738 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
739 self.fold_snapshot.intersects_fold(offset)
740 }
741
742 pub fn is_line_folded(&self, buffer_row: u32) -> bool {
743 self.fold_snapshot.is_line_folded(buffer_row)
744 }
745
746 pub fn is_block_line(&self, display_row: u32) -> bool {
747 self.block_snapshot.is_block_line(display_row)
748 }
749
750 pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
751 let wrap_row = self
752 .block_snapshot
753 .to_wrap_point(BlockPoint::new(display_row, 0))
754 .row();
755 self.wrap_snapshot.soft_wrap_indent(wrap_row)
756 }
757
758 pub fn text(&self) -> String {
759 self.text_chunks(0).collect()
760 }
761
762 pub fn line(&self, display_row: u32) -> String {
763 let mut result = String::new();
764 for chunk in self.text_chunks(display_row) {
765 if let Some(ix) = chunk.find('\n') {
766 result.push_str(&chunk[0..ix]);
767 break;
768 } else {
769 result.push_str(chunk);
770 }
771 }
772 result
773 }
774
775 pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
776 let mut indent = 0;
777 let mut is_blank = true;
778 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
779 if c == ' ' {
780 indent += 1;
781 } else {
782 is_blank = c == '\n';
783 break;
784 }
785 }
786 (indent, is_blank)
787 }
788
789 pub fn line_indent_for_buffer_row(&self, buffer_row: u32) -> (u32, bool) {
790 let (buffer, range) = self
791 .buffer_snapshot
792 .buffer_line_for_row(buffer_row)
793 .unwrap();
794
795 let mut indent_size = 0;
796 let mut is_blank = false;
797 for c in buffer.chars_at(Point::new(range.start.row, 0)) {
798 if c == ' ' || c == '\t' {
799 indent_size += 1;
800 } else {
801 if c == '\n' {
802 is_blank = true;
803 }
804 break;
805 }
806 }
807
808 (indent_size, is_blank)
809 }
810
811 pub fn line_len(&self, row: u32) -> u32 {
812 self.block_snapshot.line_len(row)
813 }
814
815 pub fn longest_row(&self) -> u32 {
816 self.block_snapshot.longest_row()
817 }
818
819 pub fn fold_for_line(self: &Self, buffer_row: u32) -> Option<FoldStatus> {
820 if self.is_line_folded(buffer_row) {
821 Some(FoldStatus::Folded)
822 } else if self.is_foldable(buffer_row) {
823 Some(FoldStatus::Foldable)
824 } else {
825 None
826 }
827 }
828
829 pub fn is_foldable(self: &Self, buffer_row: u32) -> bool {
830 let max_row = self.buffer_snapshot.max_buffer_row();
831 if buffer_row >= max_row {
832 return false;
833 }
834
835 let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
836 if is_blank {
837 return false;
838 }
839
840 for next_row in (buffer_row + 1)..=max_row {
841 let (next_indent_size, next_line_is_blank) = self.line_indent_for_buffer_row(next_row);
842 if next_indent_size > indent_size {
843 return true;
844 } else if !next_line_is_blank {
845 break;
846 }
847 }
848
849 false
850 }
851
852 pub fn foldable_range(self: &Self, buffer_row: u32) -> Option<Range<Point>> {
853 let start = Point::new(buffer_row, self.buffer_snapshot.line_len(buffer_row));
854 if self.is_foldable(start.row) && !self.is_line_folded(start.row) {
855 let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
856 let max_point = self.buffer_snapshot.max_point();
857 let mut end = None;
858
859 for row in (buffer_row + 1)..=max_point.row {
860 let (indent, is_blank) = self.line_indent_for_buffer_row(row);
861 if !is_blank && indent <= start_indent {
862 let prev_row = row - 1;
863 end = Some(Point::new(
864 prev_row,
865 self.buffer_snapshot.line_len(prev_row),
866 ));
867 break;
868 }
869 }
870 let end = end.unwrap_or(max_point);
871 Some(start..end)
872 } else {
873 None
874 }
875 }
876
877 #[cfg(any(test, feature = "test-support"))]
878 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
879 &self,
880 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
881 let type_id = TypeId::of::<Tag>();
882 self.text_highlights.get(&Some(type_id)).cloned()
883 }
884
885 #[cfg(any(test, feature = "test-support"))]
886 pub fn inlay_highlights<Tag: ?Sized + 'static>(
887 &self,
888 ) -> Option<&HashMap<InlayId, (HighlightStyle, InlayHighlight)>> {
889 let type_id = TypeId::of::<Tag>();
890 self.inlay_highlights.get(&type_id)
891 }
892}
893
894#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
895pub struct DisplayPoint(BlockPoint);
896
897impl Debug for DisplayPoint {
898 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
899 f.write_fmt(format_args!(
900 "DisplayPoint({}, {})",
901 self.row(),
902 self.column()
903 ))
904 }
905}
906
907impl DisplayPoint {
908 pub fn new(row: u32, column: u32) -> Self {
909 Self(BlockPoint(Point::new(row, column)))
910 }
911
912 pub fn zero() -> Self {
913 Self::new(0, 0)
914 }
915
916 pub fn is_zero(&self) -> bool {
917 self.0.is_zero()
918 }
919
920 pub fn row(self) -> u32 {
921 self.0.row
922 }
923
924 pub fn column(self) -> u32 {
925 self.0.column
926 }
927
928 pub fn row_mut(&mut self) -> &mut u32 {
929 &mut self.0.row
930 }
931
932 pub fn column_mut(&mut self) -> &mut u32 {
933 &mut self.0.column
934 }
935
936 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
937 map.display_point_to_point(self, Bias::Left)
938 }
939
940 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
941 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
942 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
943 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
944 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
945 map.inlay_snapshot
946 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
947 }
948}
949
950impl ToDisplayPoint for usize {
951 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
952 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
953 }
954}
955
956impl ToDisplayPoint for OffsetUtf16 {
957 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
958 self.to_offset(&map.buffer_snapshot).to_display_point(map)
959 }
960}
961
962impl ToDisplayPoint for Point {
963 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
964 map.point_to_display_point(*self, Bias::Left)
965 }
966}
967
968impl ToDisplayPoint for Anchor {
969 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
970 self.to_point(&map.buffer_snapshot).to_display_point(map)
971 }
972}
973
974pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
975 let max_row = display_map.max_point().row();
976 let start_row = display_row + 1;
977 let mut current = None;
978 std::iter::from_fn(move || {
979 if current == None {
980 current = Some(start_row);
981 } else {
982 current = Some(current.unwrap() + 1)
983 }
984 if current.unwrap() > max_row {
985 None
986 } else {
987 current
988 }
989 })
990}
991
992#[cfg(test)]
993pub mod tests {
994 use super::*;
995 use crate::{
996 movement,
997 test::{editor_test_context::EditorTestContext, marked_display_snapshot},
998 };
999 use gpui::{color::Color, elements::*, test::observe, AppContext};
1000 use language::{
1001 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1002 Buffer, Language, LanguageConfig, SelectionGoal,
1003 };
1004 use project::Project;
1005 use rand::{prelude::*, Rng};
1006 use settings::SettingsStore;
1007 use smol::stream::StreamExt;
1008 use std::{env, sync::Arc};
1009 use theme::{SyntaxTheme, Theme};
1010 use util::test::{marked_text_ranges, sample_text};
1011 use Bias::*;
1012
1013 #[gpui::test(iterations = 100)]
1014 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1015 cx.foreground().set_block_on_ticks(0..=50);
1016 cx.foreground().forbid_parking();
1017 let operations = env::var("OPERATIONS")
1018 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1019 .unwrap_or(10);
1020
1021 let font_cache = cx.font_cache().clone();
1022 let mut tab_size = rng.gen_range(1..=4);
1023 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1024 let excerpt_header_height = rng.gen_range(1..=5);
1025 let family_id = font_cache
1026 .load_family(&["Helvetica"], &Default::default())
1027 .unwrap();
1028 let font_id = font_cache
1029 .select_font(family_id, &Default::default())
1030 .unwrap();
1031 let font_size = 14.0;
1032 let max_wrap_width = 300.0;
1033 let mut wrap_width = if rng.gen_bool(0.1) {
1034 None
1035 } else {
1036 Some(rng.gen_range(0.0..=max_wrap_width))
1037 };
1038
1039 log::info!("tab size: {}", tab_size);
1040 log::info!("wrap width: {:?}", wrap_width);
1041
1042 cx.update(|cx| {
1043 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1044 });
1045
1046 let buffer = cx.update(|cx| {
1047 if rng.gen() {
1048 let len = rng.gen_range(0..10);
1049 let text = util::RandomCharIter::new(&mut rng)
1050 .take(len)
1051 .collect::<String>();
1052 MultiBuffer::build_simple(&text, cx)
1053 } else {
1054 MultiBuffer::build_random(&mut rng, cx)
1055 }
1056 });
1057
1058 let map = cx.add_model(|cx| {
1059 DisplayMap::new(
1060 buffer.clone(),
1061 font_id,
1062 font_size,
1063 wrap_width,
1064 buffer_start_excerpt_header_height,
1065 excerpt_header_height,
1066 cx,
1067 )
1068 });
1069 let mut notifications = observe(&map, cx);
1070 let mut fold_count = 0;
1071 let mut blocks = Vec::new();
1072
1073 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1074 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1075 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1076 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1077 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1078 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1079 log::info!("display text: {:?}", snapshot.text());
1080
1081 for _i in 0..operations {
1082 match rng.gen_range(0..100) {
1083 0..=19 => {
1084 wrap_width = if rng.gen_bool(0.2) {
1085 None
1086 } else {
1087 Some(rng.gen_range(0.0..=max_wrap_width))
1088 };
1089 log::info!("setting wrap width to {:?}", wrap_width);
1090 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1091 }
1092 20..=29 => {
1093 let mut tab_sizes = vec![1, 2, 3, 4];
1094 tab_sizes.remove((tab_size - 1) as usize);
1095 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1096 log::info!("setting tab size to {:?}", tab_size);
1097 cx.update(|cx| {
1098 cx.update_global::<SettingsStore, _, _>(|store, cx| {
1099 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1100 s.defaults.tab_size = NonZeroU32::new(tab_size);
1101 });
1102 });
1103 });
1104 }
1105 30..=44 => {
1106 map.update(cx, |map, cx| {
1107 if rng.gen() || blocks.is_empty() {
1108 let buffer = map.snapshot(cx).buffer_snapshot;
1109 let block_properties = (0..rng.gen_range(1..=1))
1110 .map(|_| {
1111 let position =
1112 buffer.anchor_after(buffer.clip_offset(
1113 rng.gen_range(0..=buffer.len()),
1114 Bias::Left,
1115 ));
1116
1117 let disposition = if rng.gen() {
1118 BlockDisposition::Above
1119 } else {
1120 BlockDisposition::Below
1121 };
1122 let height = rng.gen_range(1..5);
1123 log::info!(
1124 "inserting block {:?} {:?} with height {}",
1125 disposition,
1126 position.to_point(&buffer),
1127 height
1128 );
1129 BlockProperties {
1130 style: BlockStyle::Fixed,
1131 position,
1132 height,
1133 disposition,
1134 render: Arc::new(|_| Empty::new().into_any()),
1135 }
1136 })
1137 .collect::<Vec<_>>();
1138 blocks.extend(map.insert_blocks(block_properties, cx));
1139 } else {
1140 blocks.shuffle(&mut rng);
1141 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1142 let block_ids_to_remove = (0..remove_count)
1143 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1144 .collect();
1145 log::info!("removing block ids {:?}", block_ids_to_remove);
1146 map.remove_blocks(block_ids_to_remove, cx);
1147 }
1148 });
1149 }
1150 45..=79 => {
1151 let mut ranges = Vec::new();
1152 for _ in 0..rng.gen_range(1..=3) {
1153 buffer.read_with(cx, |buffer, cx| {
1154 let buffer = buffer.read(cx);
1155 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1156 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1157 ranges.push(start..end);
1158 });
1159 }
1160
1161 if rng.gen() && fold_count > 0 {
1162 log::info!("unfolding ranges: {:?}", ranges);
1163 map.update(cx, |map, cx| {
1164 map.unfold(ranges, true, cx);
1165 });
1166 } else {
1167 log::info!("folding ranges: {:?}", ranges);
1168 map.update(cx, |map, cx| {
1169 map.fold(ranges, cx);
1170 });
1171 }
1172 }
1173 _ => {
1174 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1175 }
1176 }
1177
1178 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1179 notifications.next().await.unwrap();
1180 }
1181
1182 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1183 fold_count = snapshot.fold_count();
1184 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1185 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1186 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1187 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1188 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1189 log::info!("display text: {:?}", snapshot.text());
1190
1191 // Line boundaries
1192 let buffer = &snapshot.buffer_snapshot;
1193 for _ in 0..5 {
1194 let row = rng.gen_range(0..=buffer.max_point().row);
1195 let column = rng.gen_range(0..=buffer.line_len(row));
1196 let point = buffer.clip_point(Point::new(row, column), Left);
1197
1198 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1199 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1200
1201 assert!(prev_buffer_bound <= point);
1202 assert!(next_buffer_bound >= point);
1203 assert_eq!(prev_buffer_bound.column, 0);
1204 assert_eq!(prev_display_bound.column(), 0);
1205 if next_buffer_bound < buffer.max_point() {
1206 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1207 }
1208
1209 assert_eq!(
1210 prev_display_bound,
1211 prev_buffer_bound.to_display_point(&snapshot),
1212 "row boundary before {:?}. reported buffer row boundary: {:?}",
1213 point,
1214 prev_buffer_bound
1215 );
1216 assert_eq!(
1217 next_display_bound,
1218 next_buffer_bound.to_display_point(&snapshot),
1219 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1220 point,
1221 next_buffer_bound
1222 );
1223 assert_eq!(
1224 prev_buffer_bound,
1225 prev_display_bound.to_point(&snapshot),
1226 "row boundary before {:?}. reported display row boundary: {:?}",
1227 point,
1228 prev_display_bound
1229 );
1230 assert_eq!(
1231 next_buffer_bound,
1232 next_display_bound.to_point(&snapshot),
1233 "row boundary after {:?}. reported display row boundary: {:?}",
1234 point,
1235 next_display_bound
1236 );
1237 }
1238
1239 // Movement
1240 let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1241 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1242 for _ in 0..5 {
1243 let row = rng.gen_range(0..=snapshot.max_point().row());
1244 let column = rng.gen_range(0..=snapshot.line_len(row));
1245 let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1246
1247 log::info!("Moving from point {:?}", point);
1248
1249 let moved_right = movement::right(&snapshot, point);
1250 log::info!("Right {:?}", moved_right);
1251 if point < max_point {
1252 assert!(moved_right > point);
1253 if point.column() == snapshot.line_len(point.row())
1254 || snapshot.soft_wrap_indent(point.row()).is_some()
1255 && point.column() == snapshot.line_len(point.row()) - 1
1256 {
1257 assert!(moved_right.row() > point.row());
1258 }
1259 } else {
1260 assert_eq!(moved_right, point);
1261 }
1262
1263 let moved_left = movement::left(&snapshot, point);
1264 log::info!("Left {:?}", moved_left);
1265 if point > min_point {
1266 assert!(moved_left < point);
1267 if point.column() == 0 {
1268 assert!(moved_left.row() < point.row());
1269 }
1270 } else {
1271 assert_eq!(moved_left, point);
1272 }
1273 }
1274 }
1275 }
1276
1277 #[gpui::test(retries = 5)]
1278 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1279 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1280 cx.update(|cx| {
1281 init_test(cx, |_| {});
1282 });
1283
1284 let mut cx = EditorTestContext::new(cx).await;
1285 let editor = cx.editor.clone();
1286 let window = cx.window.clone();
1287
1288 cx.update_window(window, |cx| {
1289 let text_layout_details =
1290 editor.read_with(cx, |editor, cx| TextLayoutDetails::new(editor, cx));
1291
1292 let font_cache = cx.font_cache().clone();
1293
1294 let family_id = font_cache
1295 .load_family(&["Helvetica"], &Default::default())
1296 .unwrap();
1297 let font_id = font_cache
1298 .select_font(family_id, &Default::default())
1299 .unwrap();
1300 let font_size = 12.0;
1301 let wrap_width = Some(64.);
1302
1303 let text = "one two three four five\nsix seven eight";
1304 let buffer = MultiBuffer::build_simple(text, cx);
1305 let map = cx.add_model(|cx| {
1306 DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1307 });
1308
1309 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1310 assert_eq!(
1311 snapshot.text_chunks(0).collect::<String>(),
1312 "one two \nthree four \nfive\nsix seven \neight"
1313 );
1314 assert_eq!(
1315 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1316 DisplayPoint::new(0, 7)
1317 );
1318 assert_eq!(
1319 snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1320 DisplayPoint::new(1, 0)
1321 );
1322 assert_eq!(
1323 movement::right(&snapshot, DisplayPoint::new(0, 7)),
1324 DisplayPoint::new(1, 0)
1325 );
1326 assert_eq!(
1327 movement::left(&snapshot, DisplayPoint::new(1, 0)),
1328 DisplayPoint::new(0, 7)
1329 );
1330
1331 let x = snapshot.x_for_point(DisplayPoint::new(1, 10), &text_layout_details);
1332 assert_eq!(
1333 movement::up(
1334 &snapshot,
1335 DisplayPoint::new(1, 10),
1336 SelectionGoal::None,
1337 false,
1338 &text_layout_details,
1339 ),
1340 (
1341 DisplayPoint::new(0, 7),
1342 SelectionGoal::HorizontalPosition(x)
1343 )
1344 );
1345 assert_eq!(
1346 movement::down(
1347 &snapshot,
1348 DisplayPoint::new(0, 7),
1349 SelectionGoal::HorizontalPosition(x),
1350 false,
1351 &text_layout_details
1352 ),
1353 (
1354 DisplayPoint::new(1, 10),
1355 SelectionGoal::HorizontalPosition(x)
1356 )
1357 );
1358 assert_eq!(
1359 movement::down(
1360 &snapshot,
1361 DisplayPoint::new(1, 10),
1362 SelectionGoal::HorizontalPosition(x),
1363 false,
1364 &text_layout_details
1365 ),
1366 (
1367 DisplayPoint::new(2, 4),
1368 SelectionGoal::HorizontalPosition(x)
1369 )
1370 );
1371
1372 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1373 buffer.update(cx, |buffer, cx| {
1374 buffer.edit([(ix..ix, "and ")], None, cx);
1375 });
1376
1377 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1378 assert_eq!(
1379 snapshot.text_chunks(1).collect::<String>(),
1380 "three four \nfive\nsix and \nseven eight"
1381 );
1382
1383 // Re-wrap on font size changes
1384 map.update(cx, |map, cx| map.set_font(font_id, font_size + 3., cx));
1385
1386 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1387 assert_eq!(
1388 snapshot.text_chunks(1).collect::<String>(),
1389 "three \nfour five\nsix and \nseven \neight"
1390 )
1391 });
1392 }
1393
1394 #[gpui::test]
1395 fn test_text_chunks(cx: &mut gpui::AppContext) {
1396 init_test(cx, |_| {});
1397
1398 let text = sample_text(6, 6, 'a');
1399 let buffer = MultiBuffer::build_simple(&text, cx);
1400 let family_id = cx
1401 .font_cache()
1402 .load_family(&["Helvetica"], &Default::default())
1403 .unwrap();
1404 let font_id = cx
1405 .font_cache()
1406 .select_font(family_id, &Default::default())
1407 .unwrap();
1408 let font_size = 14.0;
1409 let map =
1410 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1411
1412 buffer.update(cx, |buffer, cx| {
1413 buffer.edit(
1414 vec![
1415 (Point::new(1, 0)..Point::new(1, 0), "\t"),
1416 (Point::new(1, 1)..Point::new(1, 1), "\t"),
1417 (Point::new(2, 1)..Point::new(2, 1), "\t"),
1418 ],
1419 None,
1420 cx,
1421 )
1422 });
1423
1424 assert_eq!(
1425 map.update(cx, |map, cx| map.snapshot(cx))
1426 .text_chunks(1)
1427 .collect::<String>()
1428 .lines()
1429 .next(),
1430 Some(" b bbbbb")
1431 );
1432 assert_eq!(
1433 map.update(cx, |map, cx| map.snapshot(cx))
1434 .text_chunks(2)
1435 .collect::<String>()
1436 .lines()
1437 .next(),
1438 Some("c ccccc")
1439 );
1440 }
1441
1442 #[gpui::test]
1443 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1444 use unindent::Unindent as _;
1445
1446 let text = r#"
1447 fn outer() {}
1448
1449 mod module {
1450 fn inner() {}
1451 }"#
1452 .unindent();
1453
1454 let theme = SyntaxTheme::new(vec![
1455 ("mod.body".to_string(), Color::red().into()),
1456 ("fn.name".to_string(), Color::blue().into()),
1457 ]);
1458 let language = Arc::new(
1459 Language::new(
1460 LanguageConfig {
1461 name: "Test".into(),
1462 path_suffixes: vec![".test".to_string()],
1463 ..Default::default()
1464 },
1465 Some(tree_sitter_rust::language()),
1466 )
1467 .with_highlights_query(
1468 r#"
1469 (mod_item name: (identifier) body: _ @mod.body)
1470 (function_item name: (identifier) @fn.name)
1471 "#,
1472 )
1473 .unwrap(),
1474 );
1475 language.set_theme(&theme);
1476
1477 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1478
1479 let buffer = cx
1480 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1481 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1482 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1483
1484 let font_cache = cx.font_cache();
1485 let family_id = font_cache
1486 .load_family(&["Helvetica"], &Default::default())
1487 .unwrap();
1488 let font_id = font_cache
1489 .select_font(family_id, &Default::default())
1490 .unwrap();
1491 let font_size = 14.0;
1492
1493 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1494 assert_eq!(
1495 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1496 vec![
1497 ("fn ".to_string(), None),
1498 ("outer".to_string(), Some(Color::blue())),
1499 ("() {}\n\nmod module ".to_string(), None),
1500 ("{\n fn ".to_string(), Some(Color::red())),
1501 ("inner".to_string(), Some(Color::blue())),
1502 ("() {}\n}".to_string(), Some(Color::red())),
1503 ]
1504 );
1505 assert_eq!(
1506 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1507 vec![
1508 (" fn ".to_string(), Some(Color::red())),
1509 ("inner".to_string(), Some(Color::blue())),
1510 ("() {}\n}".to_string(), Some(Color::red())),
1511 ]
1512 );
1513
1514 map.update(cx, |map, cx| {
1515 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1516 });
1517 assert_eq!(
1518 cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1519 vec![
1520 ("fn ".to_string(), None),
1521 ("out".to_string(), Some(Color::blue())),
1522 ("āÆ".to_string(), None),
1523 (" fn ".to_string(), Some(Color::red())),
1524 ("inner".to_string(), Some(Color::blue())),
1525 ("() {}\n}".to_string(), Some(Color::red())),
1526 ]
1527 );
1528 }
1529
1530 #[gpui::test]
1531 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1532 use unindent::Unindent as _;
1533
1534 cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1535
1536 let text = r#"
1537 fn outer() {}
1538
1539 mod module {
1540 fn inner() {}
1541 }"#
1542 .unindent();
1543
1544 let theme = SyntaxTheme::new(vec![
1545 ("mod.body".to_string(), Color::red().into()),
1546 ("fn.name".to_string(), Color::blue().into()),
1547 ]);
1548 let language = Arc::new(
1549 Language::new(
1550 LanguageConfig {
1551 name: "Test".into(),
1552 path_suffixes: vec![".test".to_string()],
1553 ..Default::default()
1554 },
1555 Some(tree_sitter_rust::language()),
1556 )
1557 .with_highlights_query(
1558 r#"
1559 (mod_item name: (identifier) body: _ @mod.body)
1560 (function_item name: (identifier) @fn.name)
1561 "#,
1562 )
1563 .unwrap(),
1564 );
1565 language.set_theme(&theme);
1566
1567 cx.update(|cx| init_test(cx, |_| {}));
1568
1569 let buffer = cx
1570 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1571 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1572 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1573
1574 let font_cache = cx.font_cache();
1575
1576 let family_id = font_cache
1577 .load_family(&["Courier"], &Default::default())
1578 .unwrap();
1579 let font_id = font_cache
1580 .select_font(family_id, &Default::default())
1581 .unwrap();
1582 let font_size = 16.0;
1583
1584 let map =
1585 cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1586 assert_eq!(
1587 cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1588 [
1589 ("fn \n".to_string(), None),
1590 ("oute\nr".to_string(), Some(Color::blue())),
1591 ("() \n{}\n\n".to_string(), None),
1592 ]
1593 );
1594 assert_eq!(
1595 cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1596 [("{}\n\n".to_string(), None)]
1597 );
1598
1599 map.update(cx, |map, cx| {
1600 map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1601 });
1602 assert_eq!(
1603 cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1604 [
1605 ("out".to_string(), Some(Color::blue())),
1606 ("āÆ\n".to_string(), None),
1607 (" \nfn ".to_string(), Some(Color::red())),
1608 ("i\n".to_string(), Some(Color::blue()))
1609 ]
1610 );
1611 }
1612
1613 #[gpui::test]
1614 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1615 cx.update(|cx| init_test(cx, |_| {}));
1616
1617 let theme = SyntaxTheme::new(vec![
1618 ("operator".to_string(), Color::red().into()),
1619 ("string".to_string(), Color::green().into()),
1620 ]);
1621 let language = Arc::new(
1622 Language::new(
1623 LanguageConfig {
1624 name: "Test".into(),
1625 path_suffixes: vec![".test".to_string()],
1626 ..Default::default()
1627 },
1628 Some(tree_sitter_rust::language()),
1629 )
1630 .with_highlights_query(
1631 r#"
1632 ":" @operator
1633 (string_literal) @string
1634 "#,
1635 )
1636 .unwrap(),
1637 );
1638 language.set_theme(&theme);
1639
1640 let (text, highlighted_ranges) = marked_text_ranges(r#"constĖ Ā«aĀ»: B = "c Ā«dĀ»""#, false);
1641
1642 let buffer = cx
1643 .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1644 buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1645
1646 let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1647 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1648
1649 let font_cache = cx.font_cache();
1650 let family_id = font_cache
1651 .load_family(&["Courier"], &Default::default())
1652 .unwrap();
1653 let font_id = font_cache
1654 .select_font(family_id, &Default::default())
1655 .unwrap();
1656 let font_size = 16.0;
1657 let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1658
1659 enum MyType {}
1660
1661 let style = HighlightStyle {
1662 color: Some(Color::blue()),
1663 ..Default::default()
1664 };
1665
1666 map.update(cx, |map, _cx| {
1667 map.highlight_text(
1668 TypeId::of::<MyType>(),
1669 highlighted_ranges
1670 .into_iter()
1671 .map(|range| {
1672 buffer_snapshot.anchor_before(range.start)
1673 ..buffer_snapshot.anchor_before(range.end)
1674 })
1675 .collect(),
1676 style,
1677 );
1678 });
1679
1680 assert_eq!(
1681 cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1682 [
1683 ("const ".to_string(), None, None),
1684 ("a".to_string(), None, Some(Color::blue())),
1685 (":".to_string(), Some(Color::red()), None),
1686 (" B = ".to_string(), None, None),
1687 ("\"c ".to_string(), Some(Color::green()), None),
1688 ("d".to_string(), Some(Color::green()), Some(Color::blue())),
1689 ("\"".to_string(), Some(Color::green()), None),
1690 ]
1691 );
1692 }
1693
1694 #[gpui::test]
1695 fn test_clip_point(cx: &mut gpui::AppContext) {
1696 init_test(cx, |_| {});
1697
1698 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1699 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1700
1701 match bias {
1702 Bias::Left => {
1703 if shift_right {
1704 *markers[1].column_mut() += 1;
1705 }
1706
1707 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1708 }
1709 Bias::Right => {
1710 if shift_right {
1711 *markers[0].column_mut() += 1;
1712 }
1713
1714 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1715 }
1716 };
1717 }
1718
1719 use Bias::{Left, Right};
1720 assert("ĖĖα", false, Left, cx);
1721 assert("ĖĖα", true, Left, cx);
1722 assert("ĖĖα", false, Right, cx);
1723 assert("ĖαĖ", true, Right, cx);
1724 assert("ĖĖā", false, Left, cx);
1725 assert("ĖĖā", true, Left, cx);
1726 assert("ĖĖā", false, Right, cx);
1727 assert("ĖāĖ", true, Right, cx);
1728 assert("ĖĖš", false, Left, cx);
1729 assert("ĖĖš", true, Left, cx);
1730 assert("ĖĖš", false, Right, cx);
1731 assert("ĖšĖ", true, Right, cx);
1732 assert("ĖĖ\t", false, Left, cx);
1733 assert("ĖĖ\t", true, Left, cx);
1734 assert("ĖĖ\t", false, Right, cx);
1735 assert("Ė\tĖ", true, Right, cx);
1736 assert(" ĖĖ\t", false, Left, cx);
1737 assert(" ĖĖ\t", true, Left, cx);
1738 assert(" ĖĖ\t", false, Right, cx);
1739 assert(" Ė\tĖ", true, Right, cx);
1740 assert(" ĖĖ\t", false, Left, cx);
1741 assert(" ĖĖ\t", false, Right, cx);
1742 }
1743
1744 #[gpui::test]
1745 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1746 init_test(cx, |_| {});
1747
1748 fn assert(text: &str, cx: &mut gpui::AppContext) {
1749 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1750 unmarked_snapshot.clip_at_line_ends = true;
1751 assert_eq!(
1752 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1753 markers[0]
1754 );
1755 }
1756
1757 assert("ĖĖ", cx);
1758 assert("ĖaĖ", cx);
1759 assert("aĖbĖ", cx);
1760 assert("aĖαĖ", cx);
1761 }
1762
1763 #[gpui::test]
1764 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1765 init_test(cx, |_| {});
1766
1767 let text = "ā
\t\tα\nβ\t\nšĪ²\t\tγ";
1768 let buffer = MultiBuffer::build_simple(text, cx);
1769 let font_cache = cx.font_cache();
1770 let family_id = font_cache
1771 .load_family(&["Helvetica"], &Default::default())
1772 .unwrap();
1773 let font_id = font_cache
1774 .select_font(family_id, &Default::default())
1775 .unwrap();
1776 let font_size = 14.0;
1777
1778 let map =
1779 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1780 let map = map.update(cx, |map, cx| map.snapshot(cx));
1781 assert_eq!(map.text(), "ā
α\nβ \nšĪ² γ");
1782 assert_eq!(
1783 map.text_chunks(0).collect::<String>(),
1784 "ā
α\nβ \nšĪ² γ"
1785 );
1786 assert_eq!(map.text_chunks(1).collect::<String>(), "β \nšĪ² γ");
1787 assert_eq!(map.text_chunks(2).collect::<String>(), "šĪ² γ");
1788
1789 let point = Point::new(0, "ā
\t\t".len() as u32);
1790 let display_point = DisplayPoint::new(0, "ā
".len() as u32);
1791 assert_eq!(point.to_display_point(&map), display_point);
1792 assert_eq!(display_point.to_point(&map), point);
1793
1794 let point = Point::new(1, "β\t".len() as u32);
1795 let display_point = DisplayPoint::new(1, "β ".len() as u32);
1796 assert_eq!(point.to_display_point(&map), display_point);
1797 assert_eq!(display_point.to_point(&map), point,);
1798
1799 let point = Point::new(2, "šĪ²\t\t".len() as u32);
1800 let display_point = DisplayPoint::new(2, "šĪ² ".len() as u32);
1801 assert_eq!(point.to_display_point(&map), display_point);
1802 assert_eq!(display_point.to_point(&map), point,);
1803
1804 // Display points inside of expanded tabs
1805 assert_eq!(
1806 DisplayPoint::new(0, "ā
".len() as u32).to_point(&map),
1807 Point::new(0, "ā
\t".len() as u32),
1808 );
1809 assert_eq!(
1810 DisplayPoint::new(0, "ā
".len() as u32).to_point(&map),
1811 Point::new(0, "ā
".len() as u32),
1812 );
1813
1814 // Clipping display points inside of multi-byte characters
1815 assert_eq!(
1816 map.clip_point(DisplayPoint::new(0, "ā
".len() as u32 - 1), Left),
1817 DisplayPoint::new(0, 0)
1818 );
1819 assert_eq!(
1820 map.clip_point(DisplayPoint::new(0, "ā
".len() as u32 - 1), Bias::Right),
1821 DisplayPoint::new(0, "ā
".len() as u32)
1822 );
1823 }
1824
1825 #[gpui::test]
1826 fn test_max_point(cx: &mut gpui::AppContext) {
1827 init_test(cx, |_| {});
1828
1829 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1830 let font_cache = cx.font_cache();
1831 let family_id = font_cache
1832 .load_family(&["Helvetica"], &Default::default())
1833 .unwrap();
1834 let font_id = font_cache
1835 .select_font(family_id, &Default::default())
1836 .unwrap();
1837 let font_size = 14.0;
1838 let map =
1839 cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1840 assert_eq!(
1841 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1842 DisplayPoint::new(1, 11)
1843 )
1844 }
1845
1846 fn syntax_chunks<'a>(
1847 rows: Range<u32>,
1848 map: &ModelHandle<DisplayMap>,
1849 theme: &'a SyntaxTheme,
1850 cx: &mut AppContext,
1851 ) -> Vec<(String, Option<Color>)> {
1852 chunks(rows, map, theme, cx)
1853 .into_iter()
1854 .map(|(text, color, _)| (text, color))
1855 .collect()
1856 }
1857
1858 fn chunks<'a>(
1859 rows: Range<u32>,
1860 map: &ModelHandle<DisplayMap>,
1861 theme: &'a SyntaxTheme,
1862 cx: &mut AppContext,
1863 ) -> Vec<(String, Option<Color>, Option<Color>)> {
1864 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1865 let mut chunks: Vec<(String, Option<Color>, Option<Color>)> = Vec::new();
1866 for chunk in snapshot.chunks(rows, true, None, None) {
1867 let syntax_color = chunk
1868 .syntax_highlight_id
1869 .and_then(|id| id.style(theme)?.color);
1870 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1871 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1872 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1873 last_chunk.push_str(chunk.text);
1874 continue;
1875 }
1876 }
1877 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1878 }
1879 chunks
1880 }
1881
1882 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1883 cx.foreground().forbid_parking();
1884 cx.set_global(SettingsStore::test(cx));
1885 language::init(cx);
1886 crate::init(cx);
1887 Project::init_settings(cx);
1888 theme::init((), cx);
1889 cx.update_global::<SettingsStore, _, _>(|store, cx| {
1890 store.update_user_settings::<AllLanguageSettings>(cx, f);
1891 });
1892 }
1893}