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