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
576 let range = display_row..display_row + 1;
577 for chunk in self.highlighted_chunks(range, false, &editor_style) {
578 line.push_str(chunk.chunk);
579
580 let text_style = if let Some(style) = chunk.style {
581 Cow::Owned(editor_style.text.clone().highlight(style))
582 } else {
583 Cow::Borrowed(&editor_style.text)
584 };
585
586 runs.push(text_style.to_run(chunk.chunk.len()))
587 }
588
589 if line.ends_with('\n') {
590 line.pop();
591 if let Some(last_run) = runs.last_mut() {
592 last_run.len -= 1;
593 if last_run.len == 0 {
594 runs.pop();
595 }
596 }
597 }
598
599 let font_size = editor_style.text.font_size.to_pixels(*rem_size);
600 text_system
601 .layout_text(&line, font_size, &runs, None)
602 .unwrap()
603 .pop()
604 .unwrap()
605 }
606
607 pub fn x_for_point(
608 &self,
609 display_point: DisplayPoint,
610 text_layout_details: &TextLayoutDetails,
611 ) -> Pixels {
612 let layout_line = self.lay_out_line_for_row(display_point.row(), text_layout_details);
613 layout_line.x_for_index(display_point.column() as usize)
614 }
615
616 pub fn column_for_x(
617 &self,
618 display_row: u32,
619 x_coordinate: Pixels,
620 text_layout_details: &TextLayoutDetails,
621 ) -> u32 {
622 let layout_line = self.lay_out_line_for_row(display_row, text_layout_details);
623 layout_line.closest_index_for_x(x_coordinate) as u32
624 }
625
626 pub fn chars_at(
627 &self,
628 mut point: DisplayPoint,
629 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
630 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
631 self.text_chunks(point.row())
632 .flat_map(str::chars)
633 .skip_while({
634 let mut column = 0;
635 move |char| {
636 let at_point = column >= point.column();
637 column += char.len_utf8() as u32;
638 !at_point
639 }
640 })
641 .map(move |ch| {
642 let result = (ch, point);
643 if ch == '\n' {
644 *point.row_mut() += 1;
645 *point.column_mut() = 0;
646 } else {
647 *point.column_mut() += ch.len_utf8() as u32;
648 }
649 result
650 })
651 }
652
653 pub fn reverse_chars_at(
654 &self,
655 mut point: DisplayPoint,
656 ) -> impl Iterator<Item = (char, DisplayPoint)> + '_ {
657 point = DisplayPoint(self.block_snapshot.clip_point(point.0, Bias::Left));
658 self.reverse_text_chunks(point.row())
659 .flat_map(|chunk| chunk.chars().rev())
660 .skip_while({
661 let mut column = self.line_len(point.row());
662 if self.max_point().row() > point.row() {
663 column += 1;
664 }
665
666 move |char| {
667 let at_point = column <= point.column();
668 column = column.saturating_sub(char.len_utf8() as u32);
669 !at_point
670 }
671 })
672 .map(move |ch| {
673 if ch == '\n' {
674 *point.row_mut() -= 1;
675 *point.column_mut() = self.line_len(point.row());
676 } else {
677 *point.column_mut() = point.column().saturating_sub(ch.len_utf8() as u32);
678 }
679 (ch, point)
680 })
681 }
682
683 pub fn column_to_chars(&self, display_row: u32, target: u32) -> u32 {
684 let mut count = 0;
685 let mut column = 0;
686 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
687 if column >= target {
688 break;
689 }
690 count += 1;
691 column += c.len_utf8() as u32;
692 }
693 count
694 }
695
696 pub fn column_from_chars(&self, display_row: u32, char_count: u32) -> u32 {
697 let mut column = 0;
698
699 for (count, (c, _)) in self.chars_at(DisplayPoint::new(display_row, 0)).enumerate() {
700 if c == '\n' || count >= char_count as usize {
701 break;
702 }
703 column += c.len_utf8() as u32;
704 }
705
706 column
707 }
708
709 pub fn clip_point(&self, point: DisplayPoint, bias: Bias) -> DisplayPoint {
710 let mut clipped = self.block_snapshot.clip_point(point.0, bias);
711 if self.clip_at_line_ends {
712 clipped = self.clip_at_line_end(DisplayPoint(clipped)).0
713 }
714 DisplayPoint(clipped)
715 }
716
717 pub fn clip_at_line_end(&self, point: DisplayPoint) -> DisplayPoint {
718 let mut point = point.0;
719 if point.column == self.line_len(point.row) {
720 point.column = point.column.saturating_sub(1);
721 point = self.block_snapshot.clip_point(point, Bias::Left);
722 }
723 DisplayPoint(point)
724 }
725
726 pub fn folds_in_range<T>(&self, range: Range<T>) -> impl Iterator<Item = &Range<Anchor>>
727 where
728 T: ToOffset,
729 {
730 self.fold_snapshot.folds_in_range(range)
731 }
732
733 pub fn blocks_in_range(
734 &self,
735 rows: Range<u32>,
736 ) -> impl Iterator<Item = (u32, &TransformBlock)> {
737 self.block_snapshot.blocks_in_range(rows)
738 }
739
740 pub fn intersects_fold<T: ToOffset>(&self, offset: T) -> bool {
741 self.fold_snapshot.intersects_fold(offset)
742 }
743
744 pub fn is_line_folded(&self, buffer_row: u32) -> bool {
745 self.fold_snapshot.is_line_folded(buffer_row)
746 }
747
748 pub fn is_block_line(&self, display_row: u32) -> bool {
749 self.block_snapshot.is_block_line(display_row)
750 }
751
752 pub fn soft_wrap_indent(&self, display_row: u32) -> Option<u32> {
753 let wrap_row = self
754 .block_snapshot
755 .to_wrap_point(BlockPoint::new(display_row, 0))
756 .row();
757 self.wrap_snapshot.soft_wrap_indent(wrap_row)
758 }
759
760 pub fn text(&self) -> String {
761 self.text_chunks(0).collect()
762 }
763
764 pub fn line(&self, display_row: u32) -> String {
765 let mut result = String::new();
766 for chunk in self.text_chunks(display_row) {
767 if let Some(ix) = chunk.find('\n') {
768 result.push_str(&chunk[0..ix]);
769 break;
770 } else {
771 result.push_str(chunk);
772 }
773 }
774 result
775 }
776
777 pub fn line_indent(&self, display_row: u32) -> (u32, bool) {
778 let mut indent = 0;
779 let mut is_blank = true;
780 for (c, _) in self.chars_at(DisplayPoint::new(display_row, 0)) {
781 if c == ' ' {
782 indent += 1;
783 } else {
784 is_blank = c == '\n';
785 break;
786 }
787 }
788 (indent, is_blank)
789 }
790
791 pub fn line_indent_for_buffer_row(&self, buffer_row: u32) -> (u32, bool) {
792 let (buffer, range) = self
793 .buffer_snapshot
794 .buffer_line_for_row(buffer_row)
795 .unwrap();
796
797 let mut indent_size = 0;
798 let mut is_blank = false;
799 for c in buffer.chars_at(Point::new(range.start.row, 0)) {
800 if c == ' ' || c == '\t' {
801 indent_size += 1;
802 } else {
803 if c == '\n' {
804 is_blank = true;
805 }
806 break;
807 }
808 }
809
810 (indent_size, is_blank)
811 }
812
813 pub fn line_len(&self, row: u32) -> u32 {
814 self.block_snapshot.line_len(row)
815 }
816
817 pub fn longest_row(&self) -> u32 {
818 self.block_snapshot.longest_row()
819 }
820
821 pub fn fold_for_line(self: &Self, buffer_row: u32) -> Option<FoldStatus> {
822 if self.is_line_folded(buffer_row) {
823 Some(FoldStatus::Folded)
824 } else if self.is_foldable(buffer_row) {
825 Some(FoldStatus::Foldable)
826 } else {
827 None
828 }
829 }
830
831 pub fn is_foldable(self: &Self, buffer_row: u32) -> bool {
832 let max_row = self.buffer_snapshot.max_buffer_row();
833 if buffer_row >= max_row {
834 return false;
835 }
836
837 let (indent_size, is_blank) = self.line_indent_for_buffer_row(buffer_row);
838 if is_blank {
839 return false;
840 }
841
842 for next_row in (buffer_row + 1)..=max_row {
843 let (next_indent_size, next_line_is_blank) = self.line_indent_for_buffer_row(next_row);
844 if next_indent_size > indent_size {
845 return true;
846 } else if !next_line_is_blank {
847 break;
848 }
849 }
850
851 false
852 }
853
854 pub fn foldable_range(self: &Self, buffer_row: u32) -> Option<Range<Point>> {
855 let start = Point::new(buffer_row, self.buffer_snapshot.line_len(buffer_row));
856 if self.is_foldable(start.row) && !self.is_line_folded(start.row) {
857 let (start_indent, _) = self.line_indent_for_buffer_row(buffer_row);
858 let max_point = self.buffer_snapshot.max_point();
859 let mut end = None;
860
861 for row in (buffer_row + 1)..=max_point.row {
862 let (indent, is_blank) = self.line_indent_for_buffer_row(row);
863 if !is_blank && indent <= start_indent {
864 let prev_row = row - 1;
865 end = Some(Point::new(
866 prev_row,
867 self.buffer_snapshot.line_len(prev_row),
868 ));
869 break;
870 }
871 }
872 let end = end.unwrap_or(max_point);
873 Some(start..end)
874 } else {
875 None
876 }
877 }
878
879 #[cfg(any(test, feature = "test-support"))]
880 pub fn text_highlight_ranges<Tag: ?Sized + 'static>(
881 &self,
882 ) -> Option<Arc<(HighlightStyle, Vec<Range<Anchor>>)>> {
883 let type_id = TypeId::of::<Tag>();
884 self.text_highlights.get(&Some(type_id)).cloned()
885 }
886
887 #[cfg(any(test, feature = "test-support"))]
888 pub fn inlay_highlights<Tag: ?Sized + 'static>(
889 &self,
890 ) -> Option<&HashMap<InlayId, (HighlightStyle, InlayHighlight)>> {
891 let type_id = TypeId::of::<Tag>();
892 self.inlay_highlights.get(&type_id)
893 }
894}
895
896#[derive(Copy, Clone, Default, Eq, Ord, PartialOrd, PartialEq)]
897pub struct DisplayPoint(BlockPoint);
898
899impl Debug for DisplayPoint {
900 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
901 f.write_fmt(format_args!(
902 "DisplayPoint({}, {})",
903 self.row(),
904 self.column()
905 ))
906 }
907}
908
909impl DisplayPoint {
910 pub fn new(row: u32, column: u32) -> Self {
911 Self(BlockPoint(Point::new(row, column)))
912 }
913
914 pub fn zero() -> Self {
915 Self::new(0, 0)
916 }
917
918 pub fn is_zero(&self) -> bool {
919 self.0.is_zero()
920 }
921
922 pub fn row(self) -> u32 {
923 self.0.row
924 }
925
926 pub fn column(self) -> u32 {
927 self.0.column
928 }
929
930 pub fn row_mut(&mut self) -> &mut u32 {
931 &mut self.0.row
932 }
933
934 pub fn column_mut(&mut self) -> &mut u32 {
935 &mut self.0.column
936 }
937
938 pub fn to_point(self, map: &DisplaySnapshot) -> Point {
939 map.display_point_to_point(self, Bias::Left)
940 }
941
942 pub fn to_offset(self, map: &DisplaySnapshot, bias: Bias) -> usize {
943 let wrap_point = map.block_snapshot.to_wrap_point(self.0);
944 let tab_point = map.wrap_snapshot.to_tab_point(wrap_point);
945 let fold_point = map.tab_snapshot.to_fold_point(tab_point, bias).0;
946 let inlay_point = fold_point.to_inlay_point(&map.fold_snapshot);
947 map.inlay_snapshot
948 .to_buffer_offset(map.inlay_snapshot.to_offset(inlay_point))
949 }
950}
951
952impl ToDisplayPoint for usize {
953 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
954 map.point_to_display_point(self.to_point(&map.buffer_snapshot), Bias::Left)
955 }
956}
957
958impl ToDisplayPoint for OffsetUtf16 {
959 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
960 self.to_offset(&map.buffer_snapshot).to_display_point(map)
961 }
962}
963
964impl ToDisplayPoint for Point {
965 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
966 map.point_to_display_point(*self, Bias::Left)
967 }
968}
969
970impl ToDisplayPoint for Anchor {
971 fn to_display_point(&self, map: &DisplaySnapshot) -> DisplayPoint {
972 self.to_point(&map.buffer_snapshot).to_display_point(map)
973 }
974}
975
976pub fn next_rows(display_row: u32, display_map: &DisplaySnapshot) -> impl Iterator<Item = u32> {
977 let max_row = display_map.max_point().row();
978 let start_row = display_row + 1;
979 let mut current = None;
980 std::iter::from_fn(move || {
981 if current == None {
982 current = Some(start_row);
983 } else {
984 current = Some(current.unwrap() + 1)
985 }
986 if current.unwrap() > max_row {
987 None
988 } else {
989 current
990 }
991 })
992}
993
994// #[cfg(test)]
995// pub mod tests {
996// use super::*;
997// use crate::{
998// movement,
999// test::{editor_test_context::EditorTestContext, marked_display_snapshot},
1000// };
1001// use gpui::{AppContext, Hsla};
1002// use language::{
1003// language_settings::{AllLanguageSettings, AllLanguageSettingsContent},
1004// Buffer, Language, LanguageConfig, SelectionGoal,
1005// };
1006// use project::Project;
1007// use rand::{prelude::*, Rng};
1008// use settings::SettingsStore;
1009// use smol::stream::StreamExt;
1010// use std::{env, sync::Arc};
1011// use theme::SyntaxTheme;
1012// use util::test::{marked_text_ranges, sample_text};
1013// use Bias::*;
1014
1015// #[gpui::test(iterations = 100)]
1016// async fn test_random_display_map(cx: &mut gpui::TestAppContext, mut rng: StdRng) {
1017// cx.foreground().set_block_on_ticks(0..=50);
1018// cx.foreground().forbid_parking();
1019// let operations = env::var("OPERATIONS")
1020// .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
1021// .unwrap_or(10);
1022
1023// let font_cache = cx.font_cache().clone();
1024// let mut tab_size = rng.gen_range(1..=4);
1025// let buffer_start_excerpt_header_height = rng.gen_range(1..=5);
1026// let excerpt_header_height = rng.gen_range(1..=5);
1027// let family_id = font_cache
1028// .load_family(&["Helvetica"], &Default::default())
1029// .unwrap();
1030// let font_id = font_cache
1031// .select_font(family_id, &Default::default())
1032// .unwrap();
1033// let font_size = 14.0;
1034// let max_wrap_width = 300.0;
1035// let mut wrap_width = if rng.gen_bool(0.1) {
1036// None
1037// } else {
1038// Some(rng.gen_range(0.0..=max_wrap_width))
1039// };
1040
1041// log::info!("tab size: {}", tab_size);
1042// log::info!("wrap width: {:?}", wrap_width);
1043
1044// cx.update(|cx| {
1045// init_test(cx, |s| s.defaults.tab_size = NonZeroU32::new(tab_size));
1046// });
1047
1048// let buffer = cx.update(|cx| {
1049// if rng.gen() {
1050// let len = rng.gen_range(0..10);
1051// let text = util::RandomCharIter::new(&mut rng)
1052// .take(len)
1053// .collect::<String>();
1054// MultiBuffer::build_simple(&text, cx)
1055// } else {
1056// MultiBuffer::build_random(&mut rng, cx)
1057// }
1058// });
1059
1060// let map = cx.add_model(|cx| {
1061// DisplayMap::new(
1062// buffer.clone(),
1063// font_id,
1064// font_size,
1065// wrap_width,
1066// buffer_start_excerpt_header_height,
1067// excerpt_header_height,
1068// cx,
1069// )
1070// });
1071// let mut notifications = observe(&map, cx);
1072// let mut fold_count = 0;
1073// let mut blocks = Vec::new();
1074
1075// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1076// log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1077// log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1078// log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1079// log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1080// log::info!("block text: {:?}", snapshot.block_snapshot.text());
1081// log::info!("display text: {:?}", snapshot.text());
1082
1083// for _i in 0..operations {
1084// match rng.gen_range(0..100) {
1085// 0..=19 => {
1086// wrap_width = if rng.gen_bool(0.2) {
1087// None
1088// } else {
1089// Some(rng.gen_range(0.0..=max_wrap_width))
1090// };
1091// log::info!("setting wrap width to {:?}", wrap_width);
1092// map.update(cx, |map, cx| map.set_wrap_width(wrap_width, cx));
1093// }
1094// 20..=29 => {
1095// let mut tab_sizes = vec![1, 2, 3, 4];
1096// tab_sizes.remove((tab_size - 1) as usize);
1097// tab_size = *tab_sizes.choose(&mut rng).unwrap();
1098// log::info!("setting tab size to {:?}", tab_size);
1099// cx.update(|cx| {
1100// cx.update_global::<SettingsStore, _, _>(|store, cx| {
1101// store.update_user_settings::<AllLanguageSettings>(cx, |s| {
1102// s.defaults.tab_size = NonZeroU32::new(tab_size);
1103// });
1104// });
1105// });
1106// }
1107// 30..=44 => {
1108// map.update(cx, |map, cx| {
1109// if rng.gen() || blocks.is_empty() {
1110// let buffer = map.snapshot(cx).buffer_snapshot;
1111// let block_properties = (0..rng.gen_range(1..=1))
1112// .map(|_| {
1113// let position =
1114// buffer.anchor_after(buffer.clip_offset(
1115// rng.gen_range(0..=buffer.len()),
1116// Bias::Left,
1117// ));
1118
1119// let disposition = if rng.gen() {
1120// BlockDisposition::Above
1121// } else {
1122// BlockDisposition::Below
1123// };
1124// let height = rng.gen_range(1..5);
1125// log::info!(
1126// "inserting block {:?} {:?} with height {}",
1127// disposition,
1128// position.to_point(&buffer),
1129// height
1130// );
1131// BlockProperties {
1132// style: BlockStyle::Fixed,
1133// position,
1134// height,
1135// disposition,
1136// render: Arc::new(|_| Empty::new().into_any()),
1137// }
1138// })
1139// .collect::<Vec<_>>();
1140// blocks.extend(map.insert_blocks(block_properties, cx));
1141// } else {
1142// blocks.shuffle(&mut rng);
1143// let remove_count = rng.gen_range(1..=4.min(blocks.len()));
1144// let block_ids_to_remove = (0..remove_count)
1145// .map(|_| blocks.remove(rng.gen_range(0..blocks.len())))
1146// .collect();
1147// log::info!("removing block ids {:?}", block_ids_to_remove);
1148// map.remove_blocks(block_ids_to_remove, cx);
1149// }
1150// });
1151// }
1152// 45..=79 => {
1153// let mut ranges = Vec::new();
1154// for _ in 0..rng.gen_range(1..=3) {
1155// buffer.read_with(cx, |buffer, cx| {
1156// let buffer = buffer.read(cx);
1157// let end = buffer.clip_offset(rng.gen_range(0..=buffer.len()), Right);
1158// let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
1159// ranges.push(start..end);
1160// });
1161// }
1162
1163// if rng.gen() && fold_count > 0 {
1164// log::info!("unfolding ranges: {:?}", ranges);
1165// map.update(cx, |map, cx| {
1166// map.unfold(ranges, true, cx);
1167// });
1168// } else {
1169// log::info!("folding ranges: {:?}", ranges);
1170// map.update(cx, |map, cx| {
1171// map.fold(ranges, cx);
1172// });
1173// }
1174// }
1175// _ => {
1176// buffer.update(cx, |buffer, cx| buffer.randomly_mutate(&mut rng, 5, cx));
1177// }
1178// }
1179
1180// if map.read_with(cx, |map, cx| map.is_rewrapping(cx)) {
1181// notifications.next().await.unwrap();
1182// }
1183
1184// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1185// fold_count = snapshot.fold_count();
1186// log::info!("buffer text: {:?}", snapshot.buffer_snapshot.text());
1187// log::info!("fold text: {:?}", snapshot.fold_snapshot.text());
1188// log::info!("tab text: {:?}", snapshot.tab_snapshot.text());
1189// log::info!("wrap text: {:?}", snapshot.wrap_snapshot.text());
1190// log::info!("block text: {:?}", snapshot.block_snapshot.text());
1191// log::info!("display text: {:?}", snapshot.text());
1192
1193// // Line boundaries
1194// let buffer = &snapshot.buffer_snapshot;
1195// for _ in 0..5 {
1196// let row = rng.gen_range(0..=buffer.max_point().row);
1197// let column = rng.gen_range(0..=buffer.line_len(row));
1198// let point = buffer.clip_point(Point::new(row, column), Left);
1199
1200// let (prev_buffer_bound, prev_display_bound) = snapshot.prev_line_boundary(point);
1201// let (next_buffer_bound, next_display_bound) = snapshot.next_line_boundary(point);
1202
1203// assert!(prev_buffer_bound <= point);
1204// assert!(next_buffer_bound >= point);
1205// assert_eq!(prev_buffer_bound.column, 0);
1206// assert_eq!(prev_display_bound.column(), 0);
1207// if next_buffer_bound < buffer.max_point() {
1208// assert_eq!(buffer.chars_at(next_buffer_bound).next(), Some('\n'));
1209// }
1210
1211// assert_eq!(
1212// prev_display_bound,
1213// prev_buffer_bound.to_display_point(&snapshot),
1214// "row boundary before {:?}. reported buffer row boundary: {:?}",
1215// point,
1216// prev_buffer_bound
1217// );
1218// assert_eq!(
1219// next_display_bound,
1220// next_buffer_bound.to_display_point(&snapshot),
1221// "display row boundary after {:?}. reported buffer row boundary: {:?}",
1222// point,
1223// next_buffer_bound
1224// );
1225// assert_eq!(
1226// prev_buffer_bound,
1227// prev_display_bound.to_point(&snapshot),
1228// "row boundary before {:?}. reported display row boundary: {:?}",
1229// point,
1230// prev_display_bound
1231// );
1232// assert_eq!(
1233// next_buffer_bound,
1234// next_display_bound.to_point(&snapshot),
1235// "row boundary after {:?}. reported display row boundary: {:?}",
1236// point,
1237// next_display_bound
1238// );
1239// }
1240
1241// // Movement
1242// let min_point = snapshot.clip_point(DisplayPoint::new(0, 0), Left);
1243// let max_point = snapshot.clip_point(snapshot.max_point(), Right);
1244// for _ in 0..5 {
1245// let row = rng.gen_range(0..=snapshot.max_point().row());
1246// let column = rng.gen_range(0..=snapshot.line_len(row));
1247// let point = snapshot.clip_point(DisplayPoint::new(row, column), Left);
1248
1249// log::info!("Moving from point {:?}", point);
1250
1251// let moved_right = movement::right(&snapshot, point);
1252// log::info!("Right {:?}", moved_right);
1253// if point < max_point {
1254// assert!(moved_right > point);
1255// if point.column() == snapshot.line_len(point.row())
1256// || snapshot.soft_wrap_indent(point.row()).is_some()
1257// && point.column() == snapshot.line_len(point.row()) - 1
1258// {
1259// assert!(moved_right.row() > point.row());
1260// }
1261// } else {
1262// assert_eq!(moved_right, point);
1263// }
1264
1265// let moved_left = movement::left(&snapshot, point);
1266// log::info!("Left {:?}", moved_left);
1267// if point > min_point {
1268// assert!(moved_left < point);
1269// if point.column() == 0 {
1270// assert!(moved_left.row() < point.row());
1271// }
1272// } else {
1273// assert_eq!(moved_left, point);
1274// }
1275// }
1276// }
1277// }
1278
1279// #[gpui::test(retries = 5)]
1280// async fn test_soft_wraps(cx: &mut gpui::TestAppContext) {
1281// cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1282// cx.update(|cx| {
1283// init_test(cx, |_| {});
1284// });
1285
1286// let mut cx = EditorTestContext::new(cx).await;
1287// let editor = cx.editor.clone();
1288// let window = cx.window.clone();
1289
1290// cx.update_window(window, |cx| {
1291// let text_layout_details =
1292// editor.read_with(cx, |editor, cx| editor.text_layout_details(cx));
1293
1294// let font_cache = cx.font_cache().clone();
1295
1296// let family_id = font_cache
1297// .load_family(&["Helvetica"], &Default::default())
1298// .unwrap();
1299// let font_id = font_cache
1300// .select_font(family_id, &Default::default())
1301// .unwrap();
1302// let font_size = 12.0;
1303// let wrap_width = Some(64.);
1304
1305// let text = "one two three four five\nsix seven eight";
1306// let buffer = MultiBuffer::build_simple(text, cx);
1307// let map = cx.add_model(|cx| {
1308// DisplayMap::new(buffer.clone(), font_id, font_size, wrap_width, 1, 1, cx)
1309// });
1310
1311// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1312// assert_eq!(
1313// snapshot.text_chunks(0).collect::<String>(),
1314// "one two \nthree four \nfive\nsix seven \neight"
1315// );
1316// assert_eq!(
1317// snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Left),
1318// DisplayPoint::new(0, 7)
1319// );
1320// assert_eq!(
1321// snapshot.clip_point(DisplayPoint::new(0, 8), Bias::Right),
1322// DisplayPoint::new(1, 0)
1323// );
1324// assert_eq!(
1325// movement::right(&snapshot, DisplayPoint::new(0, 7)),
1326// DisplayPoint::new(1, 0)
1327// );
1328// assert_eq!(
1329// movement::left(&snapshot, DisplayPoint::new(1, 0)),
1330// DisplayPoint::new(0, 7)
1331// );
1332
1333// let x = snapshot.x_for_point(DisplayPoint::new(1, 10), &text_layout_details);
1334// assert_eq!(
1335// movement::up(
1336// &snapshot,
1337// DisplayPoint::new(1, 10),
1338// SelectionGoal::None,
1339// false,
1340// &text_layout_details,
1341// ),
1342// (
1343// DisplayPoint::new(0, 7),
1344// SelectionGoal::HorizontalPosition(x)
1345// )
1346// );
1347// assert_eq!(
1348// movement::down(
1349// &snapshot,
1350// DisplayPoint::new(0, 7),
1351// SelectionGoal::HorizontalPosition(x),
1352// false,
1353// &text_layout_details
1354// ),
1355// (
1356// DisplayPoint::new(1, 10),
1357// SelectionGoal::HorizontalPosition(x)
1358// )
1359// );
1360// assert_eq!(
1361// movement::down(
1362// &snapshot,
1363// DisplayPoint::new(1, 10),
1364// SelectionGoal::HorizontalPosition(x),
1365// false,
1366// &text_layout_details
1367// ),
1368// (
1369// DisplayPoint::new(2, 4),
1370// SelectionGoal::HorizontalPosition(x)
1371// )
1372// );
1373
1374// let ix = snapshot.buffer_snapshot.text().find("seven").unwrap();
1375// buffer.update(cx, |buffer, cx| {
1376// buffer.edit([(ix..ix, "and ")], None, cx);
1377// });
1378
1379// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1380// assert_eq!(
1381// snapshot.text_chunks(1).collect::<String>(),
1382// "three four \nfive\nsix and \nseven eight"
1383// );
1384
1385// // Re-wrap on font size changes
1386// map.update(cx, |map, cx| map.set_font_with_size(font_id, font_size + 3., cx));
1387
1388// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1389// assert_eq!(
1390// snapshot.text_chunks(1).collect::<String>(),
1391// "three \nfour five\nsix and \nseven \neight"
1392// )
1393// });
1394// }
1395
1396// #[gpui::test]
1397// fn test_text_chunks(cx: &mut gpui::AppContext) {
1398// init_test(cx, |_| {});
1399
1400// let text = sample_text(6, 6, 'a');
1401// let buffer = MultiBuffer::build_simple(&text, cx);
1402// let family_id = cx
1403// .font_cache()
1404// .load_family(&["Helvetica"], &Default::default())
1405// .unwrap();
1406// let font_id = cx
1407// .font_cache()
1408// .select_font(family_id, &Default::default())
1409// .unwrap();
1410// let font_size = 14.0;
1411// let map =
1412// cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1413
1414// buffer.update(cx, |buffer, cx| {
1415// buffer.edit(
1416// vec![
1417// (Point::new(1, 0)..Point::new(1, 0), "\t"),
1418// (Point::new(1, 1)..Point::new(1, 1), "\t"),
1419// (Point::new(2, 1)..Point::new(2, 1), "\t"),
1420// ],
1421// None,
1422// cx,
1423// )
1424// });
1425
1426// assert_eq!(
1427// map.update(cx, |map, cx| map.snapshot(cx))
1428// .text_chunks(1)
1429// .collect::<String>()
1430// .lines()
1431// .next(),
1432// Some(" b bbbbb")
1433// );
1434// assert_eq!(
1435// map.update(cx, |map, cx| map.snapshot(cx))
1436// .text_chunks(2)
1437// .collect::<String>()
1438// .lines()
1439// .next(),
1440// Some("c ccccc")
1441// );
1442// }
1443
1444// #[gpui::test]
1445// async fn test_chunks(cx: &mut gpui::TestAppContext) {
1446// use unindent::Unindent as _;
1447
1448// let text = r#"
1449// fn outer() {}
1450
1451// mod module {
1452// fn inner() {}
1453// }"#
1454// .unindent();
1455
1456// let theme = SyntaxTheme::new(vec![
1457// ("mod.body".to_string(), Hsla::red().into()),
1458// ("fn.name".to_string(), Hsla::blue().into()),
1459// ]);
1460// let language = Arc::new(
1461// Language::new(
1462// LanguageConfig {
1463// name: "Test".into(),
1464// path_suffixes: vec![".test".to_string()],
1465// ..Default::default()
1466// },
1467// Some(tree_sitter_rust::language()),
1468// )
1469// .with_highlights_query(
1470// r#"
1471// (mod_item name: (identifier) body: _ @mod.body)
1472// (function_item name: (identifier) @fn.name)
1473// "#,
1474// )
1475// .unwrap(),
1476// );
1477// language.set_theme(&theme);
1478
1479// cx.update(|cx| init_test(cx, |s| s.defaults.tab_size = Some(2.try_into().unwrap())));
1480
1481// let buffer = cx
1482// .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1483// buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1484// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1485
1486// let font_cache = cx.font_cache();
1487// let family_id = font_cache
1488// .load_family(&["Helvetica"], &Default::default())
1489// .unwrap();
1490// let font_id = font_cache
1491// .select_font(family_id, &Default::default())
1492// .unwrap();
1493// let font_size = 14.0;
1494
1495// let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1496// assert_eq!(
1497// cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1498// vec![
1499// ("fn ".to_string(), None),
1500// ("outer".to_string(), Some(Hsla::blue())),
1501// ("() {}\n\nmod module ".to_string(), None),
1502// ("{\n fn ".to_string(), Some(Hsla::red())),
1503// ("inner".to_string(), Some(Hsla::blue())),
1504// ("() {}\n}".to_string(), Some(Hsla::red())),
1505// ]
1506// );
1507// assert_eq!(
1508// cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1509// vec![
1510// (" fn ".to_string(), Some(Hsla::red())),
1511// ("inner".to_string(), Some(Hsla::blue())),
1512// ("() {}\n}".to_string(), Some(Hsla::red())),
1513// ]
1514// );
1515
1516// map.update(cx, |map, cx| {
1517// map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1518// });
1519// assert_eq!(
1520// cx.update(|cx| syntax_chunks(0..2, &map, &theme, cx)),
1521// vec![
1522// ("fn ".to_string(), None),
1523// ("out".to_string(), Some(Hsla::blue())),
1524// ("⋯".to_string(), None),
1525// (" fn ".to_string(), Some(Hsla::red())),
1526// ("inner".to_string(), Some(Hsla::blue())),
1527// ("() {}\n}".to_string(), Some(Hsla::red())),
1528// ]
1529// );
1530// }
1531
1532// #[gpui::test]
1533// async fn test_chunks_with_soft_wrapping(cx: &mut gpui::TestAppContext) {
1534// use unindent::Unindent as _;
1535
1536// cx.foreground().set_block_on_ticks(usize::MAX..=usize::MAX);
1537
1538// let text = r#"
1539// fn outer() {}
1540
1541// mod module {
1542// fn inner() {}
1543// }"#
1544// .unindent();
1545
1546// let theme = SyntaxTheme::new(vec![
1547// ("mod.body".to_string(), Hsla::red().into()),
1548// ("fn.name".to_string(), Hsla::blue().into()),
1549// ]);
1550// let language = Arc::new(
1551// Language::new(
1552// LanguageConfig {
1553// name: "Test".into(),
1554// path_suffixes: vec![".test".to_string()],
1555// ..Default::default()
1556// },
1557// Some(tree_sitter_rust::language()),
1558// )
1559// .with_highlights_query(
1560// r#"
1561// (mod_item name: (identifier) body: _ @mod.body)
1562// (function_item name: (identifier) @fn.name)
1563// "#,
1564// )
1565// .unwrap(),
1566// );
1567// language.set_theme(&theme);
1568
1569// cx.update(|cx| init_test(cx, |_| {}));
1570
1571// let buffer = cx
1572// .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1573// buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1574// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1575
1576// let font_cache = cx.font_cache();
1577
1578// let family_id = font_cache
1579// .load_family(&["Courier"], &Default::default())
1580// .unwrap();
1581// let font_id = font_cache
1582// .select_font(family_id, &Default::default())
1583// .unwrap();
1584// let font_size = 16.0;
1585
1586// let map =
1587// cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, Some(40.0), 1, 1, cx));
1588// assert_eq!(
1589// cx.update(|cx| syntax_chunks(0..5, &map, &theme, cx)),
1590// [
1591// ("fn \n".to_string(), None),
1592// ("oute\nr".to_string(), Some(Hsla::blue())),
1593// ("() \n{}\n\n".to_string(), None),
1594// ]
1595// );
1596// assert_eq!(
1597// cx.update(|cx| syntax_chunks(3..5, &map, &theme, cx)),
1598// [("{}\n\n".to_string(), None)]
1599// );
1600
1601// map.update(cx, |map, cx| {
1602// map.fold(vec![Point::new(0, 6)..Point::new(3, 2)], cx)
1603// });
1604// assert_eq!(
1605// cx.update(|cx| syntax_chunks(1..4, &map, &theme, cx)),
1606// [
1607// ("out".to_string(), Some(Hsla::blue())),
1608// ("⋯\n".to_string(), None),
1609// (" \nfn ".to_string(), Some(Hsla::red())),
1610// ("i\n".to_string(), Some(Hsla::blue()))
1611// ]
1612// );
1613// }
1614
1615// #[gpui::test]
1616// async fn test_chunks_with_text_highlights(cx: &mut gpui::TestAppContext) {
1617// cx.update(|cx| init_test(cx, |_| {}));
1618
1619// let theme = SyntaxTheme::new(vec![
1620// ("operator".to_string(), Hsla::red().into()),
1621// ("string".to_string(), Hsla::green().into()),
1622// ]);
1623// let language = Arc::new(
1624// Language::new(
1625// LanguageConfig {
1626// name: "Test".into(),
1627// path_suffixes: vec![".test".to_string()],
1628// ..Default::default()
1629// },
1630// Some(tree_sitter_rust::language()),
1631// )
1632// .with_highlights_query(
1633// r#"
1634// ":" @operator
1635// (string_literal) @string
1636// "#,
1637// )
1638// .unwrap(),
1639// );
1640// language.set_theme(&theme);
1641
1642// let (text, highlighted_ranges) = marked_text_ranges(r#"constˇ «a»: B = "c «d»""#, false);
1643
1644// let buffer = cx
1645// .add_model(|cx| Buffer::new(0, cx.model_id() as u64, text).with_language(language, cx));
1646// buffer.condition(cx, |buf, _| !buf.is_parsing()).await;
1647
1648// let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
1649// let buffer_snapshot = buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx));
1650
1651// let font_cache = cx.font_cache();
1652// let family_id = font_cache
1653// .load_family(&["Courier"], &Default::default())
1654// .unwrap();
1655// let font_id = font_cache
1656// .select_font(family_id, &Default::default())
1657// .unwrap();
1658// let font_size = 16.0;
1659// let map = cx.add_model(|cx| DisplayMap::new(buffer, font_id, font_size, None, 1, 1, cx));
1660
1661// enum MyType {}
1662
1663// let style = HighlightStyle {
1664// color: Some(Hsla::blue()),
1665// ..Default::default()
1666// };
1667
1668// map.update(cx, |map, _cx| {
1669// map.highlight_text(
1670// TypeId::of::<MyType>(),
1671// highlighted_ranges
1672// .into_iter()
1673// .map(|range| {
1674// buffer_snapshot.anchor_before(range.start)
1675// ..buffer_snapshot.anchor_before(range.end)
1676// })
1677// .collect(),
1678// style,
1679// );
1680// });
1681
1682// assert_eq!(
1683// cx.update(|cx| chunks(0..10, &map, &theme, cx)),
1684// [
1685// ("const ".to_string(), None, None),
1686// ("a".to_string(), None, Some(Hsla::blue())),
1687// (":".to_string(), Some(Hsla::red()), None),
1688// (" B = ".to_string(), None, None),
1689// ("\"c ".to_string(), Some(Hsla::green()), None),
1690// ("d".to_string(), Some(Hsla::green()), Some(Hsla::blue())),
1691// ("\"".to_string(), Some(Hsla::green()), None),
1692// ]
1693// );
1694// }
1695
1696// #[gpui::test]
1697// fn test_clip_point(cx: &mut gpui::AppContext) {
1698// init_test(cx, |_| {});
1699
1700// fn assert(text: &str, shift_right: bool, bias: Bias, cx: &mut gpui::AppContext) {
1701// let (unmarked_snapshot, mut markers) = marked_display_snapshot(text, cx);
1702
1703// match bias {
1704// Bias::Left => {
1705// if shift_right {
1706// *markers[1].column_mut() += 1;
1707// }
1708
1709// assert_eq!(unmarked_snapshot.clip_point(markers[1], bias), markers[0])
1710// }
1711// Bias::Right => {
1712// if shift_right {
1713// *markers[0].column_mut() += 1;
1714// }
1715
1716// assert_eq!(unmarked_snapshot.clip_point(markers[0], bias), markers[1])
1717// }
1718// };
1719// }
1720
1721// use Bias::{Left, Right};
1722// assert("ˇˇα", false, Left, cx);
1723// assert("ˇˇα", true, Left, cx);
1724// assert("ˇˇα", false, Right, cx);
1725// assert("ˇαˇ", true, Right, cx);
1726// assert("ˇˇ✋", false, Left, cx);
1727// assert("ˇˇ✋", true, Left, cx);
1728// assert("ˇˇ✋", false, Right, cx);
1729// assert("ˇ✋ˇ", true, Right, cx);
1730// assert("ˇˇ🍐", false, Left, cx);
1731// assert("ˇˇ🍐", true, Left, cx);
1732// assert("ˇˇ🍐", false, Right, cx);
1733// assert("ˇ🍐ˇ", true, Right, cx);
1734// assert("ˇˇ\t", false, Left, cx);
1735// assert("ˇˇ\t", true, Left, cx);
1736// assert("ˇˇ\t", false, Right, cx);
1737// assert("ˇ\tˇ", true, Right, cx);
1738// assert(" ˇˇ\t", false, Left, cx);
1739// assert(" ˇˇ\t", true, Left, cx);
1740// assert(" ˇˇ\t", false, Right, cx);
1741// assert(" ˇ\tˇ", true, Right, cx);
1742// assert(" ˇˇ\t", false, Left, cx);
1743// assert(" ˇˇ\t", false, Right, cx);
1744// }
1745
1746// #[gpui::test]
1747// fn test_clip_at_line_ends(cx: &mut gpui::AppContext) {
1748// init_test(cx, |_| {});
1749
1750// fn assert(text: &str, cx: &mut gpui::AppContext) {
1751// let (mut unmarked_snapshot, markers) = marked_display_snapshot(text, cx);
1752// unmarked_snapshot.clip_at_line_ends = true;
1753// assert_eq!(
1754// unmarked_snapshot.clip_point(markers[1], Bias::Left),
1755// markers[0]
1756// );
1757// }
1758
1759// assert("ˇˇ", cx);
1760// assert("ˇaˇ", cx);
1761// assert("aˇbˇ", cx);
1762// assert("aˇαˇ", cx);
1763// }
1764
1765// #[gpui::test]
1766// fn test_tabs_with_multibyte_chars(cx: &mut gpui::AppContext) {
1767// init_test(cx, |_| {});
1768
1769// let text = "✅\t\tα\nβ\t\n🏀β\t\tγ";
1770// let buffer = MultiBuffer::build_simple(text, cx);
1771// let font_cache = cx.font_cache();
1772// let family_id = font_cache
1773// .load_family(&["Helvetica"], &Default::default())
1774// .unwrap();
1775// let font_id = font_cache
1776// .select_font(family_id, &Default::default())
1777// .unwrap();
1778// let font_size = 14.0;
1779
1780// let map =
1781// cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1782// let map = map.update(cx, |map, cx| map.snapshot(cx));
1783// assert_eq!(map.text(), "✅ α\nβ \n🏀β γ");
1784// assert_eq!(
1785// map.text_chunks(0).collect::<String>(),
1786// "✅ α\nβ \n🏀β γ"
1787// );
1788// assert_eq!(map.text_chunks(1).collect::<String>(), "β \n🏀β γ");
1789// assert_eq!(map.text_chunks(2).collect::<String>(), "🏀β γ");
1790
1791// let point = Point::new(0, "✅\t\t".len() as u32);
1792// let display_point = DisplayPoint::new(0, "✅ ".len() as u32);
1793// assert_eq!(point.to_display_point(&map), display_point);
1794// assert_eq!(display_point.to_point(&map), point);
1795
1796// let point = Point::new(1, "β\t".len() as u32);
1797// let display_point = DisplayPoint::new(1, "β ".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(2, "🏀β\t\t".len() as u32);
1802// let display_point = DisplayPoint::new(2, "🏀β ".len() as u32);
1803// assert_eq!(point.to_display_point(&map), display_point);
1804// assert_eq!(display_point.to_point(&map), point,);
1805
1806// // Display points inside of expanded tabs
1807// assert_eq!(
1808// DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1809// Point::new(0, "✅\t".len() as u32),
1810// );
1811// assert_eq!(
1812// DisplayPoint::new(0, "✅ ".len() as u32).to_point(&map),
1813// Point::new(0, "✅".len() as u32),
1814// );
1815
1816// // Clipping display points inside of multi-byte characters
1817// assert_eq!(
1818// map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Left),
1819// DisplayPoint::new(0, 0)
1820// );
1821// assert_eq!(
1822// map.clip_point(DisplayPoint::new(0, "✅".len() as u32 - 1), Bias::Right),
1823// DisplayPoint::new(0, "✅".len() as u32)
1824// );
1825// }
1826
1827// #[gpui::test]
1828// fn test_max_point(cx: &mut gpui::AppContext) {
1829// init_test(cx, |_| {});
1830
1831// let buffer = MultiBuffer::build_simple("aaa\n\t\tbbb", cx);
1832// let font_cache = cx.font_cache();
1833// let family_id = font_cache
1834// .load_family(&["Helvetica"], &Default::default())
1835// .unwrap();
1836// let font_id = font_cache
1837// .select_font(family_id, &Default::default())
1838// .unwrap();
1839// let font_size = 14.0;
1840// let map =
1841// cx.add_model(|cx| DisplayMap::new(buffer.clone(), font_id, font_size, None, 1, 1, cx));
1842// assert_eq!(
1843// map.update(cx, |map, cx| map.snapshot(cx)).max_point(),
1844// DisplayPoint::new(1, 11)
1845// )
1846// }
1847
1848// fn syntax_chunks<'a>(
1849// rows: Range<u32>,
1850// map: &Model<DisplayMap>,
1851// theme: &'a SyntaxTheme,
1852// cx: &mut AppContext,
1853// ) -> Vec<(String, Option<Hsla>)> {
1854// chunks(rows, map, theme, cx)
1855// .into_iter()
1856// .map(|(text, color, _)| (text, color))
1857// .collect()
1858// }
1859
1860// fn chunks<'a>(
1861// rows: Range<u32>,
1862// map: &Model<DisplayMap>,
1863// theme: &'a SyntaxTheme,
1864// cx: &mut AppContext,
1865// ) -> Vec<(String, Option<Hsla>, Option<Hsla>)> {
1866// let snapshot = map.update(cx, |map, cx| map.snapshot(cx));
1867// let mut chunks: Vec<(String, Option<Hsla>, Option<Hsla>)> = Vec::new();
1868// for chunk in snapshot.chunks(rows, true, None, None) {
1869// let syntax_color = chunk
1870// .syntax_highlight_id
1871// .and_then(|id| id.style(theme)?.color);
1872// let highlight_color = chunk.highlight_style.and_then(|style| style.color);
1873// if let Some((last_chunk, last_syntax_color, last_highlight_color)) = chunks.last_mut() {
1874// if syntax_color == *last_syntax_color && highlight_color == *last_highlight_color {
1875// last_chunk.push_str(chunk.text);
1876// continue;
1877// }
1878// }
1879// chunks.push((chunk.text.to_string(), syntax_color, highlight_color));
1880// }
1881// chunks
1882// }
1883
1884// fn init_test(cx: &mut AppContext, f: impl Fn(&mut AllLanguageSettingsContent)) {
1885// cx.foreground().forbid_parking();
1886// cx.set_global(SettingsStore::test(cx));
1887// language::init(cx);
1888// crate::init(cx);
1889// Project::init_settings(cx);
1890// theme::init((), cx);
1891// cx.update_global::<SettingsStore, _, _>(|store, cx| {
1892// store.update_user_settings::<AllLanguageSettings>(cx, f);
1893// });
1894// }
1895// }