Skip to main content

gpui_base/input/editor/display_map/
display_map.rs

1/// DisplayMap: Public facade for Editor/Input display mapping.
2///
3/// This combines WrapMap, FoldMap and SpacerMap to provide a unified API:
4/// - BufferPoint ↔ DisplayPoint conversion
5/// - Fold management (candidates, toggle, query)
6/// - Automatic projection updates on text/layout changes
7use std::ops::Range;
8
9use gpui::{App, Font, Pixels};
10use ropey::Rope;
11
12use super::fold_map::FoldMap;
13use super::folding::FoldRange;
14use super::spacer_map::{DisplayRow, SpacerMap};
15pub use super::text_wrapper::WrappingIndent;
16use super::text_wrapper::{FontSpan, LineItem, WrapDisplayPoint};
17use super::wrap_map::WrapMap;
18use super::{BufferPoint, DisplayPoint};
19use crate::input::Point as TreeSitterPoint;
20use crate::input::Spacer;
21use crate::input::display_map::WrapPoint;
22use crate::input::rope_ext::RopeExt as _;
23
24/// DisplayMap is the main interface for Editor/Input coordinate mapping.
25///
26/// It manages the three-layer projection:
27/// 1. Buffer → Wrap (soft-wrapping)
28/// 2. Wrap → Fold (folding)
29/// 3. Fold → Display (spacers)
30///
31/// [`crate::input::InputBaseState::display_map`] exposes the editor-owned map
32/// through a shared reference for application coordinate queries. Text edits,
33/// wrapping, and folding remain owned by the editor state.
34///
35/// Coordinates describe the prepared text projection, including offscreen
36/// lines. They exclude inline completion ghost lines and other painted geometry.
37pub struct DisplayMap {
38    wrap_map: WrapMap,
39    fold_map: FoldMap,
40    spacer_map: SpacerMap,
41    /// The spacers as they were last set, before projection.
42    spacers: Vec<Spacer>,
43    /// The rows version the spacers were last projected at, `None` when they
44    /// must be projected again.
45    spacers_projected: Option<usize>,
46    /// Counts the changes of the spacers, so that [`Self::version`] moves with
47    /// them.
48    spacers_version: usize,
49}
50
51impl DisplayMap {
52    pub fn new(font: Font, font_size: Pixels, wrap_width: Option<Pixels>) -> Self {
53        Self {
54            wrap_map: WrapMap::new(font, font_size, wrap_width),
55            fold_map: FoldMap::new(),
56            spacer_map: SpacerMap::default(),
57            spacers: Vec::new(),
58            spacers_projected: None,
59            spacers_version: 0,
60        }
61    }
62
63    // ==================== Core Coordinate Mapping ====================
64
65    /// Convert buffer position to display position
66    pub fn buffer_pos_to_display_pos(&self, pos: BufferPoint) -> DisplayPoint {
67        // Buffer → Wrap
68        let wrap_pos = self.wrap_map.buffer_pos_to_wrap_pos(pos);
69
70        // Wrap → Fold → Display
71        if let Some(fold_row) = self.fold_map.wrap_row_to_display_row(wrap_pos.row) {
72            DisplayPoint::new(
73                self.spacer_map.fold_row_to_display_row(fold_row),
74                wrap_pos.col,
75            )
76        } else {
77            // Cursor is in a folded region, find nearest visible row
78            let display_row = self.nearest_visible_display_row(wrap_pos.row);
79            DisplayPoint::new(display_row, 0) // Column 0 at fold boundary
80        }
81    }
82
83    /// Convert display position to buffer position
84    ///
85    /// A spacer row is read as the nearest row of the line it stands beside.
86    pub fn display_pos_to_buffer_pos(&self, pos: DisplayPoint) -> BufferPoint {
87        // Display → Fold → Wrap
88        let wrap_row = self
89            .fold_map
90            .display_row_to_wrap_row(self.text_fold_row(pos.row))
91            .unwrap_or(0);
92
93        // Wrap → Buffer
94        let wrap_pos = WrapPoint::new(wrap_row, pos.col);
95        self.wrap_map.wrap_pos_to_buffer_pos(wrap_pos)
96    }
97
98    /// A number that changes whenever a buffer line may have taken different
99    /// display rows: an edit, a rewrap, a change of folds or of spacers.
100    ///
101    /// Compare versions for equality on the same map to invalidate cached
102    /// queries. The counter can wrap; it is not a document revision or a count
103    /// of edits. Scrolling and inline completion ghost lines do not change it,
104    /// nor does a [`crate::input::SpacerProvider`] answering with the spacers
105    /// already shown.
106    #[inline]
107    pub fn version(&self) -> usize {
108        self.rows_version().wrapping_add(self.spacers_version)
109    }
110
111    /// Like [`Self::version`], without the spacers: what the spacers are
112    /// placed by and asked for again at, so that an answer does not ask anew.
113    #[inline]
114    pub(crate) fn rows_version(&self) -> usize {
115        self.wrap_map
116            .wrapper()
117            .version()
118            .wrapping_add(self.fold_map.version())
119    }
120
121    /// Get total number of visible display rows, spacer rows included
122    #[inline]
123    pub fn display_row_count(&self) -> usize {
124        self.fold_map.display_row_count() + self.spacer_map.row_count()
125    }
126
127    /// Get the buffer line for a given display row
128    ///
129    /// A spacer row belongs to the line it stands beside.
130    pub fn display_row_to_buffer_line(&self, display_row: usize) -> usize {
131        let fold_row = match self.spacer_map.display_row(display_row) {
132            DisplayRow::Text(fold_row) => fold_row,
133            DisplayRow::Spacer(index) => return self.spacer_map.run(index).line,
134        };
135
136        // Fold → Wrap
137        let wrap_row = self.fold_map.display_row_to_wrap_row(fold_row).unwrap_or(0);
138
139        // Wrap → Buffer line
140        self.wrap_map.wrap_row_to_buffer_line(wrap_row)
141    }
142
143    /// Get the display row range for a buffer line: [start, end)
144    /// Returns None if the buffer line is completely hidden
145    ///
146    /// The range holds the rows of the line's text, not its spacers.
147    pub fn buffer_line_to_display_row_range(&self, line: usize) -> Option<Range<usize>> {
148        let rows = self.fold_row_range(line)?;
149        Some(
150            self.spacer_map.fold_row_to_display_row(rows.start)
151                ..self.spacer_map.fold_row_to_display_row(rows.end - 1) + 1,
152        )
153    }
154
155    /// The fold rows of a buffer line: [start, end)
156    /// Returns None if the buffer line is completely hidden
157    fn fold_row_range(&self, line: usize) -> Option<Range<usize>> {
158        // Buffer line → Wrap row range
159        let wrap_row_range = self.wrap_map.buffer_line_to_wrap_row_range(line);
160
161        // Find first and last visible display rows in this range
162        let mut first_display_row = None;
163        let mut last_display_row = None;
164
165        for wrap_row in wrap_row_range {
166            if let Some(display_row) = self.fold_map.wrap_row_to_display_row(wrap_row) {
167                if first_display_row.is_none() {
168                    first_display_row = Some(display_row);
169                }
170                last_display_row = Some(display_row);
171            }
172        }
173
174        if let (Some(start), Some(end)) = (first_display_row, last_display_row) {
175            Some(start..end + 1)
176        } else {
177            None // Completely folded
178        }
179    }
180
181    /// Check if a buffer line is completely hidden
182    #[inline]
183    pub fn is_buffer_line_hidden(&self, line: usize) -> bool {
184        self.buffer_line_to_display_row_range(line).is_none()
185    }
186
187    /// First display row of a buffer line. If the line is fully folded, returns the
188    /// nearest visible display row.
189    pub fn buffer_line_to_display_row(&self, line: usize) -> usize {
190        match self.buffer_line_to_display_row_range(line) {
191            Some(range) => range.start,
192            None => {
193                let wrap_row = self.wrap_map.buffer_line_to_first_wrap_row(line);
194                self.nearest_visible_display_row(wrap_row)
195            }
196        }
197    }
198
199    // ==================== Spacers ====================
200
201    /// Replace the spacers. They are placed again whenever the rows move.
202    pub(crate) fn set_spacers(&mut self, spacers: Vec<Spacer>) {
203        if spacers == self.spacers {
204            return;
205        }
206        self.spacers = spacers;
207        self.spacers_version = self.spacers_version.wrapping_add(1);
208        self.spacers_projected = None;
209        self.project_spacers();
210    }
211
212    /// How many spacer rows there are, beside lines not hidden by a fold.
213    #[inline]
214    pub(crate) fn spacer_row_count(&self) -> usize {
215        self.spacer_map.row_count()
216    }
217
218    /// Whether a display row is a spacer row: a blank row that holds no text,
219    /// standing above or below a line. See [`Spacer`].
220    pub fn is_spacer_row(&self, display_row: usize) -> bool {
221        matches!(
222            self.spacer_map.display_row(display_row),
223            DisplayRow::Spacer(_)
224        )
225    }
226
227    /// How many spacer rows stand above and below a buffer line.
228    pub(crate) fn spacer_rows_beside(&self, line: usize) -> (usize, usize) {
229        self.spacer_map.rows_beside(line)
230    }
231
232    /// The spacer rows that have a background, beside the buffer lines within
233    /// `lines`: the display rows they take, and the color.
234    pub(crate) fn spacer_backgrounds(
235        &self,
236        lines: Range<usize>,
237    ) -> impl Iterator<Item = (Range<usize>, gpui::Hsla)> + '_ {
238        self.spacer_map
239            .runs_beside(lines)
240            .filter_map(|(start, run)| Some((start..start + run.rows, run.background?)))
241    }
242
243    /// The display row of text nearest a display row: the row itself when it
244    /// holds text, else the first one past its spacers in the direction of
245    /// `forward`, or the other way when there is none that way.
246    pub(crate) fn text_display_row(&self, display_row: usize, forward: bool) -> usize {
247        let row = display_row.min(self.display_row_count().saturating_sub(1));
248        let DisplayRow::Spacer(index) = self.spacer_map.display_row(row) else {
249            return row;
250        };
251        let before = self.spacer_map.run(index).before;
252        let fold_row = if forward && before < self.fold_map.display_row_count() {
253            before
254        } else {
255            before.saturating_sub(1)
256        };
257        self.spacer_map.fold_row_to_display_row(fold_row)
258    }
259
260    /// The fold row a display row stands for: its own, or for a spacer row the
261    /// nearest row of the line it stands beside.
262    fn text_fold_row(&self, display_row: usize) -> usize {
263        match self.spacer_map.display_row(display_row) {
264            DisplayRow::Text(fold_row) => fold_row,
265            DisplayRow::Spacer(index) => {
266                let run = self.spacer_map.run(index);
267                if run.above {
268                    run.before
269                } else {
270                    run.before.saturating_sub(1)
271                }
272            }
273        }
274    }
275
276    /// Place the spacers again if the rows moved since they were last placed.
277    fn project_spacers(&mut self) {
278        if self.spacers.is_empty() && self.spacer_map.row_count() == 0 {
279            return;
280        }
281        let version = self.rows_version();
282        if self.spacers_projected == Some(version) {
283            return;
284        }
285        self.spacers_projected = Some(version);
286        let line_count = self.buffer_line_count();
287        let mut map = std::mem::take(&mut self.spacer_map);
288        map.rebuild(&self.spacers, |line| {
289            (line < line_count)
290                .then(|| self.fold_row_range(line))
291                .flatten()
292        });
293        self.spacer_map = map;
294    }
295
296    /// Set fold candidates (from tree-sitter/LSP)
297    pub fn set_fold_candidates(&mut self, candidates: Vec<FoldRange>) {
298        self.fold_map.set_candidates(candidates);
299        self.rebuild_fold_projection();
300    }
301
302    /// Set a fold at the given start_line (must be in candidates)
303    pub fn set_folded(&mut self, start_line: usize, folded: bool) {
304        self.fold_map.set_folded(start_line, folded);
305        self.rebuild_fold_projection();
306    }
307
308    /// Toggle fold at the given start_line
309    pub fn toggle_fold(&mut self, start_line: usize) {
310        self.fold_map.toggle_fold(start_line);
311        self.rebuild_fold_projection();
312    }
313
314    /// Check if a line is currently folded
315    #[inline]
316    pub fn is_folded_at(&self, start_line: usize) -> bool {
317        self.fold_map.is_folded_at(start_line)
318    }
319
320    /// Check if a line is a fold candidate
321    #[inline]
322    pub fn is_fold_candidate(&self, start_line: usize) -> bool {
323        self.fold_map.is_fold_candidate(start_line)
324    }
325
326    /// Get all currently folded ranges
327    #[inline]
328    pub fn folded_ranges(&self) -> &[FoldRange] {
329        self.fold_map.folded_ranges()
330    }
331
332    /// Clear all folds
333    pub fn clear_folds(&mut self) {
334        self.fold_map.clear_folds();
335        self.rebuild_fold_projection();
336    }
337
338    /// Get all fold candidates (the ranges that can be folded)
339    #[inline]
340    pub(crate) fn fold_candidates(&self) -> &[FoldRange] {
341        self.fold_map.fold_candidates()
342    }
343
344    /// Replace the folded ranges: fold each candidate starting at one of
345    /// `start_lines` and unfold all others. Lines that are not candidates are
346    /// ignored. The fold projection is rebuilt once.
347    pub(crate) fn set_folded_lines(&mut self, start_lines: impl IntoIterator<Item = usize>) {
348        self.fold_map.clear_folds();
349        for line in start_lines {
350            self.fold_map.set_folded(line, true);
351        }
352        self.rebuild_fold_projection();
353    }
354
355    // ==================== Text and Layout Updates ====================
356
357    /// Adjust folds and candidates for a text edit before updating the wrap map.
358    ///
359    /// Must be called with the OLD text (before replacement) and the edit range/new_text
360    /// so we can compute which old lines were affected.
361    pub fn adjust_folds_for_edit(&mut self, old_text: &Rope, range: &Range<usize>, new_text: &str) {
362        if self.fold_map.folded_ranges().is_empty() && self.fold_map.fold_candidates().is_empty() {
363            return;
364        }
365
366        let edit_start_line = old_text.offset_to_point(range.start).row;
367        let edit_end_line = old_text.offset_to_point(range.end.min(old_text.len())).row;
368
369        let old_lines_in_range = edit_end_line.saturating_sub(edit_start_line);
370        let new_lines_in_range = new_text.chars().filter(|c| *c == '\n').count();
371        let line_delta = new_lines_in_range as isize - old_lines_in_range as isize;
372
373        self.fold_map
374            .adjust_folds_for_edit(edit_start_line, edit_end_line, line_delta);
375    }
376
377    /// Incrementally update fold candidates after a text edit.
378    ///
379    /// Extracts new fold candidates on the lines of the edited byte range
380    /// and merges them with existing (already adjusted) candidates.
381    pub fn update_fold_candidates_for_edit(
382        &mut self,
383        extract_fold_ranges: impl FnOnce(Range<usize>, &Rope) -> Vec<FoldRange>,
384        edit_byte_range: Range<usize>,
385        new_text: &Rope,
386    ) {
387        let new_start_line = new_text.offset_to_point(edit_byte_range.start).row;
388        let new_end_line = new_text
389            .offset_to_point(edit_byte_range.end.min(new_text.len()))
390            .row;
391
392        let new_candidates = extract_fold_ranges(edit_byte_range, new_text);
393        self.fold_map
394            .merge_candidates_for_edit(new_start_line, new_end_line, new_candidates);
395    }
396
397    /// Update text (incremental or full)
398    pub fn on_text_changed(
399        &mut self,
400        changed_text: &Rope,
401        range: &Range<usize>,
402        new_text: &Rope,
403        cx: &mut App,
404    ) {
405        self.wrap_map
406            .on_text_changed(changed_text, range, new_text, cx);
407        self.rebuild_fold_projection();
408    }
409
410    /// Update layout parameters (wrap width or font)
411    pub(crate) fn set_inline_metrics(
412        &mut self,
413        metrics: std::rc::Rc<[(std::ops::Range<usize>, Pixels)]>,
414        cx: &mut App,
415    ) {
416        self.wrap_map.set_inline_metrics(metrics, cx);
417        self.rebuild_fold_projection();
418    }
419
420    /// Set the ranges drawn in another weight or style than the font, sorted and disjoint,
421    /// so soft wrap measures them as drawn.
422    pub(crate) fn set_font_spans(&mut self, spans: std::rc::Rc<[FontSpan]>, cx: &mut App) {
423        self.wrap_map.set_font_spans(spans, cx);
424        self.rebuild_fold_projection();
425    }
426
427    pub fn on_layout_changed(&mut self, wrap_width: Option<Pixels>, cx: &mut App) {
428        self.wrap_map.on_layout_changed(wrap_width, cx);
429        self.rebuild_fold_projection();
430    }
431
432    /// Set the wrapping indent for continuation lines.
433    pub fn set_wrapping_indent(&mut self, wrapping_indent: WrappingIndent, cx: &mut App) {
434        self.wrap_map.set_wrapping_indent(wrapping_indent, cx);
435        self.rebuild_fold_projection();
436    }
437
438    /// Set the number of spaces per tab stop.
439    pub(crate) fn set_tab_size(&mut self, tab_size: usize, cx: &mut App) {
440        if self.wrap_map.set_tab_size(tab_size, cx) {
441            self.rebuild_fold_projection();
442        }
443    }
444
445    /// The width text is wrapped at, or `None` when it is not wrapped.
446    pub(crate) fn wrap_width(&self) -> Option<Pixels> {
447        self.wrap_map.wrapper().wrap_width()
448    }
449
450    /// Wrap the next replacement of the whole text at `wrap_width`, leaving the current rows as
451    /// they are. Only valid right before such a replacement, which rewraps every line.
452    pub(crate) fn prepare_wrap_width(&mut self, wrap_width: Pixels) {
453        self.wrap_map.prepare_wrap_width(wrap_width);
454    }
455
456    /// The font and size text is measured in.
457    pub(crate) fn font(&self) -> (&Font, Pixels) {
458        self.wrap_map.wrapper().font()
459    }
460
461    /// Set font parameters
462    pub fn set_font(&mut self, font: Font, font_size: Pixels, cx: &mut App) {
463        self.wrap_map.set_font(font, font_size, cx);
464        self.rebuild_fold_projection();
465    }
466
467    /// Ensure text is prepared (initializes wrapper if needed)
468    pub fn ensure_text_prepared(&mut self, text: &Rope, cx: &mut App) {
469        let did_initialize = self.wrap_map.ensure_text_prepared(text, cx);
470        if did_initialize {
471            self.rebuild_fold_projection();
472        }
473    }
474
475    /// Initialize with text
476    pub fn set_text(&mut self, text: &Rope, cx: &mut App) {
477        self.wrap_map.set_text(text, cx);
478        self.rebuild_fold_projection();
479    }
480
481    // ==================== Internal Helpers ====================
482
483    /// Rebuild fold projection after wrap_map or fold state changes
484    /// Only rebuilds if there are actually folded ranges
485    fn rebuild_fold_projection(&mut self) {
486        if !self.fold_map.folded_ranges().is_empty() {
487            self.fold_map.rebuild(&self.wrap_map);
488        } else {
489            // No active folds: identity mapping (wrap_row == display_row).
490            // Just update cached count so query methods work without Vec allocation.
491            self.fold_map
492                .mark_dirty_with_wrap_count(self.wrap_map.wrap_row_count());
493        }
494        self.project_spacers();
495    }
496
497    // ==================== Wrap Display Point Operations ====================
498
499    /// Convert byte offset to wrap display point (with soft wrap info).
500    #[inline]
501    pub(crate) fn offset_to_wrap_display_point(&self, offset: usize) -> WrapDisplayPoint {
502        self.wrap_map.wrapper().offset_to_display_point(offset)
503    }
504
505    /// Like [`Self::offset_to_wrap_display_point`], but honours the caret's line-end affinity so
506    /// an offset on a soft wrap boundary resolves to the row the caret is drawn on.
507    #[inline]
508    pub(crate) fn offset_to_wrap_display_point_with_affinity(
509        &self,
510        offset: usize,
511        line_end_affinity: bool,
512    ) -> WrapDisplayPoint {
513        self.wrap_map
514            .wrapper()
515            .offset_to_display_point_with_affinity(offset, line_end_affinity)
516    }
517
518    /// Resolve the caret's visual row through both wrapping and folded regions.
519    pub(crate) fn offset_to_display_row(&self, offset: usize, line_end_affinity: bool) -> usize {
520        let point = self.offset_to_wrap_display_point_with_affinity(offset, line_end_affinity);
521        self.wrap_row_to_display_row(point.row)
522            .unwrap_or_else(|| self.nearest_visible_display_row(point.row))
523    }
524
525    /// Convert wrap display point to byte offset.
526    #[inline]
527    pub(crate) fn wrap_display_point_to_offset(&self, point: WrapDisplayPoint) -> usize {
528        self.wrap_map.wrapper().display_point_to_offset(point)
529    }
530
531    /// Convert wrap display point to TreeSitterPoint (buffer line/col).
532    #[inline]
533    pub(crate) fn wrap_display_point_to_point(&self, point: WrapDisplayPoint) -> TreeSitterPoint {
534        self.wrap_map.wrapper().display_point_to_point(point)
535    }
536
537    /// Convert a wrap row to a display row (skipping folded rows).
538    /// Returns None if the wrap row is folded.
539    #[inline]
540    pub fn wrap_row_to_display_row(&self, wrap_row: usize) -> Option<usize> {
541        self.fold_map
542            .wrap_row_to_display_row(wrap_row)
543            .map(|fold_row| self.spacer_map.fold_row_to_display_row(fold_row))
544    }
545
546    /// Find the nearest visible display row for a given wrap row.
547    #[inline]
548    pub fn nearest_visible_display_row(&self, wrap_row: usize) -> usize {
549        self.spacer_map
550            .fold_row_to_display_row(self.fold_map.nearest_visible_display_row(wrap_row))
551    }
552
553    /// Convert a display row to a wrap row.
554    /// Returns None for a spacer row.
555    #[inline]
556    pub fn display_row_to_wrap_row(&self, display_row: usize) -> Option<usize> {
557        match self.spacer_map.display_row(display_row) {
558            DisplayRow::Text(fold_row) => self.fold_map.display_row_to_wrap_row(fold_row),
559            DisplayRow::Spacer(_) => None,
560        }
561    }
562
563    pub(crate) fn display_row_column_to_offset(&self, display_row: usize, column: usize) -> usize {
564        let wrap_row = self
565            .fold_map
566            .display_row_to_wrap_row(self.text_fold_row(display_row))
567            .unwrap_or(0);
568        self.wrap_map
569            .wrapper()
570            .display_point_to_offset(WrapDisplayPoint::new(wrap_row, 0, column))
571    }
572
573    /// Get the longest row index (by byte length).
574    #[inline]
575    pub(crate) fn longest_row(&self) -> usize {
576        self.wrap_map.wrapper().longest_row()
577    }
578
579    // ==================== Access Methods ====================
580
581    /// Get the line item by buffer row index.
582    #[inline]
583    pub(crate) fn line(&self, row: usize) -> Option<&LineItem> {
584        self.wrap_map.line(row)
585    }
586
587    /// Get the rope text
588    #[inline]
589    pub fn text(&self) -> &Rope {
590        self.wrap_map.text()
591    }
592
593    /// Calculate how many wrap rows of a buffer line are visible (not folded)
594    #[inline]
595    pub fn visible_wrap_row_count_for_buffer_line(&self, line: usize) -> usize {
596        self.wrap_map
597            .visible_wrap_row_count_for_line(line, &self.fold_map)
598    }
599
600    /// Get the wrap row count (before folding)
601    #[inline]
602    pub fn wrap_row_count(&self) -> usize {
603        self.wrap_map.wrap_row_count()
604    }
605
606    /// Get the buffer line count (logical lines)
607    #[inline]
608    pub fn buffer_line_count(&self) -> usize {
609        self.wrap_map.buffer_line_count()
610    }
611}