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 buffer.line_indent_for_row(range.start.row)
849 }
850
851 pub fn line_len(&self, row: DisplayRow) -> u32 {
852 self.block_snapshot.line_len(BlockRow(row.0))
853 }
854
855 pub fn longest_row(&self) -> DisplayRow {
856 DisplayRow(self.block_snapshot.longest_row())
857 }
858
859 pub fn starts_indent(&self, buffer_row: MultiBufferRow) -> bool {
860 let max_row = self.buffer_snapshot.max_buffer_row();
861 if buffer_row >= max_row {
862 return false;
863 }
864
865 let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
866 if is_blank {
867 return false;
868 }
869
870 for next_row in (buffer_row.0 + 1)..=max_row.0 {
871 let (next_indent_size, next_line_is_blank) =
872 self.line_indent_for_buffer_row(MultiBufferRow(next_row));
873 if next_indent_size > indent_size {
874 return true;
875 } else if !next_line_is_blank {
876 break;
877 }
878 }
879
880 false
881 }
882
883 pub fn foldable_range(
884 &self,
885 buffer_row: MultiBufferRow,
886 ) -> Option<(Range<Point>, &'static str)> {
887 let start = MultiBufferPoint::new(buffer_row.0, self.buffer_snapshot.line_len(buffer_row));
888 if let Some(flap) = self
889 .flap_snapshot
890 .query_row(buffer_row, &self.buffer_snapshot)
891 {
892 Some((flap.range.to_point(&self.buffer_snapshot), ""))
893 } else if self.starts_indent(MultiBufferRow(start.row))
894 && !self.is_line_folded(MultiBufferRow(start.row))
895 {
896 let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
897 let max_point = self.buffer_snapshot.max_point();
898 let mut end = None;
899
900 for row in (buffer_row.0 + 1)..=max_point.row {
901 let (indent, is_blank) = self.line_indent_for_buffer_row(MultiBufferRow(row));
902 if !is_blank && indent <= start_indent {
903 let prev_row = row - 1;
904 end = Some(Point::new(
905 prev_row,
906 self.buffer_snapshot.line_len(MultiBufferRow(prev_row)),
907 ));
908 break;
909 }
910 }
911 let end = end.unwrap_or(max_point);
912 Some((start..end, "⋯"))
913 } else {
914 None
915 }
916 }
917
918 #[cfg(any(test, feature = "test-support"))]
919 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
920 &self,
921 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
922 let type_id = TypeId::of::<Tag>();
923 self.text_highlights.get(&Some(type_id)).cloned()
924 }
925
926 #[allow(unused)]
927 #[cfg(any(test, feature = "test-support"))]
928 pub(crate) fn inlay_highlights<Tag: ?Sized + 'static>(
929 &self,
930 ) -> Option<&TreeMap<InlayId, (HighlightStyle, InlayHighlight)>> {
931 let type_id = TypeId::of::<Tag>();
932 self.inlay_highlights.get(&type_id)
933 }
934}
935
936#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
937pub struct DisplayPoint(BlockPoint);
938
939impl Debug for DisplayPoint {
940 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
941 f.write_fmt(format_args!(
942 "DisplayPoint({}, {})",
943 self.row().0,
944 self.column()
945 ))
946 }
947}
948
949#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
950#[serde(transparent)]
951pub struct DisplayRow(pub u32);
952
953impl DisplayPoint {
954 pub fn new(row: DisplayRow, column: u32) -> Self {
955 Self(BlockPoint(Point::new(row.0, column)))
956 }
957
958 pub fn zero() -> Self {
959 Self::new(DisplayRow(0), 0)
960 }
961
962 pub fn is_zero(&self) -> bool {
963 self.0.is_zero()
964 }
965
966 pub fn row(self) -> DisplayRow {
967 DisplayRow(self.0.row)
968 }
969
970 pub fn column(self) -> u32 {
971 self.0.column
972 }
973
974 pub fn row_mut(&mut self) -> &mut u32 {
975 &mut self.0.row
976 }
977
978 pub fn column_mut(&mut self) -> &mut u32 {
979 &mut self.0.column
980 }
981
982 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
983 map.display_point_to_point(self, Bias::Left)
984 }
985
986 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
987 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
988 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
989 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
990 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
991 map.inlay_snapshot
992 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
993 }
994}
995
996impl ToDisplayPoint for usize {
997 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
998 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
999 }
1000}
1001
1002impl ToDisplayPoint for OffsetUtf16 {
1003 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1004 self.to_offset(&map.buffer_snapshot).to_display_point(map)
1005 }
1006}
1007
1008impl ToDisplayPoint for Point {
1009 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1010 map.point_to_display_point(*self, Bias::Left)
1011 }
1012}
1013
1014impl ToDisplayPoint for Anchor {
1015 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1016 self.to_point(&map.buffer_snapshot).to_display_point(map)
1017 }
1018}
1019
1020#[cfg(test)]
1021pub mod tests {
1022 use super::*;
1023 use crate::{
1024 movement,
1025 test::{editor_test_context::EditorTestContext, marked_display_snapshot},
1026 };
1027 use gpui::{div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla};
1028 use language::{
1029 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1030 Buffer, Language, LanguageConfig, LanguageMatcher, SelectionGoal,
1031 };
1032 use project::Project;
1033 use rand::{prelude::*, Rng};
1034 use settings::SettingsStore;
1035 use smol::stream::StreamExt;
1036 use std::{env, sync::Arc};
1037 use theme::{LoadThemes, SyntaxTheme};
1038 use util::test::{marked_text_ranges, sample_text};
1039 use Bias::*;
1040
1041 #[gpui::test(iterations = 100)]
1042 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1043 cx.background_executor.set_block_on_ticks(0..=50);
1044 let operations = env::var("OPERATIONS")
1045 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1046 .unwrap_or(10);
1047
1048 let mut tab_size = rng.gen_range(1..=4);
1049 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1050 let excerpt_header_height = rng.gen_range(1..=5);
1051 let font_size = px(14.0);
1052 let max_wrap_width = 300.0;
1053 let mut wrap_width = if rng.gen_bool(0.1) {
1054 None
1055 } else {
1056 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1057 };
1058
1059 log::info!("tab size: {}", tab_size);
1060 log::info!("wrap width: {:?}", wrap_width);
1061
1062 cx.update(|cx| {
1063 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1064 });
1065
1066 let buffer = cx.update(|cx| {
1067 if rng.gen() {
1068 let len = rng.gen_range(0..10);
1069 let text = util::RandomCharIter::new(&mut rng)
1070 .take(len)
1071 .collect::<String>();
1072 MultiBuffer::build_simple(&text, cx)
1073 } else {
1074 MultiBuffer::build_random(&mut rng, cx)
1075 }
1076 });
1077
1078 let map = cx.new_model(|cx| {
1079 DisplayMap::new(
1080 buffer.clone(),
1081 font("Helvetica"),
1082 font_size,
1083 wrap_width,
1084 buffer_start_excerpt_header_height,
1085 excerpt_header_height,
1086 cx,
1087 )
1088 });
1089 let mut notifications = observe(&map, cx);
1090 let mut fold_count = 0;
1091 let mut blocks = Vec::new();
1092
1093 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1094 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1095 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1096 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1097 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1098 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1099 log::info!("display text: {:?}", snapshot.text());
1100
1101 for _i in 0..operations {
1102 match rng.gen_range(0..100) {
1103 0..=19 => {
1104 wrap_width = if rng.gen_bool(0.2) {
1105 None
1106 } else {
1107 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1108 };
1109 log::info!("setting wrap width to {:?}", wrap_width);
1110 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1111 }
1112 20..=29 => {
1113 let mut tab_sizes = vec![1, 2, 3, 4];
1114 tab_sizes.remove((tab_size - 1) as usize);
1115 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1116 log::info!("setting tab size to {:?}", tab_size);
1117 cx.update(|cx| {
1118 cx.update_global::<SettingsStore, _>(|store, cx| {
1119 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1120 s.defaults.tab_size = NonZeroU32::new(tab_size);
1121 });
1122 });
1123 });
1124 }
1125 30..=44 => {
1126 map.update(cx, |map, cx| {
1127 if rng.gen() || blocks.is_empty() {
1128 let buffer = map.snapshot(cx).buffer_snapshot;
1129 let block_properties = (0..rng.gen_range(1..=1))
1130 .map(|_| {
1131 let position =
1132 buffer.anchor_after(buffer.clip_offset(
1133 rng.gen_range(0..=buffer.len()),
1134 Bias::Left,
1135 ));
1136
1137 let disposition = if rng.gen() {
1138 BlockDisposition::Above
1139 } else {
1140 BlockDisposition::Below
1141 };
1142 let height = rng.gen_range(1..5);
1143 log::info!(
1144 "inserting block {:?} {:?} with height {}",
1145 disposition,
1146 position.to_point(&buffer),
1147 height
1148 );
1149 BlockProperties {
1150 style: BlockStyle::Fixed,
1151 position,
1152 height,
1153 disposition,
1154 render: Box::new(|_| div().into_any()),
1155 }
1156 })
1157 .collect::<Vec<_>>();
1158 blocks.extend(map.insert_blocks(block_properties, cx));
1159 } else {
1160 blocks.shuffle(&mut rng);
1161 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1162 let block_ids_to_remove = (0..remove_count)
1163 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1164 .collect();
1165 log::info!("removing block ids {:?}", block_ids_to_remove);
1166 map.remove_blocks(block_ids_to_remove, cx);
1167 }
1168 });
1169 }
1170 45..=79 => {
1171 let mut ranges = Vec::new();
1172 for _ in 0..rng.gen_range(1..=3) {
1173 buffer.read_with(cx, |buffer, cx| {
1174 let buffer = buffer.read(cx);
1175 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1176 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1177 ranges.push(start..end);
1178 });
1179 }
1180
1181 if rng.gen() && fold_count > 0 {
1182 log::info!("unfolding ranges: {:?}", ranges);
1183 map.update(cx, |map, cx| {
1184 map.unfold(ranges, true, cx);
1185 });
1186 } else {
1187 log::info!("folding ranges: {:?}", ranges);
1188 map.update(cx, |map, cx| {
1189 map.fold(ranges.into_iter().map(|range| (range, "⋯")), cx);
1190 });
1191 }
1192 }
1193 _ => {
1194 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1195 }
1196 }
1197
1198 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1199 notifications.next().await.unwrap();
1200 }
1201
1202 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1203 fold_count = snapshot.fold_count();
1204 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1205 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1206 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1207 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1208 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1209 log::info!("display text: {:?}", snapshot.text());
1210
1211 // Line boundaries
1212 let buffer = &snapshot.buffer_snapshot;
1213 for _ in 0..5 {
1214 let row = rng.gen_range(0..=buffer.max_point().row);
1215 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1216 let point = buffer.clip_point(Point::new(row, column), Left);
1217
1218 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1219 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1220
1221 assert!(prev_buffer_bound <= point);
1222 assert!(next_buffer_bound >= point);
1223 assert_eq!(prev_buffer_bound.column, 0);
1224 assert_eq!(prev_display_bound.column(), 0);
1225 if next_buffer_bound < buffer.max_point() {
1226 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1227 }
1228
1229 assert_eq!(
1230 prev_display_bound,
1231 prev_buffer_bound.to_display_point(&snapshot),
1232 "row boundary before {:?}. reported buffer row boundary: {:?}",
1233 point,
1234 prev_buffer_bound
1235 );
1236 assert_eq!(
1237 next_display_bound,
1238 next_buffer_bound.to_display_point(&snapshot),
1239 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1240 point,
1241 next_buffer_bound
1242 );
1243 assert_eq!(
1244 prev_buffer_bound,
1245 prev_display_bound.to_point(&snapshot),
1246 "row boundary before {:?}. reported display row boundary: {:?}",
1247 point,
1248 prev_display_bound
1249 );
1250 assert_eq!(
1251 next_buffer_bound,
1252 next_display_bound.to_point(&snapshot),
1253 "row boundary after {:?}. reported display row boundary: {:?}",
1254 point,
1255 next_display_bound
1256 );
1257 }
1258
1259 // Movement
1260 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1261 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1262 for _ in 0..5 {
1263 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1264 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1265 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1266
1267 log::info!("Moving from point {:?}", point);
1268
1269 let moved_right = movement::right(&snapshot, point);
1270 log::info!("Right {:?}", moved_right);
1271 if point < max_point {
1272 assert!(moved_right > point);
1273 if point.column() == snapshot.line_len(point.row())
1274 || snapshot.soft_wrap_indent(point.row()).is_some()
1275 && point.column() == snapshot.line_len(point.row()) - 1
1276 {
1277 assert!(moved_right.row() > point.row());
1278 }
1279 } else {
1280 assert_eq!(moved_right, point);
1281 }
1282
1283 let moved_left = movement::left(&snapshot, point);
1284 log::info!("Left {:?}", moved_left);
1285 if point > min_point {
1286 assert!(moved_left < point);
1287 if point.column() == 0 {
1288 assert!(moved_left.row() < point.row());
1289 }
1290 } else {
1291 assert_eq!(moved_left, point);
1292 }
1293 }
1294 }
1295 }
1296
1297 #[gpui::test(retries = 5)]
1298 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1299 cx.background_executor
1300 .set_block_on_ticks(usize::MAX..=usize::MAX);
1301 cx.update(|cx| {
1302 init_test(cx, |_| {});
1303 });
1304
1305 let mut cx = EditorTestContext::new(cx).await;
1306 let editor = cx.editor.clone();
1307 let window = cx.window;
1308
1309 _ = cx.update_window(window, |_, cx| {
1310 let text_layout_details =
1311 editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1312
1313 let font_size = px(12.0);
1314 let wrap_width = Some(px(64.));
1315
1316 let text = "one two three four five\nsix seven eight";
1317 let buffer = MultiBuffer::build_simple(text, cx);
1318 let map = cx.new_model(|cx| {
1319 DisplayMap::new(
1320 buffer.clone(),
1321 font("Helvetica"),
1322 font_size,
1323 wrap_width,
1324 1,
1325 1,
1326 cx,
1327 )
1328 });
1329
1330 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1331 assert_eq!(
1332 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1333 "one two \nthree four \nfive\nsix seven \neight"
1334 );
1335 assert_eq!(
1336 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1337 DisplayPoint::new(DisplayRow(0), 7)
1338 );
1339 assert_eq!(
1340 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1341 DisplayPoint::new(DisplayRow(1), 0)
1342 );
1343 assert_eq!(
1344 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1345 DisplayPoint::new(DisplayRow(1), 0)
1346 );
1347 assert_eq!(
1348 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1349 DisplayPoint::new(DisplayRow(0), 7)
1350 );
1351
1352 let x = snapshot
1353 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1354 assert_eq!(
1355 movement::up(
1356 &snapshot,
1357 DisplayPoint::new(DisplayRow(1), 10),
1358 SelectionGoal::None,
1359 false,
1360 &text_layout_details,
1361 ),
1362 (
1363 DisplayPoint::new(DisplayRow(0), 7),
1364 SelectionGoal::HorizontalPosition(x.0)
1365 )
1366 );
1367 assert_eq!(
1368 movement::down(
1369 &snapshot,
1370 DisplayPoint::new(DisplayRow(0), 7),
1371 SelectionGoal::HorizontalPosition(x.0),
1372 false,
1373 &text_layout_details
1374 ),
1375 (
1376 DisplayPoint::new(DisplayRow(1), 10),
1377 SelectionGoal::HorizontalPosition(x.0)
1378 )
1379 );
1380 assert_eq!(
1381 movement::down(
1382 &snapshot,
1383 DisplayPoint::new(DisplayRow(1), 10),
1384 SelectionGoal::HorizontalPosition(x.0),
1385 false,
1386 &text_layout_details
1387 ),
1388 (
1389 DisplayPoint::new(DisplayRow(2), 4),
1390 SelectionGoal::HorizontalPosition(x.0)
1391 )
1392 );
1393
1394 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1395 buffer.update(cx, |buffer, cx| {
1396 buffer.edit([(ix..ix, "and ")], None, cx);
1397 });
1398
1399 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1400 assert_eq!(
1401 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1402 "three four \nfive\nsix and \nseven eight"
1403 );
1404
1405 // Re-wrap on font size changes
1406 map.update(cx, |map, cx| {
1407 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1408 });
1409
1410 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1411 assert_eq!(
1412 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1413 "three \nfour five\nsix and \nseven \neight"
1414 )
1415 });
1416 }
1417
1418 #[gpui::test]
1419 fn test_text_chunks(cx: &mut gpui::AppContext) {
1420 init_test(cx, |_| {});
1421
1422 let text = sample_text(6, 6, 'a');
1423 let buffer = MultiBuffer::build_simple(&text, cx);
1424
1425 let font_size = px(14.0);
1426 let map = cx.new_model(|cx| {
1427 DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1428 });
1429
1430 buffer.update(cx, |buffer, cx| {
1431 buffer.edit(
1432 vec![
1433 (
1434 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1435 "\t",
1436 ),
1437 (
1438 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1439 "\t",
1440 ),
1441 (
1442 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1443 "\t",
1444 ),
1445 ],
1446 None,
1447 cx,
1448 )
1449 });
1450
1451 assert_eq!(
1452 map.update(cx, |map, cx| map.snapshot(cx))
1453 .text_chunks(DisplayRow(1))
1454 .collect::<String>()
1455 .lines()
1456 .next(),
1457 Some(" b bbbbb")
1458 );
1459 assert_eq!(
1460 map.update(cx, |map, cx| map.snapshot(cx))
1461 .text_chunks(DisplayRow(2))
1462 .collect::<String>()
1463 .lines()
1464 .next(),
1465 Some("c ccccc")
1466 );
1467 }
1468
1469 #[gpui::test]
1470 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1471 use unindent::Unindent as _;
1472
1473 let text = r#"
1474 fn outer() {}
1475
1476 mod module {
1477 fn inner() {}
1478 }"#
1479 .unindent();
1480
1481 let theme =
1482 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1483 let language = Arc::new(
1484 Language::new(
1485 LanguageConfig {
1486 name: "Test".into(),
1487 matcher: LanguageMatcher {
1488 path_suffixes: vec![".test".to_string()],
1489 ..Default::default()
1490 },
1491 ..Default::default()
1492 },
1493 Some(tree_sitter_rust::language()),
1494 )
1495 .with_highlights_query(
1496 r#"
1497 (mod_item name: (identifier) body: _ @mod.body)
1498 (function_item name: (identifier) @fn.name)
1499 "#,
1500 )
1501 .unwrap(),
1502 );
1503 language.set_theme(&theme);
1504
1505 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1506
1507 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1508 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1509 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1510
1511 let font_size = px(14.0);
1512
1513 let map = cx
1514 .new_model(|cx| DisplayMap::new(buffer, font("Helvetica"), font_size, None, 1, 1, cx));
1515 assert_eq!(
1516 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1517 vec![
1518 ("fn ".to_string(), None),
1519 ("outer".to_string(), Some(Hsla::blue())),
1520 ("() {}\n\nmod module ".to_string(), None),
1521 ("{\n fn ".to_string(), Some(Hsla::red())),
1522 ("inner".to_string(), Some(Hsla::blue())),
1523 ("() {}\n}".to_string(), Some(Hsla::red())),
1524 ]
1525 );
1526 assert_eq!(
1527 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1528 vec![
1529 (" fn ".to_string(), Some(Hsla::red())),
1530 ("inner".to_string(), Some(Hsla::blue())),
1531 ("() {}\n}".to_string(), Some(Hsla::red())),
1532 ]
1533 );
1534
1535 map.update(cx, |map, cx| {
1536 map.fold(
1537 vec![(
1538 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1539 "⋯",
1540 )],
1541 cx,
1542 )
1543 });
1544 assert_eq!(
1545 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1546 vec![
1547 ("fn ".to_string(), None),
1548 ("out".to_string(), Some(Hsla::blue())),
1549 ("⋯".to_string(), None),
1550 (" fn ".to_string(), Some(Hsla::red())),
1551 ("inner".to_string(), Some(Hsla::blue())),
1552 ("() {}\n}".to_string(), Some(Hsla::red())),
1553 ]
1554 );
1555 }
1556
1557 #[gpui::test]
1558 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1559 use unindent::Unindent as _;
1560
1561 cx.background_executor
1562 .set_block_on_ticks(usize::MAX..=usize::MAX);
1563
1564 let text = r#"
1565 fn outer() {}
1566
1567 mod module {
1568 fn inner() {}
1569 }"#
1570 .unindent();
1571
1572 let theme =
1573 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1574 let language = Arc::new(
1575 Language::new(
1576 LanguageConfig {
1577 name: "Test".into(),
1578 matcher: LanguageMatcher {
1579 path_suffixes: vec![".test".to_string()],
1580 ..Default::default()
1581 },
1582 ..Default::default()
1583 },
1584 Some(tree_sitter_rust::language()),
1585 )
1586 .with_highlights_query(
1587 r#"
1588 (mod_item name: (identifier) body: _ @mod.body)
1589 (function_item name: (identifier) @fn.name)
1590 "#,
1591 )
1592 .unwrap(),
1593 );
1594 language.set_theme(&theme);
1595
1596 cx.update(|cx| init_test(cx, |_| {}));
1597
1598 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1599 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1600 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1601
1602 let font_size = px(16.0);
1603
1604 let map = cx.new_model(|cx| {
1605 DisplayMap::new(buffer, font("Courier"), font_size, Some(px(40.0)), 1, 1, cx)
1606 });
1607 assert_eq!(
1608 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1609 [
1610 ("fn \n".to_string(), None),
1611 ("oute\nr".to_string(), Some(Hsla::blue())),
1612 ("() \n{}\n\n".to_string(), None),
1613 ]
1614 );
1615 assert_eq!(
1616 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1617 [("{}\n\n".to_string(), None)]
1618 );
1619
1620 map.update(cx, |map, cx| {
1621 map.fold(
1622 vec![(
1623 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1624 "⋯",
1625 )],
1626 cx,
1627 )
1628 });
1629 assert_eq!(
1630 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
1631 [
1632 ("out".to_string(), Some(Hsla::blue())),
1633 ("⋯\n".to_string(), None),
1634 (" \nfn ".to_string(), Some(Hsla::red())),
1635 ("i\n".to_string(), Some(Hsla::blue()))
1636 ]
1637 );
1638 }
1639
1640 #[gpui::test]
1641 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1642 cx.update(|cx| init_test(cx, |_| {}));
1643
1644 let theme =
1645 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
1646 let language = Arc::new(
1647 Language::new(
1648 LanguageConfig {
1649 name: "Test".into(),
1650 matcher: LanguageMatcher {
1651 path_suffixes: vec![".test".to_string()],
1652 ..Default::default()
1653 },
1654 ..Default::default()
1655 },
1656 Some(tree_sitter_rust::language()),
1657 )
1658 .with_highlights_query(
1659 r#"
1660 ":" @operator
1661 (string_literal) @string
1662 "#,
1663 )
1664 .unwrap(),
1665 );
1666 language.set_theme(&theme);
1667
1668 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1669
1670 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1671 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1672
1673 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1674 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1675
1676 let font_size = px(16.0);
1677 let map =
1678 cx.new_model(|cx| DisplayMap::new(buffer, font("Courier"), font_size, None, 1, 1, cx));
1679
1680 enum MyType {}
1681
1682 let style = HighlightStyle {
1683 color: Some(Hsla::blue()),
1684 ..Default::default()
1685 };
1686
1687 map.update(cx, |map, _cx| {
1688 map.highlight_text(
1689 TypeId::of::<MyType>(),
1690 highlighted_ranges
1691 .into_iter()
1692 .map(|range| {
1693 buffer_snapshot.anchor_before(range.start)
1694 ..buffer_snapshot.anchor_before(range.end)
1695 })
1696 .collect(),
1697 style,
1698 );
1699 });
1700
1701 assert_eq!(
1702 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
1703 [
1704 ("const ".to_string(), None, None),
1705 ("a".to_string(), None, Some(Hsla::blue())),
1706 (":".to_string(), Some(Hsla::red()), None),
1707 (" B = ".to_string(), None, None),
1708 ("\"c ".to_string(), Some(Hsla::green()), None),
1709 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1710 ("\"".to_string(), Some(Hsla::green()), None),
1711 ]
1712 );
1713 }
1714
1715 #[gpui::test]
1716 fn test_clip_point(cx: &mut gpui::AppContext) {
1717 init_test(cx, |_| {});
1718
1719 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1720 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1721
1722 match bias {
1723 Bias::Left => {
1724 if shift_right {
1725 *markers[1].column_mut() += 1;
1726 }
1727
1728 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1729 }
1730 Bias::Right => {
1731 if shift_right {
1732 *markers[0].column_mut() += 1;
1733 }
1734
1735 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1736 }
1737 };
1738 }
1739
1740 use Bias::{Left, Right};
1741 assert("ˇˇα", false, Left, cx);
1742 assert("ˇˇα", true, Left, cx);
1743 assert("ˇˇα", false, Right, cx);
1744 assert("ˇαˇ", true, Right, cx);
1745 assert("ˇˇ✋", false, Left, cx);
1746 assert("ˇˇ✋", true, Left, cx);
1747 assert("ˇˇ✋", false, Right, cx);
1748 assert("ˇ✋ˇ", true, Right, cx);
1749 assert("ˇˇ🍐", false, Left, cx);
1750 assert("ˇˇ🍐", true, Left, cx);
1751 assert("ˇˇ🍐", false, Right, cx);
1752 assert("ˇ🍐ˇ", true, Right, cx);
1753 assert("ˇˇ\t", false, Left, cx);
1754 assert("ˇˇ\t", true, Left, cx);
1755 assert("ˇˇ\t", false, Right, cx);
1756 assert("ˇ\tˇ", true, Right, cx);
1757 assert(" ˇˇ\t", false, Left, cx);
1758 assert(" ˇˇ\t", true, Left, cx);
1759 assert(" ˇˇ\t", false, Right, cx);
1760 assert(" ˇ\tˇ", true, Right, cx);
1761 assert(" ˇˇ\t", false, Left, cx);
1762 assert(" ˇˇ\t", false, Right, cx);
1763 }
1764
1765 #[gpui::test]
1766 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1767 init_test(cx, |_| {});
1768
1769 fn assert(text: &str, cx: &mut gpui::AppContext) {
1770 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1771 unmarked_snapshot.clip_at_line_ends = true;
1772 assert_eq!(
1773 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1774 markers[0]
1775 );
1776 }
1777
1778 assert("ˇˇ", cx);
1779 assert("ˇaˇ", cx);
1780 assert("aˇbˇ", cx);
1781 assert("aˇαˇ", cx);
1782 }
1783
1784 #[gpui::test]
1785 fn test_flaps(cx: &mut gpui::AppContext) {
1786 init_test(cx, |_| {});
1787
1788 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
1789 let buffer = MultiBuffer::build_simple(text, cx);
1790 let font_size = px(14.0);
1791 cx.new_model(|cx| {
1792 let mut map =
1793 DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx);
1794 let snapshot = map.buffer.read(cx).snapshot(cx);
1795 let range =
1796 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
1797
1798 map.flap_map.insert(
1799 [Flap::new(
1800 range,
1801 |_row, _status, _toggle, _cx| div(),
1802 |_row, _status, _cx| div(),
1803 )],
1804 &map.buffer.read(cx).snapshot(cx),
1805 );
1806
1807 map
1808 });
1809 }
1810
1811 #[gpui::test]
1812 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1813 init_test(cx, |_| {});
1814
1815 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1816 let buffer = MultiBuffer::build_simple(text, cx);
1817 let font_size = px(14.0);
1818
1819 let map = cx.new_model(|cx| {
1820 DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1821 });
1822 let map = map.update(cx, |map, cx| map.snapshot(cx));
1823 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1824 assert_eq!(
1825 map.text_chunks(DisplayRow(0)).collect::<String>(),
1826 "✅ α\nβ \n🏀β γ"
1827 );
1828 assert_eq!(
1829 map.text_chunks(DisplayRow(1)).collect::<String>(),
1830 "β \n🏀β γ"
1831 );
1832 assert_eq!(
1833 map.text_chunks(DisplayRow(2)).collect::<String>(),
1834 "🏀β γ"
1835 );
1836
1837 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
1838 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
1839 assert_eq!(point.to_display_point(&map), display_point);
1840 assert_eq!(display_point.to_point(&map), point);
1841
1842 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
1843 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
1844 assert_eq!(point.to_display_point(&map), display_point);
1845 assert_eq!(display_point.to_point(&map), point,);
1846
1847 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
1848 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
1849 assert_eq!(point.to_display_point(&map), display_point);
1850 assert_eq!(display_point.to_point(&map), point,);
1851
1852 // Display points inside of expanded tabs
1853 assert_eq!(
1854 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
1855 MultiBufferPoint::new(0, "✅\t".len() as u32),
1856 );
1857 assert_eq!(
1858 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
1859 MultiBufferPoint::new(0, "✅".len() as u32),
1860 );
1861
1862 // Clipping display points inside of multi-byte characters
1863 assert_eq!(
1864 map.clip_point(
1865 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
1866 Left
1867 ),
1868 DisplayPoint::new(DisplayRow(0), 0)
1869 );
1870 assert_eq!(
1871 map.clip_point(
1872 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
1873 Bias::Right
1874 ),
1875 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
1876 );
1877 }
1878
1879 #[gpui::test]
1880 fn test_max_point(cx: &mut gpui::AppContext) {
1881 init_test(cx, |_| {});
1882
1883 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1884 let font_size = px(14.0);
1885 let map = cx.new_model(|cx| {
1886 DisplayMap::new(buffer.clone(), font("Helvetica"), font_size, None, 1, 1, cx)
1887 });
1888 assert_eq!(
1889 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1890 DisplayPoint::new(DisplayRow(1), 11)
1891 )
1892 }
1893
1894 fn syntax_chunks(
1895 rows: Range<DisplayRow>,
1896 map: &Model<DisplayMap>,
1897 theme: &SyntaxTheme,
1898 cx: &mut AppContext,
1899 ) -> Vec<(String, Option<Hsla>)> {
1900 chunks(rows, map, theme, cx)
1901 .into_iter()
1902 .map(|(text, color, _)| (text, color))
1903 .collect()
1904 }
1905
1906 fn chunks(
1907 rows: Range<DisplayRow>,
1908 map: &Model<DisplayMap>,
1909 theme: &SyntaxTheme,
1910 cx: &mut AppContext,
1911 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
1912 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1913 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
1914 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
1915 let syntax_color = chunk
1916 .syntax_highlight_id
1917 .and_then(|id| id.style(theme)?.color);
1918 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1919 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1920 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1921 last_chunk.push_str(chunk.text);
1922 continue;
1923 }
1924 }
1925 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1926 }
1927 chunks
1928 }
1929
1930 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1931 let settings = SettingsStore::test(cx);
1932 cx.set_global(settings);
1933 language::init(cx);
1934 crate::init(cx);
1935 Project::init_settings(cx);
1936 theme::init(LoadThemes::JustBase, cx);
1937 cx.update_global::<SettingsStore, _>(|store, cx| {
1938 store.update_user_settings::<AllLanguageSettings>(cx, f);
1939 });
1940 }
1941}