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 crease_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 crease_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 crease_map: CreaseMap,
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 crease_map = CreaseMap::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 crease_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 crease_snapshot: self.crease_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_creases(
251 &mut self,
252 creases: impl IntoIterator<Item = Crease>,
253 cx: &mut ModelContext<Self>,
254 ) -> Vec<CreaseId> {
255 let snapshot = self.buffer.read(cx).snapshot(cx);
256 self.crease_map.insert(creases, &snapshot)
257 }
258
259 pub fn remove_creases(
260 &mut self,
261 crease_ids: impl IntoIterator<Item = CreaseId>,
262 cx: &mut ModelContext<Self>,
263 ) {
264 let snapshot = self.buffer.read(cx).snapshot(cx);
265 self.crease_map.remove(crease_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 crease_snapshot: CreaseSnapshot,
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(crease) = self
959 .crease_snapshot
960 .query_row(buffer_row, &self.buffer_snapshot)
961 {
962 Some((
963 crease.range.to_point(&self.buffer_snapshot),
964 crease.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
1024impl Add for DisplayPoint {
1025 type Output = Self;
1026
1027 fn add(self, other: Self) -> Self::Output {
1028 DisplayPoint(BlockPoint(self.0 .0 + other.0 .0))
1029 }
1030}
1031
1032impl Sub for DisplayPoint {
1033 type Output = Self;
1034
1035 fn sub(self, other: Self) -> Self::Output {
1036 DisplayPoint(BlockPoint(self.0 .0 - other.0 .0))
1037 }
1038}
1039
1040#[derive(Debug, Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq, Deserialize, Hash)]
1041#[serde(transparent)]
1042pub struct DisplayRow(pub u32);
1043
1044impl Add for DisplayRow {
1045 type Output = Self;
1046
1047 fn add(self, other: Self) -> Self::Output {
1048 DisplayRow(self.0 + other.0)
1049 }
1050}
1051
1052impl Sub for DisplayRow {
1053 type Output = Self;
1054
1055 fn sub(self, other: Self) -> Self::Output {
1056 DisplayRow(self.0 - other.0)
1057 }
1058}
1059
1060impl DisplayPoint {
1061 pub fn new(row: DisplayRow, column: u32) -> Self {
1062 Self(BlockPoint(Point::new(row.0, column)))
1063 }
1064
1065 pub fn zero() -> Self {
1066 Self::new(DisplayRow(0), 0)
1067 }
1068
1069 pub fn is_zero(&self) -> bool {
1070 self.0.is_zero()
1071 }
1072
1073 pub fn row(self) -> DisplayRow {
1074 DisplayRow(self.0.row)
1075 }
1076
1077 pub fn column(self) -> u32 {
1078 self.0.column
1079 }
1080
1081 pub fn row_mut(&mut self) -> &mut u32 {
1082 &mut self.0.row
1083 }
1084
1085 pub fn column_mut(&mut self) -> &mut u32 {
1086 &mut self.0.column
1087 }
1088
1089 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
1090 map.display_point_to_point(self, Bias::Left)
1091 }
1092
1093 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
1094 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
1095 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
1096 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
1097 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
1098 map.inlay_snapshot
1099 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
1100 }
1101}
1102
1103impl ToDisplayPoint for usize {
1104 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1105 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
1106 }
1107}
1108
1109impl ToDisplayPoint for OffsetUtf16 {
1110 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1111 self.to_offset(&map.buffer_snapshot).to_display_point(map)
1112 }
1113}
1114
1115impl ToDisplayPoint for Point {
1116 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1117 map.point_to_display_point(*self, Bias::Left)
1118 }
1119}
1120
1121impl ToDisplayPoint for Anchor {
1122 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
1123 self.to_point(&map.buffer_snapshot).to_display_point(map)
1124 }
1125}
1126
1127#[cfg(test)]
1128pub mod tests {
1129 use super::*;
1130 use crate::{movement, test::marked_display_snapshot};
1131 use gpui::{div, font, observe, px, AppContext, BorrowAppContext, Context, Element, Hsla};
1132 use language::{
1133 language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1134 Buffer, Language, LanguageConfig, LanguageMatcher,
1135 };
1136 use project::Project;
1137 use rand::{prelude::*, Rng};
1138 use settings::SettingsStore;
1139 use smol::stream::StreamExt;
1140 use std::{env, sync::Arc};
1141 use theme::{LoadThemes, SyntaxTheme};
1142 use util::test::{marked_text_ranges, sample_text};
1143 use Bias::*;
1144
1145 #[gpui::test(iterations = 100)]
1146 async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1147 cx.background_executor.set_block_on_ticks(0..=50);
1148 let operations = env::var("OPERATIONS")
1149 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1150 .unwrap_or(10);
1151
1152 let mut tab_size = rng.gen_range(1..=4);
1153 let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1154 let excerpt_header_height = rng.gen_range(1..=5);
1155 let font_size = px(14.0);
1156 let max_wrap_width = 300.0;
1157 let mut wrap_width = if rng.gen_bool(0.1) {
1158 None
1159 } else {
1160 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1161 };
1162
1163 log::info!("tab size: {}", tab_size);
1164 log::info!("wrap width: {:?}", wrap_width);
1165
1166 cx.update(|cx| {
1167 init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1168 });
1169
1170 let buffer = cx.update(|cx| {
1171 if rng.gen() {
1172 let len = rng.gen_range(0..10);
1173 let text = util::RandomCharIter::new(&mut rng)
1174 .take(len)
1175 .collect::<String>();
1176 MultiBuffer::build_simple(&text, cx)
1177 } else {
1178 MultiBuffer::build_random(&mut rng, cx)
1179 }
1180 });
1181
1182 let map = cx.new_model(|cx| {
1183 DisplayMap::new(
1184 buffer.clone(),
1185 font("Helvetica"),
1186 font_size,
1187 wrap_width,
1188 true,
1189 buffer_start_excerpt_header_height,
1190 excerpt_header_height,
1191 0,
1192 FoldPlaceholder::test(),
1193 cx,
1194 )
1195 });
1196 let mut notifications = observe(&map, cx);
1197 let mut fold_count = 0;
1198 let mut blocks = Vec::new();
1199
1200 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1201 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1202 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1203 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1204 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1205 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1206 log::info!("display text: {:?}", snapshot.text());
1207
1208 for _i in 0..operations {
1209 match rng.gen_range(0..100) {
1210 0..=19 => {
1211 wrap_width = if rng.gen_bool(0.2) {
1212 None
1213 } else {
1214 Some(px(rng.gen_range(0.0..=max_wrap_width)))
1215 };
1216 log::info!("setting wrap width to {:?}", wrap_width);
1217 map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1218 }
1219 20..=29 => {
1220 let mut tab_sizes = vec![1, 2, 3, 4];
1221 tab_sizes.remove((tab_size - 1) as usize);
1222 tab_size = *tab_sizes.choose(&mut rng).unwrap();
1223 log::info!("setting tab size to {:?}", tab_size);
1224 cx.update(|cx| {
1225 cx.update_global::<SettingsStore, _>(|store, cx| {
1226 store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1227 s.defaults.tab_size = NonZeroU32::new(tab_size);
1228 });
1229 });
1230 });
1231 }
1232 30..=44 => {
1233 map.update(cx, |map, cx| {
1234 if rng.gen() || blocks.is_empty() {
1235 let buffer = map.snapshot(cx).buffer_snapshot;
1236 let block_properties = (0..rng.gen_range(1..=1))
1237 .map(|_| {
1238 let position =
1239 buffer.anchor_after(buffer.clip_offset(
1240 rng.gen_range(0..=buffer.len()),
1241 Bias::Left,
1242 ));
1243
1244 let disposition = if rng.gen() {
1245 BlockDisposition::Above
1246 } else {
1247 BlockDisposition::Below
1248 };
1249 let height = rng.gen_range(1..5);
1250 log::info!(
1251 "inserting block {:?} {:?} with height {}",
1252 disposition,
1253 position.to_point(&buffer),
1254 height
1255 );
1256 BlockProperties {
1257 style: BlockStyle::Fixed,
1258 position,
1259 height,
1260 disposition,
1261 render: Box::new(|_| div().into_any()),
1262 }
1263 })
1264 .collect::<Vec<_>>();
1265 blocks.extend(map.insert_blocks(block_properties, cx));
1266 } else {
1267 blocks.shuffle(&mut rng);
1268 let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1269 let block_ids_to_remove = (0..remove_count)
1270 .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1271 .collect();
1272 log::info!("removing block ids {:?}", block_ids_to_remove);
1273 map.remove_blocks(block_ids_to_remove, cx);
1274 }
1275 });
1276 }
1277 45..=79 => {
1278 let mut ranges = Vec::new();
1279 for _ in 0..rng.gen_range(1..=3) {
1280 buffer.read_with(cx, |buffer, cx| {
1281 let buffer = buffer.read(cx);
1282 let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1283 let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1284 ranges.push(start..end);
1285 });
1286 }
1287
1288 if rng.gen() && fold_count > 0 {
1289 log::info!("unfolding ranges: {:?}", ranges);
1290 map.update(cx, |map, cx| {
1291 map.unfold(ranges, true, cx);
1292 });
1293 } else {
1294 log::info!("folding ranges: {:?}", ranges);
1295 map.update(cx, |map, cx| {
1296 map.fold(
1297 ranges
1298 .into_iter()
1299 .map(|range| (range, FoldPlaceholder::test())),
1300 cx,
1301 );
1302 });
1303 }
1304 }
1305 _ => {
1306 buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1307 }
1308 }
1309
1310 if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1311 notifications.next().await.unwrap();
1312 }
1313
1314 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1315 fold_count = snapshot.fold_count();
1316 log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1317 log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1318 log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1319 log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1320 log::info!("block text: {:?}", snapshot.block_snapshot.text());
1321 log::info!("display text: {:?}", snapshot.text());
1322
1323 // Line boundaries
1324 let buffer = &snapshot.buffer_snapshot;
1325 for _ in 0..5 {
1326 let row = rng.gen_range(0..=buffer.max_point().row);
1327 let column = rng.gen_range(0..=buffer.line_len(MultiBufferRow(row)));
1328 let point = buffer.clip_point(Point::new(row, column), Left);
1329
1330 let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1331 let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1332
1333 assert!(prev_buffer_bound <= point);
1334 assert!(next_buffer_bound >= point);
1335 assert_eq!(prev_buffer_bound.column, 0);
1336 assert_eq!(prev_display_bound.column(), 0);
1337 if next_buffer_bound < buffer.max_point() {
1338 assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1339 }
1340
1341 assert_eq!(
1342 prev_display_bound,
1343 prev_buffer_bound.to_display_point(&snapshot),
1344 "row boundary before {:?}. reported buffer row boundary: {:?}",
1345 point,
1346 prev_buffer_bound
1347 );
1348 assert_eq!(
1349 next_display_bound,
1350 next_buffer_bound.to_display_point(&snapshot),
1351 "display row boundary after {:?}. reported buffer row boundary: {:?}",
1352 point,
1353 next_buffer_bound
1354 );
1355 assert_eq!(
1356 prev_buffer_bound,
1357 prev_display_bound.to_point(&snapshot),
1358 "row boundary before {:?}. reported display row boundary: {:?}",
1359 point,
1360 prev_display_bound
1361 );
1362 assert_eq!(
1363 next_buffer_bound,
1364 next_display_bound.to_point(&snapshot),
1365 "row boundary after {:?}. reported display row boundary: {:?}",
1366 point,
1367 next_display_bound
1368 );
1369 }
1370
1371 // Movement
1372 let min_point = snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 0), Left);
1373 let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1374 for _ in 0..5 {
1375 let row = rng.gen_range(0..=snapshot.max_point().row().0);
1376 let column = rng.gen_range(0..=snapshot.line_len(DisplayRow(row)));
1377 let point = snapshot.clip_point(DisplayPoint::new(DisplayRow(row), column), Left);
1378
1379 log::info!("Moving from point {:?}", point);
1380
1381 let moved_right = movement::right(&snapshot, point);
1382 log::info!("Right {:?}", moved_right);
1383 if point < max_point {
1384 assert!(moved_right > point);
1385 if point.column() == snapshot.line_len(point.row())
1386 || snapshot.soft_wrap_indent(point.row()).is_some()
1387 && point.column() == snapshot.line_len(point.row()) - 1
1388 {
1389 assert!(moved_right.row() > point.row());
1390 }
1391 } else {
1392 assert_eq!(moved_right, point);
1393 }
1394
1395 let moved_left = movement::left(&snapshot, point);
1396 log::info!("Left {:?}", moved_left);
1397 if point > min_point {
1398 assert!(moved_left < point);
1399 if point.column() == 0 {
1400 assert!(moved_left.row() < point.row());
1401 }
1402 } else {
1403 assert_eq!(moved_left, point);
1404 }
1405 }
1406 }
1407 }
1408
1409 #[cfg(target_os = "macos")]
1410 #[gpui::test(retries = 5)]
1411 async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1412 cx.background_executor
1413 .set_block_on_ticks(usize::MAX..=usize::MAX);
1414 cx.update(|cx| {
1415 init_test(cx, |_| {});
1416 });
1417
1418 let mut cx = crate::test::editor_test_context::EditorTestContext::new(cx).await;
1419 let editor = cx.editor.clone();
1420 let window = cx.window;
1421
1422 _ = cx.update_window(window, |_, cx| {
1423 let text_layout_details =
1424 editor.update(cx, |editor, cx| editor.text_layout_details(cx));
1425
1426 let font_size = px(12.0);
1427 let wrap_width = Some(px(64.));
1428
1429 let text = "one two three four five\nsix seven eight";
1430 let buffer = MultiBuffer::build_simple(text, cx);
1431 let map = cx.new_model(|cx| {
1432 DisplayMap::new(
1433 buffer.clone(),
1434 font("Helvetica"),
1435 font_size,
1436 wrap_width,
1437 true,
1438 1,
1439 1,
1440 0,
1441 FoldPlaceholder::test(),
1442 cx,
1443 )
1444 });
1445
1446 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1447 assert_eq!(
1448 snapshot.text_chunks(DisplayRow(0)).collect::<String>(),
1449 "one two \nthree four \nfive\nsix seven \neight"
1450 );
1451 assert_eq!(
1452 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Left),
1453 DisplayPoint::new(DisplayRow(0), 7)
1454 );
1455 assert_eq!(
1456 snapshot.clip_point(DisplayPoint::new(DisplayRow(0), 8), Bias::Right),
1457 DisplayPoint::new(DisplayRow(1), 0)
1458 );
1459 assert_eq!(
1460 movement::right(&snapshot, DisplayPoint::new(DisplayRow(0), 7)),
1461 DisplayPoint::new(DisplayRow(1), 0)
1462 );
1463 assert_eq!(
1464 movement::left(&snapshot, DisplayPoint::new(DisplayRow(1), 0)),
1465 DisplayPoint::new(DisplayRow(0), 7)
1466 );
1467
1468 let x = snapshot
1469 .x_for_display_point(DisplayPoint::new(DisplayRow(1), 10), &text_layout_details);
1470 assert_eq!(
1471 movement::up(
1472 &snapshot,
1473 DisplayPoint::new(DisplayRow(1), 10),
1474 language::SelectionGoal::None,
1475 false,
1476 &text_layout_details,
1477 ),
1478 (
1479 DisplayPoint::new(DisplayRow(0), 7),
1480 language::SelectionGoal::HorizontalPosition(x.0)
1481 )
1482 );
1483 assert_eq!(
1484 movement::down(
1485 &snapshot,
1486 DisplayPoint::new(DisplayRow(0), 7),
1487 language::SelectionGoal::HorizontalPosition(x.0),
1488 false,
1489 &text_layout_details
1490 ),
1491 (
1492 DisplayPoint::new(DisplayRow(1), 10),
1493 language::SelectionGoal::HorizontalPosition(x.0)
1494 )
1495 );
1496 assert_eq!(
1497 movement::down(
1498 &snapshot,
1499 DisplayPoint::new(DisplayRow(1), 10),
1500 language::SelectionGoal::HorizontalPosition(x.0),
1501 false,
1502 &text_layout_details
1503 ),
1504 (
1505 DisplayPoint::new(DisplayRow(2), 4),
1506 language::SelectionGoal::HorizontalPosition(x.0)
1507 )
1508 );
1509
1510 let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1511 buffer.update(cx, |buffer, cx| {
1512 buffer.edit([(ix..ix, "and ")], None, cx);
1513 });
1514
1515 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1516 assert_eq!(
1517 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1518 "three four \nfive\nsix and \nseven eight"
1519 );
1520
1521 // Re-wrap on font size changes
1522 map.update(cx, |map, cx| {
1523 map.set_font(font("Helvetica"), px(font_size.0 + 3.), cx)
1524 });
1525
1526 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1527 assert_eq!(
1528 snapshot.text_chunks(DisplayRow(1)).collect::<String>(),
1529 "three \nfour five\nsix and \nseven \neight"
1530 )
1531 });
1532 }
1533
1534 #[gpui::test]
1535 fn test_text_chunks(cx: &mut gpui::AppContext) {
1536 init_test(cx, |_| {});
1537
1538 let text = sample_text(6, 6, 'a');
1539 let buffer = MultiBuffer::build_simple(&text, cx);
1540
1541 let font_size = px(14.0);
1542 let map = cx.new_model(|cx| {
1543 DisplayMap::new(
1544 buffer.clone(),
1545 font("Helvetica"),
1546 font_size,
1547 None,
1548 true,
1549 1,
1550 1,
1551 0,
1552 FoldPlaceholder::test(),
1553 cx,
1554 )
1555 });
1556
1557 buffer.update(cx, |buffer, cx| {
1558 buffer.edit(
1559 vec![
1560 (
1561 MultiBufferPoint::new(1, 0)..MultiBufferPoint::new(1, 0),
1562 "\t",
1563 ),
1564 (
1565 MultiBufferPoint::new(1, 1)..MultiBufferPoint::new(1, 1),
1566 "\t",
1567 ),
1568 (
1569 MultiBufferPoint::new(2, 1)..MultiBufferPoint::new(2, 1),
1570 "\t",
1571 ),
1572 ],
1573 None,
1574 cx,
1575 )
1576 });
1577
1578 assert_eq!(
1579 map.update(cx, |map, cx| map.snapshot(cx))
1580 .text_chunks(DisplayRow(1))
1581 .collect::<String>()
1582 .lines()
1583 .next(),
1584 Some(" b bbbbb")
1585 );
1586 assert_eq!(
1587 map.update(cx, |map, cx| map.snapshot(cx))
1588 .text_chunks(DisplayRow(2))
1589 .collect::<String>()
1590 .lines()
1591 .next(),
1592 Some("c ccccc")
1593 );
1594 }
1595
1596 #[gpui::test]
1597 async fn test_chunks(cx: &mut gpui::TestAppContext) {
1598 use unindent::Unindent as _;
1599
1600 let text = r#"
1601 fn outer() {}
1602
1603 mod module {
1604 fn inner() {}
1605 }"#
1606 .unindent();
1607
1608 let theme =
1609 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1610 let language = Arc::new(
1611 Language::new(
1612 LanguageConfig {
1613 name: "Test".into(),
1614 matcher: LanguageMatcher {
1615 path_suffixes: vec![".test".to_string()],
1616 ..Default::default()
1617 },
1618 ..Default::default()
1619 },
1620 Some(tree_sitter_rust::language()),
1621 )
1622 .with_highlights_query(
1623 r#"
1624 (mod_item name: (identifier) body: _ @mod.body)
1625 (function_item name: (identifier) @fn.name)
1626 "#,
1627 )
1628 .unwrap(),
1629 );
1630 language.set_theme(&theme);
1631
1632 cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1633
1634 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1635 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1636 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1637
1638 let font_size = px(14.0);
1639
1640 let map = cx.new_model(|cx| {
1641 DisplayMap::new(
1642 buffer,
1643 font("Helvetica"),
1644 font_size,
1645 None,
1646 true,
1647 1,
1648 1,
1649 1,
1650 FoldPlaceholder::test(),
1651 cx,
1652 )
1653 });
1654 assert_eq!(
1655 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1656 vec![
1657 ("fn ".to_string(), None),
1658 ("outer".to_string(), Some(Hsla::blue())),
1659 ("() {}\n\nmod module ".to_string(), None),
1660 ("{\n fn ".to_string(), Some(Hsla::red())),
1661 ("inner".to_string(), Some(Hsla::blue())),
1662 ("() {}\n}".to_string(), Some(Hsla::red())),
1663 ]
1664 );
1665 assert_eq!(
1666 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1667 vec![
1668 (" fn ".to_string(), Some(Hsla::red())),
1669 ("inner".to_string(), Some(Hsla::blue())),
1670 ("() {}\n}".to_string(), Some(Hsla::red())),
1671 ]
1672 );
1673
1674 map.update(cx, |map, cx| {
1675 map.fold(
1676 vec![(
1677 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1678 FoldPlaceholder::test(),
1679 )],
1680 cx,
1681 )
1682 });
1683 assert_eq!(
1684 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(2), &map, &theme, cx)),
1685 vec![
1686 ("fn ".to_string(), None),
1687 ("out".to_string(), Some(Hsla::blue())),
1688 ("⋯".to_string(), None),
1689 (" fn ".to_string(), Some(Hsla::red())),
1690 ("inner".to_string(), Some(Hsla::blue())),
1691 ("() {}\n}".to_string(), Some(Hsla::red())),
1692 ]
1693 );
1694 }
1695
1696 // todo(linux) fails due to pixel differences in text rendering
1697 #[cfg(target_os = "macos")]
1698 #[gpui::test]
1699 async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1700 use unindent::Unindent as _;
1701
1702 cx.background_executor
1703 .set_block_on_ticks(usize::MAX..=usize::MAX);
1704
1705 let text = r#"
1706 fn outer() {}
1707
1708 mod module {
1709 fn inner() {}
1710 }"#
1711 .unindent();
1712
1713 let theme =
1714 SyntaxTheme::new_test(vec![("mod.body", Hsla::red()), ("fn.name", Hsla::blue())]);
1715 let language = Arc::new(
1716 Language::new(
1717 LanguageConfig {
1718 name: "Test".into(),
1719 matcher: LanguageMatcher {
1720 path_suffixes: vec![".test".to_string()],
1721 ..Default::default()
1722 },
1723 ..Default::default()
1724 },
1725 Some(tree_sitter_rust::language()),
1726 )
1727 .with_highlights_query(
1728 r#"
1729 (mod_item name: (identifier) body: _ @mod.body)
1730 (function_item name: (identifier) @fn.name)
1731 "#,
1732 )
1733 .unwrap(),
1734 );
1735 language.set_theme(&theme);
1736
1737 cx.update(|cx| init_test(cx, |_| {}));
1738
1739 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1740 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1741 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1742
1743 let font_size = px(16.0);
1744
1745 let map = cx.new_model(|cx| {
1746 DisplayMap::new(
1747 buffer,
1748 font("Courier"),
1749 font_size,
1750 Some(px(40.0)),
1751 true,
1752 1,
1753 1,
1754 0,
1755 FoldPlaceholder::test(),
1756 cx,
1757 )
1758 });
1759 assert_eq!(
1760 cx.update(|cx| syntax_chunks(DisplayRow(0)..DisplayRow(5), &map, &theme, cx)),
1761 [
1762 ("fn \n".to_string(), None),
1763 ("oute\nr".to_string(), Some(Hsla::blue())),
1764 ("() \n{}\n\n".to_string(), None),
1765 ]
1766 );
1767 assert_eq!(
1768 cx.update(|cx| syntax_chunks(DisplayRow(3)..DisplayRow(5), &map, &theme, cx)),
1769 [("{}\n\n".to_string(), None)]
1770 );
1771
1772 map.update(cx, |map, cx| {
1773 map.fold(
1774 vec![(
1775 MultiBufferPoint::new(0, 6)..MultiBufferPoint::new(3, 2),
1776 FoldPlaceholder::test(),
1777 )],
1778 cx,
1779 )
1780 });
1781 assert_eq!(
1782 cx.update(|cx| syntax_chunks(DisplayRow(1)..DisplayRow(4), &map, &theme, cx)),
1783 [
1784 ("out".to_string(), Some(Hsla::blue())),
1785 ("⋯\n".to_string(), None),
1786 (" \nfn ".to_string(), Some(Hsla::red())),
1787 ("i\n".to_string(), Some(Hsla::blue()))
1788 ]
1789 );
1790 }
1791
1792 #[gpui::test]
1793 async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1794 cx.update(|cx| init_test(cx, |_| {}));
1795
1796 let theme =
1797 SyntaxTheme::new_test(vec![("operator", Hsla::red()), ("string", Hsla::green())]);
1798 let language = Arc::new(
1799 Language::new(
1800 LanguageConfig {
1801 name: "Test".into(),
1802 matcher: LanguageMatcher {
1803 path_suffixes: vec![".test".to_string()],
1804 ..Default::default()
1805 },
1806 ..Default::default()
1807 },
1808 Some(tree_sitter_rust::language()),
1809 )
1810 .with_highlights_query(
1811 r#"
1812 ":" @operator
1813 (string_literal) @string
1814 "#,
1815 )
1816 .unwrap(),
1817 );
1818 language.set_theme(&theme);
1819
1820 let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1821
1822 let buffer = cx.new_model(|cx| Buffer::local(text, cx).with_language(language, cx));
1823 cx.condition(&buffer, |buf, _| !buf.is_parsing()).await;
1824
1825 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1826 let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1827
1828 let font_size = px(16.0);
1829 let map = cx.new_model(|cx| {
1830 DisplayMap::new(
1831 buffer,
1832 font("Courier"),
1833 font_size,
1834 None,
1835 true,
1836 1,
1837 1,
1838 1,
1839 FoldPlaceholder::test(),
1840 cx,
1841 )
1842 });
1843
1844 enum MyType {}
1845
1846 let style = HighlightStyle {
1847 color: Some(Hsla::blue()),
1848 ..Default::default()
1849 };
1850
1851 map.update(cx, |map, _cx| {
1852 map.highlight_text(
1853 TypeId::of::<MyType>(),
1854 highlighted_ranges
1855 .into_iter()
1856 .map(|range| {
1857 buffer_snapshot.anchor_before(range.start)
1858 ..buffer_snapshot.anchor_before(range.end)
1859 })
1860 .collect(),
1861 style,
1862 );
1863 });
1864
1865 assert_eq!(
1866 cx.update(|cx| chunks(DisplayRow(0)..DisplayRow(10), &map, &theme, cx)),
1867 [
1868 ("const ".to_string(), None, None),
1869 ("a".to_string(), None, Some(Hsla::blue())),
1870 (":".to_string(), Some(Hsla::red()), None),
1871 (" B = ".to_string(), None, None),
1872 ("\"c ".to_string(), Some(Hsla::green()), None),
1873 ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1874 ("\"".to_string(), Some(Hsla::green()), None),
1875 ]
1876 );
1877 }
1878
1879 #[gpui::test]
1880 fn test_clip_point(cx: &mut gpui::AppContext) {
1881 init_test(cx, |_| {});
1882
1883 fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1884 let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1885
1886 match bias {
1887 Bias::Left => {
1888 if shift_right {
1889 *markers[1].column_mut() += 1;
1890 }
1891
1892 assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1893 }
1894 Bias::Right => {
1895 if shift_right {
1896 *markers[0].column_mut() += 1;
1897 }
1898
1899 assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1900 }
1901 };
1902 }
1903
1904 use Bias::{Left, Right};
1905 assert("ˇˇα", false, Left, cx);
1906 assert("ˇˇα", true, Left, cx);
1907 assert("ˇˇα", false, Right, cx);
1908 assert("ˇαˇ", true, Right, cx);
1909 assert("ˇˇ✋", false, Left, cx);
1910 assert("ˇˇ✋", true, Left, cx);
1911 assert("ˇˇ✋", false, Right, cx);
1912 assert("ˇ✋ˇ", true, Right, cx);
1913 assert("ˇˇ🍐", false, Left, cx);
1914 assert("ˇˇ🍐", true, Left, cx);
1915 assert("ˇˇ🍐", false, Right, cx);
1916 assert("ˇ🍐ˇ", true, Right, cx);
1917 assert("ˇˇ\t", false, Left, cx);
1918 assert("ˇˇ\t", true, Left, cx);
1919 assert("ˇˇ\t", false, Right, cx);
1920 assert("ˇ\tˇ", true, Right, cx);
1921 assert(" ˇˇ\t", false, Left, cx);
1922 assert(" ˇˇ\t", true, Left, cx);
1923 assert(" ˇˇ\t", false, Right, cx);
1924 assert(" ˇ\tˇ", true, Right, cx);
1925 assert(" ˇˇ\t", false, Left, cx);
1926 assert(" ˇˇ\t", false, Right, cx);
1927 }
1928
1929 #[gpui::test]
1930 fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1931 init_test(cx, |_| {});
1932
1933 fn assert(text: &str, cx: &mut gpui::AppContext) {
1934 let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1935 unmarked_snapshot.clip_at_line_ends = true;
1936 assert_eq!(
1937 unmarked_snapshot.clip_point(markers[1], Bias::Left),
1938 markers[0]
1939 );
1940 }
1941
1942 assert("ˇˇ", cx);
1943 assert("ˇaˇ", cx);
1944 assert("aˇbˇ", cx);
1945 assert("aˇαˇ", cx);
1946 }
1947
1948 #[gpui::test]
1949 fn test_creases(cx: &mut gpui::AppContext) {
1950 init_test(cx, |_| {});
1951
1952 let text = "aaa\nbbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\nkkk\nlll";
1953 let buffer = MultiBuffer::build_simple(text, cx);
1954 let font_size = px(14.0);
1955 cx.new_model(|cx| {
1956 let mut map = DisplayMap::new(
1957 buffer.clone(),
1958 font("Helvetica"),
1959 font_size,
1960 None,
1961 true,
1962 1,
1963 1,
1964 0,
1965 FoldPlaceholder::test(),
1966 cx,
1967 );
1968 let snapshot = map.buffer.read(cx).snapshot(cx);
1969 let range =
1970 snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_after(Point::new(3, 3));
1971
1972 map.crease_map.insert(
1973 [Crease::new(
1974 range,
1975 FoldPlaceholder::test(),
1976 |_row, _status, _toggle, _cx| div(),
1977 |_row, _status, _cx| div(),
1978 )],
1979 &map.buffer.read(cx).snapshot(cx),
1980 );
1981
1982 map
1983 });
1984 }
1985
1986 #[gpui::test]
1987 fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1988 init_test(cx, |_| {});
1989
1990 let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1991 let buffer = MultiBuffer::build_simple(text, cx);
1992 let font_size = px(14.0);
1993
1994 let map = cx.new_model(|cx| {
1995 DisplayMap::new(
1996 buffer.clone(),
1997 font("Helvetica"),
1998 font_size,
1999 None,
2000 true,
2001 1,
2002 1,
2003 0,
2004 FoldPlaceholder::test(),
2005 cx,
2006 )
2007 });
2008 let map = map.update(cx, |map, cx| map.snapshot(cx));
2009 assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
2010 assert_eq!(
2011 map.text_chunks(DisplayRow(0)).collect::<String>(),
2012 "✅ α\nβ \n🏀β γ"
2013 );
2014 assert_eq!(
2015 map.text_chunks(DisplayRow(1)).collect::<String>(),
2016 "β \n🏀β γ"
2017 );
2018 assert_eq!(
2019 map.text_chunks(DisplayRow(2)).collect::<String>(),
2020 "🏀β γ"
2021 );
2022
2023 let point = MultiBufferPoint::new(0, "✅\t\t".len() as u32);
2024 let display_point = DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32);
2025 assert_eq!(point.to_display_point(&map), display_point);
2026 assert_eq!(display_point.to_point(&map), point);
2027
2028 let point = MultiBufferPoint::new(1, "β\t".len() as u32);
2029 let display_point = DisplayPoint::new(DisplayRow(1), "β ".len() as u32);
2030 assert_eq!(point.to_display_point(&map), display_point);
2031 assert_eq!(display_point.to_point(&map), point,);
2032
2033 let point = MultiBufferPoint::new(2, "🏀β\t\t".len() as u32);
2034 let display_point = DisplayPoint::new(DisplayRow(2), "🏀β ".len() as u32);
2035 assert_eq!(point.to_display_point(&map), display_point);
2036 assert_eq!(display_point.to_point(&map), point,);
2037
2038 // Display points inside of expanded tabs
2039 assert_eq!(
2040 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2041 MultiBufferPoint::new(0, "✅\t".len() as u32),
2042 );
2043 assert_eq!(
2044 DisplayPoint::new(DisplayRow(0), "✅ ".len() as u32).to_point(&map),
2045 MultiBufferPoint::new(0, "✅".len() as u32),
2046 );
2047
2048 // Clipping display points inside of multi-byte characters
2049 assert_eq!(
2050 map.clip_point(
2051 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2052 Left
2053 ),
2054 DisplayPoint::new(DisplayRow(0), 0)
2055 );
2056 assert_eq!(
2057 map.clip_point(
2058 DisplayPoint::new(DisplayRow(0), "✅".len() as u32 - 1),
2059 Bias::Right
2060 ),
2061 DisplayPoint::new(DisplayRow(0), "✅".len() as u32)
2062 );
2063 }
2064
2065 #[gpui::test]
2066 fn test_max_point(cx: &mut gpui::AppContext) {
2067 init_test(cx, |_| {});
2068
2069 let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
2070 let font_size = px(14.0);
2071 let map = cx.new_model(|cx| {
2072 DisplayMap::new(
2073 buffer.clone(),
2074 font("Helvetica"),
2075 font_size,
2076 None,
2077 true,
2078 1,
2079 1,
2080 0,
2081 FoldPlaceholder::test(),
2082 cx,
2083 )
2084 });
2085 assert_eq!(
2086 map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
2087 DisplayPoint::new(DisplayRow(1), 11)
2088 )
2089 }
2090
2091 fn syntax_chunks(
2092 rows: Range<DisplayRow>,
2093 map: &Model<DisplayMap>,
2094 theme: &SyntaxTheme,
2095 cx: &mut AppContext,
2096 ) -> Vec<(String, Option<Hsla>)> {
2097 chunks(rows, map, theme, cx)
2098 .into_iter()
2099 .map(|(text, color, _)| (text, color))
2100 .collect()
2101 }
2102
2103 fn chunks(
2104 rows: Range<DisplayRow>,
2105 map: &Model<DisplayMap>,
2106 theme: &SyntaxTheme,
2107 cx: &mut AppContext,
2108 ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
2109 let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
2110 let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
2111 for chunk in snapshot.chunks(rows, true, HighlightStyles::default()) {
2112 let syntax_color = chunk
2113 .syntax_highlight_id
2114 .and_then(|id| id.style(theme)?.color);
2115 let highlight_color = chunk.highlight_style.and_then(|style| style.color);
2116 if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
2117 if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
2118 last_chunk.push_str(chunk.text);
2119 continue;
2120 }
2121 }
2122 chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
2123 }
2124 chunks
2125 }
2126
2127 fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
2128 let settings = SettingsStore::test(cx);
2129 cx.set_global(settings);
2130 language::init(cx);
2131 crate::init(cx);
2132 Project::init_settings(cx);
2133 theme::init(LoadThemes::JustBase, cx);
2134 cx.update_global::<SettingsStore, _>(|store, cx| {
2135 store.update_user_settings::<AllLanguageSettings>(cx, f);
2136 });
2137 }
2138}