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