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