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