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