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