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