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