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