element.rs

   1use crate::{
   2    blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
   3    code_context_menus::CodeActionsMenu,
   4    display_map::{
   5        Block, BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint,
   6    },
   7    editor_settings::{
   8        CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ScrollBeyondLastLine,
   9        ShowScrollbar,
  10    },
  11    git::blame::{CommitDetails, GitBlame},
  12    hover_popover::{
  13        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  14    },
  15    hunk_diff::{diff_hunk_to_display, DisplayDiffHunk},
  16    hunk_status,
  17    items::BufferSearchHighlights,
  18    mouse_context_menu::{self, MenuPosition, MouseContextMenu},
  19    scroll::scroll_amount::ScrollAmount,
  20    BlockId, ChunkReplacement, CursorShape, CustomBlockId, DisplayPoint, DisplayRow,
  21    DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode, EditorSettings,
  22    EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GutterDimensions, HalfPageDown,
  23    HalfPageUp, HandleInput, HoveredCursor, HoveredHunk, InlineCompletion, JumpData, LineDown,
  24    LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase, Selection,
  25    SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, FILE_HEADER_HEIGHT,
  26    GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
  27};
  28use client::ParticipantIndex;
  29use collections::{BTreeMap, HashMap, HashSet};
  30use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
  31use gpui::{
  32    anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
  33    transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
  34    ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
  35    FontId, GlobalElementId, HighlightStyle, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
  36    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
  37    ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
  38    StatefulInteractiveElement, Style, Styled, TextRun, TextStyleRefinement, View, ViewContext,
  39    WeakView, WindowContext,
  40};
  41use gpui::{ClickEvent, Subscription};
  42use itertools::Itertools;
  43use language::{
  44    language_settings::{
  45        IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings,
  46        ShowWhitespaceSetting,
  47    },
  48    ChunkRendererContext,
  49};
  50use lsp::DiagnosticSeverity;
  51use multi_buffer::{
  52    Anchor, AnchorRangeExt, ExcerptId, ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow,
  53    MultiBufferSnapshot, ToOffset,
  54};
  55use project::{
  56    project_settings::{GitGutterSetting, ProjectSettings},
  57    ProjectPath,
  58};
  59use settings::Settings;
  60use smallvec::{smallvec, SmallVec};
  61use std::{
  62    any::TypeId,
  63    borrow::Cow,
  64    cmp::{self, Ordering},
  65    fmt::{self, Write},
  66    iter, mem,
  67    ops::{Deref, Range},
  68    rc::Rc,
  69    sync::Arc,
  70};
  71use sum_tree::Bias;
  72use theme::{ActiveTheme, Appearance, PlayerColor};
  73use ui::prelude::*;
  74use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
  75use unicode_segmentation::UnicodeSegmentation;
  76use util::RangeExt;
  77use util::ResultExt;
  78use workspace::{item::Item, Workspace};
  79
  80struct SelectionLayout {
  81    head: DisplayPoint,
  82    cursor_shape: CursorShape,
  83    is_newest: bool,
  84    is_local: bool,
  85    range: Range<DisplayPoint>,
  86    active_rows: Range<DisplayRow>,
  87    user_name: Option<SharedString>,
  88}
  89
  90impl SelectionLayout {
  91    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  92        selection: Selection<T>,
  93        line_mode: bool,
  94        cursor_shape: CursorShape,
  95        map: &DisplaySnapshot,
  96        is_newest: bool,
  97        is_local: bool,
  98        user_name: Option<SharedString>,
  99    ) -> Self {
 100        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
 101        let display_selection = point_selection.map(|p| p.to_display_point(map));
 102        let mut range = display_selection.range();
 103        let mut head = display_selection.head();
 104        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
 105            ..map.next_line_boundary(point_selection.end).1.row();
 106
 107        // vim visual line mode
 108        if line_mode {
 109            let point_range = map.expand_to_line(point_selection.range());
 110            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
 111        }
 112
 113        // any vim visual mode (including line mode)
 114        if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
 115            && !range.is_empty()
 116            && !selection.reversed
 117        {
 118            if head.column() > 0 {
 119                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
 120            } else if head.row().0 > 0 && head != map.max_point() {
 121                head = map.clip_point(
 122                    DisplayPoint::new(
 123                        head.row().previous_row(),
 124                        map.line_len(head.row().previous_row()),
 125                    ),
 126                    Bias::Left,
 127                );
 128                // updating range.end is a no-op unless you're cursor is
 129                // on the newline containing a multi-buffer divider
 130                // in which case the clip_point may have moved the head up
 131                // an additional row.
 132                range.end = DisplayPoint::new(head.row().next_row(), 0);
 133                active_rows.end = head.row();
 134            }
 135        }
 136
 137        Self {
 138            head,
 139            cursor_shape,
 140            is_newest,
 141            is_local,
 142            range,
 143            active_rows,
 144            user_name,
 145        }
 146    }
 147}
 148
 149pub struct EditorElement {
 150    editor: View<Editor>,
 151    style: EditorStyle,
 152}
 153
 154type DisplayRowDelta = u32;
 155
 156impl EditorElement {
 157    pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
 158
 159    pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
 160        Self {
 161            editor: editor.clone(),
 162            style,
 163        }
 164    }
 165
 166    fn register_actions(&self, cx: &mut WindowContext) {
 167        let view = &self.editor;
 168        view.update(cx, |editor, cx| {
 169            for action in editor.editor_actions.borrow().values() {
 170                (action)(cx)
 171            }
 172        });
 173
 174        crate::rust_analyzer_ext::apply_related_actions(view, cx);
 175        crate::clangd_ext::apply_related_actions(view, cx);
 176        register_action(view, cx, Editor::open_context_menu);
 177        register_action(view, cx, Editor::move_left);
 178        register_action(view, cx, Editor::move_right);
 179        register_action(view, cx, Editor::move_down);
 180        register_action(view, cx, Editor::move_down_by_lines);
 181        register_action(view, cx, Editor::select_down_by_lines);
 182        register_action(view, cx, Editor::move_up);
 183        register_action(view, cx, Editor::move_up_by_lines);
 184        register_action(view, cx, Editor::select_up_by_lines);
 185        register_action(view, cx, Editor::select_page_down);
 186        register_action(view, cx, Editor::select_page_up);
 187        register_action(view, cx, Editor::cancel);
 188        register_action(view, cx, Editor::newline);
 189        register_action(view, cx, Editor::newline_above);
 190        register_action(view, cx, Editor::newline_below);
 191        register_action(view, cx, Editor::backspace);
 192        register_action(view, cx, Editor::delete);
 193        register_action(view, cx, Editor::tab);
 194        register_action(view, cx, Editor::tab_prev);
 195        register_action(view, cx, Editor::indent);
 196        register_action(view, cx, Editor::outdent);
 197        register_action(view, cx, Editor::autoindent);
 198        register_action(view, cx, Editor::delete_line);
 199        register_action(view, cx, Editor::join_lines);
 200        register_action(view, cx, Editor::sort_lines_case_sensitive);
 201        register_action(view, cx, Editor::sort_lines_case_insensitive);
 202        register_action(view, cx, Editor::reverse_lines);
 203        register_action(view, cx, Editor::shuffle_lines);
 204        register_action(view, cx, Editor::convert_to_upper_case);
 205        register_action(view, cx, Editor::convert_to_lower_case);
 206        register_action(view, cx, Editor::convert_to_title_case);
 207        register_action(view, cx, Editor::convert_to_snake_case);
 208        register_action(view, cx, Editor::convert_to_kebab_case);
 209        register_action(view, cx, Editor::convert_to_upper_camel_case);
 210        register_action(view, cx, Editor::convert_to_lower_camel_case);
 211        register_action(view, cx, Editor::convert_to_opposite_case);
 212        register_action(view, cx, Editor::delete_to_previous_word_start);
 213        register_action(view, cx, Editor::delete_to_previous_subword_start);
 214        register_action(view, cx, Editor::delete_to_next_word_end);
 215        register_action(view, cx, Editor::delete_to_next_subword_end);
 216        register_action(view, cx, Editor::delete_to_beginning_of_line);
 217        register_action(view, cx, Editor::delete_to_end_of_line);
 218        register_action(view, cx, Editor::cut_to_end_of_line);
 219        register_action(view, cx, Editor::duplicate_line_up);
 220        register_action(view, cx, Editor::duplicate_line_down);
 221        register_action(view, cx, Editor::move_line_up);
 222        register_action(view, cx, Editor::move_line_down);
 223        register_action(view, cx, Editor::transpose);
 224        register_action(view, cx, Editor::rewrap);
 225        register_action(view, cx, Editor::cut);
 226        register_action(view, cx, Editor::kill_ring_cut);
 227        register_action(view, cx, Editor::kill_ring_yank);
 228        register_action(view, cx, Editor::copy);
 229        register_action(view, cx, Editor::paste);
 230        register_action(view, cx, Editor::undo);
 231        register_action(view, cx, Editor::redo);
 232        register_action(view, cx, Editor::move_page_up);
 233        register_action(view, cx, Editor::move_page_down);
 234        register_action(view, cx, Editor::next_screen);
 235        register_action(view, cx, Editor::scroll_cursor_top);
 236        register_action(view, cx, Editor::scroll_cursor_center);
 237        register_action(view, cx, Editor::scroll_cursor_bottom);
 238        register_action(view, cx, Editor::scroll_cursor_center_top_bottom);
 239        register_action(view, cx, |editor, _: &LineDown, cx| {
 240            editor.scroll_screen(&ScrollAmount::Line(1.), cx)
 241        });
 242        register_action(view, cx, |editor, _: &LineUp, cx| {
 243            editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
 244        });
 245        register_action(view, cx, |editor, _: &HalfPageDown, cx| {
 246            editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
 247        });
 248        register_action(view, cx, |editor, HandleInput(text): &HandleInput, cx| {
 249            if text.is_empty() {
 250                return;
 251            }
 252            editor.handle_input(text, cx);
 253        });
 254        register_action(view, cx, |editor, _: &HalfPageUp, cx| {
 255            editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
 256        });
 257        register_action(view, cx, |editor, _: &PageDown, cx| {
 258            editor.scroll_screen(&ScrollAmount::Page(1.), cx)
 259        });
 260        register_action(view, cx, |editor, _: &PageUp, cx| {
 261            editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
 262        });
 263        register_action(view, cx, Editor::move_to_previous_word_start);
 264        register_action(view, cx, Editor::move_to_previous_subword_start);
 265        register_action(view, cx, Editor::move_to_next_word_end);
 266        register_action(view, cx, Editor::move_to_next_subword_end);
 267        register_action(view, cx, Editor::move_to_beginning_of_line);
 268        register_action(view, cx, Editor::move_to_end_of_line);
 269        register_action(view, cx, Editor::move_to_start_of_paragraph);
 270        register_action(view, cx, Editor::move_to_end_of_paragraph);
 271        register_action(view, cx, Editor::move_to_beginning);
 272        register_action(view, cx, Editor::move_to_end);
 273        register_action(view, cx, Editor::select_up);
 274        register_action(view, cx, Editor::select_down);
 275        register_action(view, cx, Editor::select_left);
 276        register_action(view, cx, Editor::select_right);
 277        register_action(view, cx, Editor::select_to_previous_word_start);
 278        register_action(view, cx, Editor::select_to_previous_subword_start);
 279        register_action(view, cx, Editor::select_to_next_word_end);
 280        register_action(view, cx, Editor::select_to_next_subword_end);
 281        register_action(view, cx, Editor::select_to_beginning_of_line);
 282        register_action(view, cx, Editor::select_to_end_of_line);
 283        register_action(view, cx, Editor::select_to_start_of_paragraph);
 284        register_action(view, cx, Editor::select_to_end_of_paragraph);
 285        register_action(view, cx, Editor::select_to_beginning);
 286        register_action(view, cx, Editor::select_to_end);
 287        register_action(view, cx, Editor::select_all);
 288        register_action(view, cx, |editor, action, cx| {
 289            editor.select_all_matches(action, cx).log_err();
 290        });
 291        register_action(view, cx, Editor::select_line);
 292        register_action(view, cx, Editor::split_selection_into_lines);
 293        register_action(view, cx, Editor::add_selection_above);
 294        register_action(view, cx, Editor::add_selection_below);
 295        register_action(view, cx, |editor, action, cx| {
 296            editor.select_next(action, cx).log_err();
 297        });
 298        register_action(view, cx, |editor, action, cx| {
 299            editor.select_previous(action, cx).log_err();
 300        });
 301        register_action(view, cx, Editor::toggle_comments);
 302        register_action(view, cx, Editor::select_larger_syntax_node);
 303        register_action(view, cx, Editor::select_smaller_syntax_node);
 304        register_action(view, cx, Editor::select_enclosing_symbol);
 305        register_action(view, cx, Editor::move_to_enclosing_bracket);
 306        register_action(view, cx, Editor::undo_selection);
 307        register_action(view, cx, Editor::redo_selection);
 308        if !view.read(cx).is_singleton(cx) {
 309            register_action(view, cx, Editor::expand_excerpts);
 310            register_action(view, cx, Editor::expand_excerpts_up);
 311            register_action(view, cx, Editor::expand_excerpts_down);
 312        }
 313        register_action(view, cx, Editor::go_to_diagnostic);
 314        register_action(view, cx, Editor::go_to_prev_diagnostic);
 315        register_action(view, cx, Editor::go_to_next_hunk);
 316        register_action(view, cx, Editor::go_to_prev_hunk);
 317        register_action(view, cx, |editor, a, cx| {
 318            editor.go_to_definition(a, cx).detach_and_log_err(cx);
 319        });
 320        register_action(view, cx, |editor, a, cx| {
 321            editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
 322        });
 323        register_action(view, cx, |editor, a, cx| {
 324            editor.go_to_declaration(a, cx).detach_and_log_err(cx);
 325        });
 326        register_action(view, cx, |editor, a, cx| {
 327            editor.go_to_declaration_split(a, cx).detach_and_log_err(cx);
 328        });
 329        register_action(view, cx, |editor, a, cx| {
 330            editor.go_to_implementation(a, cx).detach_and_log_err(cx);
 331        });
 332        register_action(view, cx, |editor, a, cx| {
 333            editor
 334                .go_to_implementation_split(a, cx)
 335                .detach_and_log_err(cx);
 336        });
 337        register_action(view, cx, |editor, a, cx| {
 338            editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
 339        });
 340        register_action(view, cx, |editor, a, cx| {
 341            editor
 342                .go_to_type_definition_split(a, cx)
 343                .detach_and_log_err(cx);
 344        });
 345        register_action(view, cx, Editor::open_url);
 346        register_action(view, cx, Editor::open_file);
 347        register_action(view, cx, Editor::fold);
 348        register_action(view, cx, Editor::fold_at_level);
 349        register_action(view, cx, Editor::fold_all);
 350        register_action(view, cx, Editor::fold_function_bodies);
 351        register_action(view, cx, Editor::fold_at);
 352        register_action(view, cx, Editor::fold_recursive);
 353        register_action(view, cx, Editor::toggle_fold);
 354        register_action(view, cx, Editor::toggle_fold_recursive);
 355        register_action(view, cx, Editor::unfold_lines);
 356        register_action(view, cx, Editor::unfold_recursive);
 357        register_action(view, cx, Editor::unfold_all);
 358        register_action(view, cx, Editor::unfold_at);
 359        register_action(view, cx, Editor::fold_selected_ranges);
 360        register_action(view, cx, Editor::show_completions);
 361        register_action(view, cx, Editor::toggle_code_actions);
 362        register_action(view, cx, Editor::open_excerpts);
 363        register_action(view, cx, Editor::open_excerpts_in_split);
 364        register_action(view, cx, Editor::open_proposed_changes_editor);
 365        register_action(view, cx, Editor::toggle_soft_wrap);
 366        register_action(view, cx, Editor::toggle_tab_bar);
 367        register_action(view, cx, Editor::toggle_line_numbers);
 368        register_action(view, cx, Editor::toggle_relative_line_numbers);
 369        register_action(view, cx, Editor::toggle_indent_guides);
 370        register_action(view, cx, Editor::toggle_inlay_hints);
 371        register_action(view, cx, Editor::toggle_inline_completions);
 372        register_action(view, cx, hover_popover::hover);
 373        register_action(view, cx, Editor::reveal_in_finder);
 374        register_action(view, cx, Editor::copy_path);
 375        register_action(view, cx, Editor::copy_relative_path);
 376        register_action(view, cx, Editor::copy_highlight_json);
 377        register_action(view, cx, Editor::copy_permalink_to_line);
 378        register_action(view, cx, Editor::open_permalink_to_line);
 379        register_action(view, cx, Editor::copy_file_location);
 380        register_action(view, cx, Editor::toggle_git_blame);
 381        register_action(view, cx, Editor::toggle_git_blame_inline);
 382        register_action(view, cx, Editor::toggle_hunk_diff);
 383        register_action(view, cx, Editor::expand_all_hunk_diffs);
 384        register_action(view, cx, |editor, action, cx| {
 385            if let Some(task) = editor.format(action, cx) {
 386                task.detach_and_log_err(cx);
 387            } else {
 388                cx.propagate();
 389            }
 390        });
 391        register_action(view, cx, |editor, action, cx| {
 392            if let Some(task) = editor.format_selections(action, cx) {
 393                task.detach_and_log_err(cx);
 394            } else {
 395                cx.propagate();
 396            }
 397        });
 398        register_action(view, cx, Editor::restart_language_server);
 399        register_action(view, cx, Editor::cancel_language_server_work);
 400        register_action(view, cx, Editor::show_character_palette);
 401        register_action(view, cx, |editor, action, cx| {
 402            if let Some(task) = editor.confirm_completion(action, cx) {
 403                task.detach_and_log_err(cx);
 404            } else {
 405                cx.propagate();
 406            }
 407        });
 408        register_action(view, cx, |editor, action, cx| {
 409            if let Some(task) = editor.compose_completion(action, cx) {
 410                task.detach_and_log_err(cx);
 411            } else {
 412                cx.propagate();
 413            }
 414        });
 415        register_action(view, cx, |editor, action, cx| {
 416            if let Some(task) = editor.confirm_code_action(action, cx) {
 417                task.detach_and_log_err(cx);
 418            } else {
 419                cx.propagate();
 420            }
 421        });
 422        register_action(view, cx, |editor, action, cx| {
 423            if let Some(task) = editor.rename(action, cx) {
 424                task.detach_and_log_err(cx);
 425            } else {
 426                cx.propagate();
 427            }
 428        });
 429        register_action(view, cx, |editor, action, cx| {
 430            if let Some(task) = editor.confirm_rename(action, cx) {
 431                task.detach_and_log_err(cx);
 432            } else {
 433                cx.propagate();
 434            }
 435        });
 436        register_action(view, cx, |editor, action, cx| {
 437            if let Some(task) = editor.find_all_references(action, cx) {
 438                task.detach_and_log_err(cx);
 439            } else {
 440                cx.propagate();
 441            }
 442        });
 443        register_action(view, cx, Editor::show_signature_help);
 444        register_action(view, cx, Editor::next_inline_completion);
 445        register_action(view, cx, Editor::previous_inline_completion);
 446        register_action(view, cx, Editor::show_inline_completion);
 447        register_action(view, cx, Editor::context_menu_first);
 448        register_action(view, cx, Editor::context_menu_prev);
 449        register_action(view, cx, Editor::context_menu_next);
 450        register_action(view, cx, Editor::context_menu_last);
 451        register_action(view, cx, Editor::display_cursor_names);
 452        register_action(view, cx, Editor::unique_lines_case_insensitive);
 453        register_action(view, cx, Editor::unique_lines_case_sensitive);
 454        register_action(view, cx, Editor::accept_partial_inline_completion);
 455        register_action(view, cx, Editor::accept_inline_completion);
 456        register_action(view, cx, Editor::revert_file);
 457        register_action(view, cx, Editor::revert_selected_hunks);
 458        register_action(view, cx, Editor::apply_all_diff_hunks);
 459        register_action(view, cx, Editor::apply_selected_diff_hunks);
 460        register_action(view, cx, Editor::open_active_item_in_terminal);
 461        register_action(view, cx, Editor::reload_file);
 462        register_action(view, cx, Editor::spawn_nearest_task);
 463        register_action(view, cx, Editor::insert_uuid_v4);
 464        register_action(view, cx, Editor::insert_uuid_v7);
 465    }
 466
 467    fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
 468        let position_map = layout.position_map.clone();
 469        cx.on_key_event({
 470            let editor = self.editor.clone();
 471            let text_hitbox = layout.text_hitbox.clone();
 472            move |event: &ModifiersChangedEvent, phase, cx| {
 473                if phase != DispatchPhase::Bubble {
 474                    return;
 475                }
 476                editor.update(cx, |editor, cx| {
 477                    if editor.hover_state.focused(cx) {
 478                        return;
 479                    }
 480                    Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
 481                })
 482            }
 483        });
 484    }
 485
 486    fn modifiers_changed(
 487        editor: &mut Editor,
 488        event: &ModifiersChangedEvent,
 489        position_map: &PositionMap,
 490        text_hitbox: &Hitbox,
 491        cx: &mut ViewContext<Editor>,
 492    ) {
 493        let mouse_position = cx.mouse_position();
 494        if !text_hitbox.is_hovered(cx) {
 495            return;
 496        }
 497
 498        editor.update_hovered_link(
 499            position_map.point_for_position(text_hitbox.bounds, mouse_position),
 500            &position_map.snapshot,
 501            event.modifiers,
 502            cx,
 503        )
 504    }
 505
 506    fn mouse_left_down(
 507        editor: &mut Editor,
 508        event: &MouseDownEvent,
 509        hovered_hunk: Option<HoveredHunk>,
 510        position_map: &PositionMap,
 511        text_hitbox: &Hitbox,
 512        gutter_hitbox: &Hitbox,
 513        cx: &mut ViewContext<Editor>,
 514    ) {
 515        if cx.default_prevented() {
 516            return;
 517        }
 518
 519        let mut click_count = event.click_count;
 520        let mut modifiers = event.modifiers;
 521
 522        if let Some(hovered_hunk) = hovered_hunk {
 523            editor.toggle_hovered_hunk(&hovered_hunk, cx);
 524            cx.notify();
 525            return;
 526        } else if gutter_hitbox.is_hovered(cx) {
 527            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 528        } else if !text_hitbox.is_hovered(cx) {
 529            return;
 530        }
 531
 532        if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
 533            match EditorSettings::get_global(cx).double_click_in_multibuffer {
 534                DoubleClickInMultibuffer::Select => {
 535                    // do nothing special on double click, all selection logic is below
 536                }
 537                DoubleClickInMultibuffer::Open => {
 538                    if modifiers.alt {
 539                        // if double click is made with alt, pretend it's a regular double click without opening and alt,
 540                        // and run the selection logic.
 541                        modifiers.alt = false;
 542                    } else {
 543                        // if double click is made without alt, open the corresponding excerp
 544                        editor.open_excerpts(&OpenExcerpts, cx);
 545                        return;
 546                    }
 547                }
 548            }
 549        }
 550
 551        let point_for_position =
 552            position_map.point_for_position(text_hitbox.bounds, event.position);
 553        let position = point_for_position.previous_valid;
 554        if modifiers.shift && modifiers.alt {
 555            editor.select(
 556                SelectPhase::BeginColumnar {
 557                    position,
 558                    reset: false,
 559                    goal_column: point_for_position.exact_unclipped.column(),
 560                },
 561                cx,
 562            );
 563        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
 564        {
 565            editor.select(
 566                SelectPhase::Extend {
 567                    position,
 568                    click_count,
 569                },
 570                cx,
 571            );
 572        } else {
 573            let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 574            let multi_cursor_modifier = match multi_cursor_setting {
 575                MultiCursorModifier::Alt => modifiers.alt,
 576                MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
 577            };
 578            editor.select(
 579                SelectPhase::Begin {
 580                    position,
 581                    add: multi_cursor_modifier,
 582                    click_count,
 583                },
 584                cx,
 585            );
 586        }
 587
 588        cx.stop_propagation();
 589    }
 590
 591    fn mouse_right_down(
 592        editor: &mut Editor,
 593        event: &MouseDownEvent,
 594        position_map: &PositionMap,
 595        text_hitbox: &Hitbox,
 596        cx: &mut ViewContext<Editor>,
 597    ) {
 598        if !text_hitbox.is_hovered(cx) {
 599            return;
 600        }
 601        let point_for_position =
 602            position_map.point_for_position(text_hitbox.bounds, event.position);
 603        mouse_context_menu::deploy_context_menu(
 604            editor,
 605            Some(event.position),
 606            point_for_position.previous_valid,
 607            cx,
 608        );
 609        cx.stop_propagation();
 610    }
 611
 612    fn mouse_middle_down(
 613        editor: &mut Editor,
 614        event: &MouseDownEvent,
 615        position_map: &PositionMap,
 616        text_hitbox: &Hitbox,
 617        cx: &mut ViewContext<Editor>,
 618    ) {
 619        if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
 620            return;
 621        }
 622
 623        let point_for_position =
 624            position_map.point_for_position(text_hitbox.bounds, event.position);
 625        let position = point_for_position.previous_valid;
 626
 627        editor.select(
 628            SelectPhase::BeginColumnar {
 629                position,
 630                reset: true,
 631                goal_column: point_for_position.exact_unclipped.column(),
 632            },
 633            cx,
 634        );
 635    }
 636
 637    fn mouse_up(
 638        editor: &mut Editor,
 639        event: &MouseUpEvent,
 640        position_map: &PositionMap,
 641        text_hitbox: &Hitbox,
 642        cx: &mut ViewContext<Editor>,
 643    ) {
 644        let end_selection = editor.has_pending_selection();
 645        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 646
 647        if end_selection {
 648            editor.select(SelectPhase::End, cx);
 649        }
 650
 651        let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
 652        let multi_cursor_modifier = match multi_cursor_setting {
 653            MultiCursorModifier::Alt => event.modifiers.secondary(),
 654            MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
 655        };
 656
 657        if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
 658            let point = position_map.point_for_position(text_hitbox.bounds, event.position);
 659            editor.handle_click_hovered_link(point, event.modifiers, cx);
 660
 661            cx.stop_propagation();
 662        } else if end_selection && pending_nonempty_selections {
 663            cx.stop_propagation();
 664        } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
 665            && event.button == MouseButton::Middle
 666        {
 667            if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
 668                return;
 669            }
 670
 671            #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 672            if EditorSettings::get_global(cx).middle_click_paste {
 673                if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
 674                    let point_for_position =
 675                        position_map.point_for_position(text_hitbox.bounds, event.position);
 676                    let position = point_for_position.previous_valid;
 677
 678                    editor.select(
 679                        SelectPhase::Begin {
 680                            position,
 681                            add: false,
 682                            click_count: 1,
 683                        },
 684                        cx,
 685                    );
 686                    editor.insert(&text, cx);
 687                }
 688                cx.stop_propagation()
 689            }
 690        }
 691    }
 692
 693    fn mouse_dragged(
 694        editor: &mut Editor,
 695        event: &MouseMoveEvent,
 696        position_map: &PositionMap,
 697        text_bounds: Bounds<Pixels>,
 698        cx: &mut ViewContext<Editor>,
 699    ) {
 700        if !editor.has_pending_selection() {
 701            return;
 702        }
 703
 704        let point_for_position = position_map.point_for_position(text_bounds, event.position);
 705        let mut scroll_delta = gpui::Point::<f32>::default();
 706        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 707        let top = text_bounds.origin.y + vertical_margin;
 708        let bottom = text_bounds.lower_left().y - vertical_margin;
 709        if event.position.y < top {
 710            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 711        }
 712        if event.position.y > bottom {
 713            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 714        }
 715
 716        let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
 717        let left = text_bounds.origin.x + horizontal_margin;
 718        let right = text_bounds.upper_right().x - horizontal_margin;
 719        if event.position.x < left {
 720            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 721        }
 722        if event.position.x > right {
 723            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 724        }
 725
 726        editor.select(
 727            SelectPhase::Update {
 728                position: point_for_position.previous_valid,
 729                goal_column: point_for_position.exact_unclipped.column(),
 730                scroll_delta,
 731            },
 732            cx,
 733        );
 734    }
 735
 736    fn mouse_moved(
 737        editor: &mut Editor,
 738        event: &MouseMoveEvent,
 739        position_map: &PositionMap,
 740        text_hitbox: &Hitbox,
 741        gutter_hitbox: &Hitbox,
 742        cx: &mut ViewContext<Editor>,
 743    ) {
 744        let modifiers = event.modifiers;
 745        let gutter_hovered = gutter_hitbox.is_hovered(cx);
 746        editor.set_gutter_hovered(gutter_hovered, cx);
 747
 748        // Don't trigger hover popover if mouse is hovering over context menu
 749        if text_hitbox.is_hovered(cx) {
 750            let point_for_position =
 751                position_map.point_for_position(text_hitbox.bounds, event.position);
 752
 753            editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
 754
 755            if let Some(point) = point_for_position.as_valid() {
 756                let anchor = position_map
 757                    .snapshot
 758                    .buffer_snapshot
 759                    .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
 760                hover_at(editor, Some(anchor), cx);
 761                Self::update_visible_cursor(editor, point, position_map, cx);
 762            } else {
 763                hover_at(editor, None, cx);
 764            }
 765        } else {
 766            editor.hide_hovered_link(cx);
 767            hover_at(editor, None, cx);
 768            if gutter_hovered {
 769                cx.stop_propagation();
 770            }
 771        }
 772    }
 773
 774    fn update_visible_cursor(
 775        editor: &mut Editor,
 776        point: DisplayPoint,
 777        position_map: &PositionMap,
 778        cx: &mut ViewContext<Editor>,
 779    ) {
 780        let snapshot = &position_map.snapshot;
 781        let Some(hub) = editor.collaboration_hub() else {
 782            return;
 783        };
 784        let start = snapshot.display_snapshot.clip_point(
 785            DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
 786            Bias::Left,
 787        );
 788        let end = snapshot.display_snapshot.clip_point(
 789            DisplayPoint::new(
 790                point.row(),
 791                (point.column() + 1).min(snapshot.line_len(point.row())),
 792            ),
 793            Bias::Right,
 794        );
 795
 796        let range = snapshot
 797            .buffer_snapshot
 798            .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
 799            ..snapshot
 800                .buffer_snapshot
 801                .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
 802
 803        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 804            return;
 805        };
 806        let key = crate::HoveredCursor {
 807            replica_id: selection.replica_id,
 808            selection_id: selection.selection.id,
 809        };
 810        editor.hovered_cursors.insert(
 811            key.clone(),
 812            cx.spawn(|editor, mut cx| async move {
 813                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 814                editor
 815                    .update(&mut cx, |editor, cx| {
 816                        editor.hovered_cursors.remove(&key);
 817                        cx.notify();
 818                    })
 819                    .ok();
 820            }),
 821        );
 822        cx.notify()
 823    }
 824
 825    #[allow(clippy::too_many_arguments)]
 826    fn layout_selections(
 827        &self,
 828        start_anchor: Anchor,
 829        end_anchor: Anchor,
 830        local_selections: &[Selection<Point>],
 831        snapshot: &EditorSnapshot,
 832        start_row: DisplayRow,
 833        end_row: DisplayRow,
 834        cx: &mut WindowContext,
 835    ) -> (
 836        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 837        BTreeMap<DisplayRow, bool>,
 838        Option<DisplayPoint>,
 839    ) {
 840        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 841        let mut active_rows = BTreeMap::new();
 842        let mut newest_selection_head = None;
 843        self.editor.update(cx, |editor, cx| {
 844            if editor.show_local_selections {
 845                let mut layouts = Vec::new();
 846                let newest = editor.selections.newest(cx);
 847                for selection in local_selections.iter().cloned() {
 848                    let is_empty = selection.start == selection.end;
 849                    let is_newest = selection == newest;
 850
 851                    let layout = SelectionLayout::new(
 852                        selection,
 853                        editor.selections.line_mode,
 854                        editor.cursor_shape,
 855                        &snapshot.display_snapshot,
 856                        is_newest,
 857                        editor.leader_peer_id.is_none(),
 858                        None,
 859                    );
 860                    if is_newest {
 861                        newest_selection_head = Some(layout.head);
 862                    }
 863
 864                    for row in cmp::max(layout.active_rows.start.0, start_row.0)
 865                        ..=cmp::min(layout.active_rows.end.0, end_row.0)
 866                    {
 867                        let contains_non_empty_selection =
 868                            active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
 869                        *contains_non_empty_selection |= !is_empty;
 870                    }
 871                    layouts.push(layout);
 872                }
 873
 874                let player = if editor.read_only(cx) {
 875                    cx.theme().players().read_only()
 876                } else {
 877                    self.style.local_player
 878                };
 879
 880                selections.push((player, layouts));
 881            }
 882
 883            if let Some(collaboration_hub) = &editor.collaboration_hub {
 884                // When following someone, render the local selections in their color.
 885                if let Some(leader_id) = editor.leader_peer_id {
 886                    if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id)
 887                    {
 888                        if let Some(participant_index) = collaboration_hub
 889                            .user_participant_indices(cx)
 890                            .get(&collaborator.user_id)
 891                        {
 892                            if let Some((local_selection_style, _)) = selections.first_mut() {
 893                                *local_selection_style = cx
 894                                    .theme()
 895                                    .players()
 896                                    .color_for_participant(participant_index.0);
 897                            }
 898                        }
 899                    }
 900                }
 901
 902                let mut remote_selections = HashMap::default();
 903                for selection in snapshot.remote_selections_in_range(
 904                    &(start_anchor..end_anchor),
 905                    collaboration_hub.as_ref(),
 906                    cx,
 907                ) {
 908                    let selection_style =
 909                        Self::get_participant_color(selection.participant_index, cx);
 910
 911                    // Don't re-render the leader's selections, since the local selections
 912                    // match theirs.
 913                    if Some(selection.peer_id) == editor.leader_peer_id {
 914                        continue;
 915                    }
 916                    let key = HoveredCursor {
 917                        replica_id: selection.replica_id,
 918                        selection_id: selection.selection.id,
 919                    };
 920
 921                    let is_shown =
 922                        editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 923
 924                    remote_selections
 925                        .entry(selection.replica_id)
 926                        .or_insert((selection_style, Vec::new()))
 927                        .1
 928                        .push(SelectionLayout::new(
 929                            selection.selection,
 930                            selection.line_mode,
 931                            selection.cursor_shape,
 932                            &snapshot.display_snapshot,
 933                            false,
 934                            false,
 935                            if is_shown { selection.user_name } else { None },
 936                        ));
 937                }
 938
 939                selections.extend(remote_selections.into_values());
 940            } else if !editor.is_focused(cx) && editor.show_cursor_when_unfocused {
 941                let player = if editor.read_only(cx) {
 942                    cx.theme().players().read_only()
 943                } else {
 944                    self.style.local_player
 945                };
 946                let layouts = snapshot
 947                    .buffer_snapshot
 948                    .selections_in_range(&(start_anchor..end_anchor), true)
 949                    .map(move |(_, line_mode, cursor_shape, selection)| {
 950                        SelectionLayout::new(
 951                            selection,
 952                            line_mode,
 953                            cursor_shape,
 954                            &snapshot.display_snapshot,
 955                            false,
 956                            false,
 957                            None,
 958                        )
 959                    })
 960                    .collect::<Vec<_>>();
 961                selections.push((player, layouts));
 962            }
 963        });
 964        (selections, active_rows, newest_selection_head)
 965    }
 966
 967    fn collect_cursors(
 968        &self,
 969        snapshot: &EditorSnapshot,
 970        cx: &mut WindowContext,
 971    ) -> Vec<(DisplayPoint, Hsla)> {
 972        let editor = self.editor.read(cx);
 973        let mut cursors = Vec::new();
 974        let mut skip_local = false;
 975        let mut add_cursor = |anchor: Anchor, color| {
 976            cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
 977        };
 978        // Remote cursors
 979        if let Some(collaboration_hub) = &editor.collaboration_hub {
 980            for remote_selection in snapshot.remote_selections_in_range(
 981                &(Anchor::min()..Anchor::max()),
 982                collaboration_hub.deref(),
 983                cx,
 984            ) {
 985                let color = Self::get_participant_color(remote_selection.participant_index, cx);
 986                add_cursor(remote_selection.selection.head(), color.cursor);
 987                if Some(remote_selection.peer_id) == editor.leader_peer_id {
 988                    skip_local = true;
 989                }
 990            }
 991        }
 992        // Local cursors
 993        if !skip_local {
 994            let color = cx.theme().players().local().cursor;
 995            editor.selections.disjoint.iter().for_each(|selection| {
 996                add_cursor(selection.head(), color);
 997            });
 998            if let Some(ref selection) = editor.selections.pending_anchor() {
 999                add_cursor(selection.head(), color);
1000            }
1001        }
1002        cursors
1003    }
1004
1005    #[allow(clippy::too_many_arguments)]
1006    fn layout_visible_cursors(
1007        &self,
1008        snapshot: &EditorSnapshot,
1009        selections: &[(PlayerColor, Vec<SelectionLayout>)],
1010        block_start_rows: &HashSet<DisplayRow>,
1011        visible_display_row_range: Range<DisplayRow>,
1012        line_layouts: &[LineWithInvisibles],
1013        text_hitbox: &Hitbox,
1014        content_origin: gpui::Point<Pixels>,
1015        scroll_position: gpui::Point<f32>,
1016        scroll_pixel_position: gpui::Point<Pixels>,
1017        line_height: Pixels,
1018        em_width: Pixels,
1019        autoscroll_containing_element: bool,
1020        cx: &mut WindowContext,
1021    ) -> Vec<CursorLayout> {
1022        let mut autoscroll_bounds = None;
1023        let cursor_layouts = self.editor.update(cx, |editor, cx| {
1024            let mut cursors = Vec::new();
1025            for (player_color, selections) in selections {
1026                for selection in selections {
1027                    let cursor_position = selection.head;
1028
1029                    let in_range = visible_display_row_range.contains(&cursor_position.row());
1030                    if (selection.is_local && !editor.show_local_cursors(cx))
1031                        || !in_range
1032                        || block_start_rows.contains(&cursor_position.row())
1033                    {
1034                        continue;
1035                    }
1036
1037                    let cursor_row_layout = &line_layouts
1038                        [cursor_position.row().minus(visible_display_row_range.start) as usize];
1039                    let cursor_column = cursor_position.column() as usize;
1040
1041                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1042                    let mut block_width =
1043                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1044                    if block_width == Pixels::ZERO {
1045                        block_width = em_width;
1046                    }
1047                    let block_text = if let CursorShape::Block = selection.cursor_shape {
1048                        snapshot
1049                            .grapheme_at(cursor_position)
1050                            .or_else(|| {
1051                                if cursor_column == 0 {
1052                                    snapshot.placeholder_text().and_then(|s| {
1053                                        s.graphemes(true).next().map(|s| s.to_string().into())
1054                                    })
1055                                } else {
1056                                    None
1057                                }
1058                            })
1059                            .and_then(|text| {
1060                                let len = text.len();
1061
1062                                let font = cursor_row_layout
1063                                    .font_id_for_index(cursor_column)
1064                                    .and_then(|cursor_font_id| {
1065                                        cx.text_system().get_font_for_id(cursor_font_id)
1066                                    })
1067                                    .unwrap_or(self.style.text.font());
1068
1069                                // Invert the text color for the block cursor. Ensure that the text
1070                                // color is opaque enough to be visible against the background color.
1071                                //
1072                                // 0.75 is an arbitrary threshold to determine if the background color is
1073                                // opaque enough to use as a text color.
1074                                //
1075                                // TODO: In the future we should ensure themes have a `text_inverse` color.
1076                                let color = if cx.theme().colors().editor_background.a < 0.75 {
1077                                    match cx.theme().appearance {
1078                                        Appearance::Dark => Hsla::black(),
1079                                        Appearance::Light => Hsla::white(),
1080                                    }
1081                                } else {
1082                                    cx.theme().colors().editor_background
1083                                };
1084
1085                                cx.text_system()
1086                                    .shape_line(
1087                                        text,
1088                                        cursor_row_layout.font_size,
1089                                        &[TextRun {
1090                                            len,
1091                                            font,
1092                                            color,
1093                                            background_color: None,
1094                                            strikethrough: None,
1095                                            underline: None,
1096                                        }],
1097                                    )
1098                                    .log_err()
1099                            })
1100                    } else {
1101                        None
1102                    };
1103
1104                    let x = cursor_character_x - scroll_pixel_position.x;
1105                    let y = (cursor_position.row().as_f32()
1106                        - scroll_pixel_position.y / line_height)
1107                        * line_height;
1108                    if selection.is_newest {
1109                        editor.pixel_position_of_newest_cursor = Some(point(
1110                            text_hitbox.origin.x + x + block_width / 2.,
1111                            text_hitbox.origin.y + y + line_height / 2.,
1112                        ));
1113
1114                        if autoscroll_containing_element {
1115                            let top = text_hitbox.origin.y
1116                                + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1117                                    * line_height;
1118                            let left = text_hitbox.origin.x
1119                                + (cursor_position.column() as f32 - scroll_position.x - 3.)
1120                                    .max(0.)
1121                                    * em_width;
1122
1123                            let bottom = text_hitbox.origin.y
1124                                + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1125                                    * line_height;
1126                            let right = text_hitbox.origin.x
1127                                + (cursor_position.column() as f32 - scroll_position.x + 4.)
1128                                    * em_width;
1129
1130                            autoscroll_bounds =
1131                                Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1132                        }
1133                    }
1134
1135                    let mut cursor = CursorLayout {
1136                        color: player_color.cursor,
1137                        block_width,
1138                        origin: point(x, y),
1139                        line_height,
1140                        shape: selection.cursor_shape,
1141                        block_text,
1142                        cursor_name: None,
1143                    };
1144                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
1145                        string: name,
1146                        color: self.style.background,
1147                        is_top_row: cursor_position.row().0 == 0,
1148                    });
1149                    cursor.layout(content_origin, cursor_name, cx);
1150                    cursors.push(cursor);
1151                }
1152            }
1153            cursors
1154        });
1155
1156        if let Some(bounds) = autoscroll_bounds {
1157            cx.request_autoscroll(bounds);
1158        }
1159
1160        cursor_layouts
1161    }
1162
1163    fn layout_scrollbar(
1164        &self,
1165        snapshot: &EditorSnapshot,
1166        bounds: Bounds<Pixels>,
1167        scroll_position: gpui::Point<f32>,
1168        rows_per_page: f32,
1169        non_visible_cursors: bool,
1170        cx: &mut WindowContext,
1171    ) -> Option<ScrollbarLayout> {
1172        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1173        let show_scrollbars = match scrollbar_settings.show {
1174            ShowScrollbar::Auto => {
1175                let editor = self.editor.read(cx);
1176                let is_singleton = editor.is_singleton(cx);
1177                // Git
1178                (is_singleton && scrollbar_settings.git_diff && !snapshot.diff_map.is_empty())
1179                    ||
1180                    // Buffer Search Results
1181                    (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1182                    ||
1183                    // Selected Symbol Occurrences
1184                    (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1185                    ||
1186                    // Diagnostics
1187                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1188                    ||
1189                    // Cursors out of sight
1190                    non_visible_cursors
1191                    ||
1192                    // Scrollmanager
1193                    editor.scroll_manager.scrollbars_visible()
1194            }
1195            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1196            ShowScrollbar::Always => true,
1197            ShowScrollbar::Never => false,
1198        };
1199        if snapshot.mode != EditorMode::Full {
1200            return None;
1201        }
1202
1203        let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1204
1205        // If a drag took place after we started dragging the scrollbar,
1206        // cancel the scrollbar drag.
1207        if cx.has_active_drag() {
1208            self.editor.update(cx, |editor, cx| {
1209                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1210            });
1211        }
1212
1213        let track_bounds = Bounds::from_corners(
1214            point(self.scrollbar_left(&bounds), bounds.origin.y),
1215            point(bounds.lower_right().x, bounds.lower_left().y),
1216        );
1217
1218        let settings = EditorSettings::get_global(cx);
1219        let scroll_beyond_last_line: f32 = match settings.scroll_beyond_last_line {
1220            ScrollBeyondLastLine::OnePage => rows_per_page,
1221            ScrollBeyondLastLine::Off => 1.0,
1222            ScrollBeyondLastLine::VerticalScrollMargin => 1.0 + settings.vertical_scroll_margin,
1223        };
1224        let total_rows =
1225            (snapshot.max_point().row().as_f32() + scroll_beyond_last_line).max(rows_per_page);
1226        let height = bounds.size.height;
1227        let px_per_row = height / total_rows;
1228        let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1229        let row_height = (height - thumb_height) / (total_rows - rows_per_page).max(0.);
1230
1231        Some(ScrollbarLayout {
1232            hitbox: cx.insert_hitbox(track_bounds, false),
1233            visible_row_range,
1234            row_height,
1235            visible: show_scrollbars,
1236            thumb_height,
1237        })
1238    }
1239
1240    #[allow(clippy::too_many_arguments)]
1241    fn prepaint_crease_toggles(
1242        &self,
1243        crease_toggles: &mut [Option<AnyElement>],
1244        line_height: Pixels,
1245        gutter_dimensions: &GutterDimensions,
1246        gutter_settings: crate::editor_settings::Gutter,
1247        scroll_pixel_position: gpui::Point<Pixels>,
1248        gutter_hitbox: &Hitbox,
1249        cx: &mut WindowContext,
1250    ) {
1251        for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
1252            if let Some(crease_toggle) = crease_toggle {
1253                debug_assert!(gutter_settings.folds);
1254                let available_space = size(
1255                    AvailableSpace::MinContent,
1256                    AvailableSpace::Definite(line_height * 0.55),
1257                );
1258                let crease_toggle_size = crease_toggle.layout_as_root(available_space, cx);
1259
1260                let position = point(
1261                    gutter_dimensions.width - gutter_dimensions.right_padding,
1262                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1263                );
1264                let centering_offset = point(
1265                    (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
1266                    (line_height - crease_toggle_size.height) / 2.,
1267                );
1268                let origin = gutter_hitbox.origin + position + centering_offset;
1269                crease_toggle.prepaint_as_root(origin, available_space, cx);
1270            }
1271        }
1272    }
1273
1274    #[allow(clippy::too_many_arguments)]
1275    fn prepaint_crease_trailers(
1276        &self,
1277        trailers: Vec<Option<AnyElement>>,
1278        lines: &[LineWithInvisibles],
1279        line_height: Pixels,
1280        content_origin: gpui::Point<Pixels>,
1281        scroll_pixel_position: gpui::Point<Pixels>,
1282        em_width: Pixels,
1283        cx: &mut WindowContext,
1284    ) -> Vec<Option<CreaseTrailerLayout>> {
1285        trailers
1286            .into_iter()
1287            .enumerate()
1288            .map(|(ix, element)| {
1289                let mut element = element?;
1290                let available_space = size(
1291                    AvailableSpace::MinContent,
1292                    AvailableSpace::Definite(line_height),
1293                );
1294                let size = element.layout_as_root(available_space, cx);
1295
1296                let line = &lines[ix];
1297                let padding = if line.width == Pixels::ZERO {
1298                    Pixels::ZERO
1299                } else {
1300                    4. * em_width
1301                };
1302                let position = point(
1303                    scroll_pixel_position.x + line.width + padding,
1304                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1305                );
1306                let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1307                let origin = content_origin + position + centering_offset;
1308                element.prepaint_as_root(origin, available_space, cx);
1309                Some(CreaseTrailerLayout {
1310                    element,
1311                    bounds: Bounds::new(origin, size),
1312                })
1313            })
1314            .collect()
1315    }
1316
1317    // Folds contained in a hunk are ignored apart from shrinking visual size
1318    // If a fold contains any hunks then that fold line is marked as modified
1319    fn layout_gutter_git_hunks(
1320        &self,
1321        line_height: Pixels,
1322        gutter_hitbox: &Hitbox,
1323        display_rows: Range<DisplayRow>,
1324        anchor_range: Range<Anchor>,
1325        snapshot: &EditorSnapshot,
1326        cx: &mut WindowContext,
1327    ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1328        let buffer_snapshot = &snapshot.buffer_snapshot;
1329        let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(snapshot);
1330        let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(snapshot);
1331
1332        let git_gutter_setting = ProjectSettings::get_global(cx)
1333            .git
1334            .git_gutter
1335            .unwrap_or_default();
1336
1337        self.editor.update(cx, |editor, cx| {
1338            let expanded_hunks = &editor.diff_map.hunks;
1339            let expanded_hunks_start_ix = expanded_hunks
1340                .binary_search_by(|hunk| {
1341                    hunk.hunk_range
1342                        .end
1343                        .cmp(&anchor_range.start, &buffer_snapshot)
1344                        .then(Ordering::Less)
1345                })
1346                .unwrap_err();
1347            let mut expanded_hunks = expanded_hunks[expanded_hunks_start_ix..].iter().peekable();
1348
1349            let mut display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)> = editor
1350                .diff_map
1351                .snapshot
1352                .diff_hunks_in_range(buffer_start..buffer_end, &buffer_snapshot)
1353                .filter_map(|hunk| {
1354                    let display_hunk = diff_hunk_to_display(&hunk, snapshot);
1355
1356                    if let DisplayDiffHunk::Unfolded {
1357                        multi_buffer_range,
1358                        status,
1359                        ..
1360                    } = &display_hunk
1361                    {
1362                        let mut is_expanded = false;
1363                        while let Some(expanded_hunk) = expanded_hunks.peek() {
1364                            match expanded_hunk
1365                                .hunk_range
1366                                .start
1367                                .cmp(&multi_buffer_range.start, &buffer_snapshot)
1368                            {
1369                                Ordering::Less => {
1370                                    expanded_hunks.next();
1371                                }
1372                                Ordering::Equal => {
1373                                    is_expanded = true;
1374                                    break;
1375                                }
1376                                Ordering::Greater => {
1377                                    break;
1378                                }
1379                            }
1380                        }
1381                        match status {
1382                            DiffHunkStatus::Added => {}
1383                            DiffHunkStatus::Modified => {}
1384                            DiffHunkStatus::Removed => {
1385                                if is_expanded {
1386                                    return None;
1387                                }
1388                            }
1389                        }
1390                    }
1391
1392                    Some(display_hunk)
1393                })
1394                .dedup()
1395                .map(|hunk| (hunk, None))
1396                .collect();
1397
1398            if let GitGutterSetting::TrackedFiles = git_gutter_setting {
1399                for (hunk, hitbox) in &mut display_hunks {
1400                    if let DisplayDiffHunk::Unfolded { .. } = hunk {
1401                        let hunk_bounds = Self::diff_hunk_bounds(
1402                            snapshot,
1403                            line_height,
1404                            gutter_hitbox.bounds,
1405                            &hunk,
1406                        );
1407                        *hitbox = Some(cx.insert_hitbox(hunk_bounds, true));
1408                    };
1409                }
1410            }
1411
1412            display_hunks
1413        })
1414    }
1415
1416    #[allow(clippy::too_many_arguments)]
1417    fn layout_inline_blame(
1418        &self,
1419        display_row: DisplayRow,
1420        display_snapshot: &DisplaySnapshot,
1421        line_layout: &LineWithInvisibles,
1422        crease_trailer: Option<&CreaseTrailerLayout>,
1423        em_width: Pixels,
1424        content_origin: gpui::Point<Pixels>,
1425        scroll_pixel_position: gpui::Point<Pixels>,
1426        line_height: Pixels,
1427        cx: &mut WindowContext,
1428    ) -> Option<AnyElement> {
1429        if !self
1430            .editor
1431            .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1432        {
1433            return None;
1434        }
1435
1436        let workspace = self
1437            .editor
1438            .read(cx)
1439            .workspace
1440            .as_ref()
1441            .map(|(w, _)| w.clone());
1442
1443        let display_point = DisplayPoint::new(display_row, 0);
1444        let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1445
1446        let blame = self.editor.read(cx).blame.clone()?;
1447        let blame_entry = blame
1448            .update(cx, |blame, cx| {
1449                blame.blame_for_rows([Some(buffer_row)], cx).next()
1450            })
1451            .flatten()?;
1452
1453        let mut element =
1454            render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1455
1456        let start_y = content_origin.y
1457            + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1458
1459        let start_x = {
1460            const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1461
1462            let line_end = if let Some(crease_trailer) = crease_trailer {
1463                crease_trailer.bounds.right()
1464            } else {
1465                content_origin.x - scroll_pixel_position.x + line_layout.width
1466            };
1467            let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1468
1469            let min_column_in_pixels = ProjectSettings::get_global(cx)
1470                .git
1471                .inline_blame
1472                .and_then(|settings| settings.min_column)
1473                .map(|col| self.column_pixels(col as usize, cx))
1474                .unwrap_or(px(0.));
1475            let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1476
1477            cmp::max(padded_line_end, min_start)
1478        };
1479
1480        let absolute_offset = point(start_x, start_y);
1481        element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), cx);
1482
1483        Some(element)
1484    }
1485
1486    #[allow(clippy::too_many_arguments)]
1487    fn layout_blame_entries(
1488        &self,
1489        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1490        em_width: Pixels,
1491        scroll_position: gpui::Point<f32>,
1492        line_height: Pixels,
1493        gutter_hitbox: &Hitbox,
1494        max_width: Option<Pixels>,
1495        cx: &mut WindowContext,
1496    ) -> Option<Vec<AnyElement>> {
1497        if !self
1498            .editor
1499            .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1500        {
1501            return None;
1502        }
1503
1504        let blame = self.editor.read(cx).blame.clone()?;
1505        let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1506            blame.blame_for_rows(buffer_rows, cx).collect()
1507        });
1508
1509        let width = if let Some(max_width) = max_width {
1510            AvailableSpace::Definite(max_width)
1511        } else {
1512            AvailableSpace::MaxContent
1513        };
1514        let scroll_top = scroll_position.y * line_height;
1515        let start_x = em_width;
1516
1517        let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1518
1519        let shaped_lines = blamed_rows
1520            .into_iter()
1521            .enumerate()
1522            .flat_map(|(ix, blame_entry)| {
1523                if let Some(blame_entry) = blame_entry {
1524                    let mut element = render_blame_entry(
1525                        ix,
1526                        &blame,
1527                        blame_entry,
1528                        &self.style,
1529                        &mut last_used_color,
1530                        self.editor.clone(),
1531                        cx,
1532                    );
1533
1534                    let start_y = ix as f32 * line_height - (scroll_top % line_height);
1535                    let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1536
1537                    element.prepaint_as_root(
1538                        absolute_offset,
1539                        size(width, AvailableSpace::MinContent),
1540                        cx,
1541                    );
1542
1543                    Some(element)
1544                } else {
1545                    None
1546                }
1547            })
1548            .collect();
1549
1550        Some(shaped_lines)
1551    }
1552
1553    #[allow(clippy::too_many_arguments)]
1554    fn layout_indent_guides(
1555        &self,
1556        content_origin: gpui::Point<Pixels>,
1557        text_origin: gpui::Point<Pixels>,
1558        visible_buffer_range: Range<MultiBufferRow>,
1559        scroll_pixel_position: gpui::Point<Pixels>,
1560        line_height: Pixels,
1561        snapshot: &DisplaySnapshot,
1562        cx: &mut WindowContext,
1563    ) -> Option<Vec<IndentGuideLayout>> {
1564        let indent_guides = self.editor.update(cx, |editor, cx| {
1565            editor.indent_guides(visible_buffer_range, snapshot, cx)
1566        })?;
1567
1568        let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1569            editor
1570                .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1571                .unwrap_or_default()
1572        });
1573
1574        Some(
1575            indent_guides
1576                .into_iter()
1577                .enumerate()
1578                .filter_map(|(i, indent_guide)| {
1579                    let single_indent_width =
1580                        self.column_pixels(indent_guide.tab_size as usize, cx);
1581                    let total_width = single_indent_width * indent_guide.depth as f32;
1582                    let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1583                    if start_x >= text_origin.x {
1584                        let (offset_y, length) = Self::calculate_indent_guide_bounds(
1585                            indent_guide.multibuffer_row_range.clone(),
1586                            line_height,
1587                            snapshot,
1588                        );
1589
1590                        let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1591
1592                        Some(IndentGuideLayout {
1593                            origin: point(start_x, start_y),
1594                            length,
1595                            single_indent_width,
1596                            depth: indent_guide.depth,
1597                            active: active_indent_guide_indices.contains(&i),
1598                            settings: indent_guide.settings,
1599                        })
1600                    } else {
1601                        None
1602                    }
1603                })
1604                .collect(),
1605        )
1606    }
1607
1608    fn calculate_indent_guide_bounds(
1609        row_range: Range<MultiBufferRow>,
1610        line_height: Pixels,
1611        snapshot: &DisplaySnapshot,
1612    ) -> (gpui::Pixels, gpui::Pixels) {
1613        let start_point = Point::new(row_range.start.0, 0);
1614        let end_point = Point::new(row_range.end.0, 0);
1615
1616        let row_range = start_point.to_display_point(snapshot).row()
1617            ..end_point.to_display_point(snapshot).row();
1618
1619        let mut prev_line = start_point;
1620        prev_line.row = prev_line.row.saturating_sub(1);
1621        let prev_line = prev_line.to_display_point(snapshot).row();
1622
1623        let mut cons_line = end_point;
1624        cons_line.row += 1;
1625        let cons_line = cons_line.to_display_point(snapshot).row();
1626
1627        let mut offset_y = row_range.start.0 as f32 * line_height;
1628        let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1629
1630        // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1631        if row_range.end == cons_line {
1632            length += line_height;
1633        }
1634
1635        // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1636        // we want to extend the indent guide to the start of the block.
1637        let mut block_height = 0;
1638        let mut block_offset = 0;
1639        let mut found_excerpt_header = false;
1640        for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1641            if matches!(block, Block::ExcerptBoundary { .. }) {
1642                found_excerpt_header = true;
1643                break;
1644            }
1645            block_offset += block.height();
1646            block_height += block.height();
1647        }
1648        if !found_excerpt_header {
1649            offset_y -= block_offset as f32 * line_height;
1650            length += block_height as f32 * line_height;
1651        }
1652
1653        // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1654        // we want to ensure that the indent guide stops before the excerpt header.
1655        let mut block_height = 0;
1656        let mut found_excerpt_header = false;
1657        for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1658            if matches!(block, Block::ExcerptBoundary { .. }) {
1659                found_excerpt_header = true;
1660            }
1661            block_height += block.height();
1662        }
1663        if found_excerpt_header {
1664            length -= block_height as f32 * line_height;
1665        }
1666
1667        (offset_y, length)
1668    }
1669
1670    #[allow(clippy::too_many_arguments)]
1671    fn layout_run_indicators(
1672        &self,
1673        line_height: Pixels,
1674        range: Range<DisplayRow>,
1675        scroll_pixel_position: gpui::Point<Pixels>,
1676        gutter_dimensions: &GutterDimensions,
1677        gutter_hitbox: &Hitbox,
1678        rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1679        snapshot: &EditorSnapshot,
1680        cx: &mut WindowContext,
1681    ) -> Vec<AnyElement> {
1682        self.editor.update(cx, |editor, cx| {
1683            let active_task_indicator_row =
1684                if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1685                    deployed_from_indicator,
1686                    actions,
1687                    ..
1688                })) = editor.context_menu.read().as_ref()
1689                {
1690                    actions
1691                        .tasks
1692                        .as_ref()
1693                        .map(|tasks| tasks.position.to_display_point(snapshot).row())
1694                        .or(*deployed_from_indicator)
1695                } else {
1696                    None
1697                };
1698
1699            let offset_range_start = snapshot
1700                .display_point_to_anchor(DisplayPoint::new(range.start, 0), Bias::Left)
1701                .to_offset(&snapshot.buffer_snapshot);
1702            let offset_range_end = snapshot
1703                .display_point_to_anchor(DisplayPoint::new(range.end, 0), Bias::Right)
1704                .to_offset(&snapshot.buffer_snapshot);
1705
1706            editor
1707                .tasks
1708                .iter()
1709                .filter_map(|(_, tasks)| {
1710                    if tasks.offset.0 < offset_range_start || tasks.offset.0 >= offset_range_end {
1711                        return None;
1712                    }
1713                    let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1714                    let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1715
1716                    if snapshot.is_line_folded(multibuffer_row) {
1717                        // Skip folded indicators, unless it's the starting line of a fold.
1718                        if multibuffer_row
1719                            .0
1720                            .checked_sub(1)
1721                            .map_or(false, |previous_row| {
1722                                snapshot.is_line_folded(MultiBufferRow(previous_row))
1723                            })
1724                        {
1725                            return None;
1726                        }
1727                    }
1728                    let display_row = multibuffer_point.to_display_point(snapshot).row();
1729                    let button = editor.render_run_indicator(
1730                        &self.style,
1731                        Some(display_row) == active_task_indicator_row,
1732                        display_row,
1733                        cx,
1734                    );
1735
1736                    let button = prepaint_gutter_button(
1737                        button,
1738                        display_row,
1739                        line_height,
1740                        gutter_dimensions,
1741                        scroll_pixel_position,
1742                        gutter_hitbox,
1743                        rows_with_hunk_bounds,
1744                        cx,
1745                    );
1746                    Some(button)
1747                })
1748                .collect_vec()
1749        })
1750    }
1751
1752    #[allow(clippy::too_many_arguments)]
1753    fn layout_code_actions_indicator(
1754        &self,
1755        line_height: Pixels,
1756        newest_selection_head: DisplayPoint,
1757        scroll_pixel_position: gpui::Point<Pixels>,
1758        gutter_dimensions: &GutterDimensions,
1759        gutter_hitbox: &Hitbox,
1760        rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1761        cx: &mut WindowContext,
1762    ) -> Option<AnyElement> {
1763        let mut active = false;
1764        let mut button = None;
1765        let row = newest_selection_head.row();
1766        self.editor.update(cx, |editor, cx| {
1767            if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1768                deployed_from_indicator,
1769                ..
1770            })) = editor.context_menu.read().as_ref()
1771            {
1772                active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1773            };
1774            button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1775        });
1776
1777        let button = prepaint_gutter_button(
1778            button?,
1779            row,
1780            line_height,
1781            gutter_dimensions,
1782            scroll_pixel_position,
1783            gutter_hitbox,
1784            rows_with_hunk_bounds,
1785            cx,
1786        );
1787
1788        Some(button)
1789    }
1790
1791    fn get_participant_color(
1792        participant_index: Option<ParticipantIndex>,
1793        cx: &WindowContext,
1794    ) -> PlayerColor {
1795        if let Some(index) = participant_index {
1796            cx.theme().players().color_for_participant(index.0)
1797        } else {
1798            cx.theme().players().absent()
1799        }
1800    }
1801
1802    fn calculate_relative_line_numbers(
1803        &self,
1804        snapshot: &EditorSnapshot,
1805        rows: &Range<DisplayRow>,
1806        relative_to: Option<DisplayRow>,
1807    ) -> HashMap<DisplayRow, DisplayRowDelta> {
1808        let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1809        let Some(relative_to) = relative_to else {
1810            return relative_rows;
1811        };
1812
1813        let start = rows.start.min(relative_to);
1814        let end = rows.end.max(relative_to);
1815
1816        let buffer_rows = snapshot
1817            .buffer_rows(start)
1818            .take(1 + end.minus(start) as usize)
1819            .collect::<Vec<_>>();
1820
1821        let head_idx = relative_to.minus(start);
1822        let mut delta = 1;
1823        let mut i = head_idx + 1;
1824        while i < buffer_rows.len() as u32 {
1825            if buffer_rows[i as usize].is_some() {
1826                if rows.contains(&DisplayRow(i + start.0)) {
1827                    relative_rows.insert(DisplayRow(i + start.0), delta);
1828                }
1829                delta += 1;
1830            }
1831            i += 1;
1832        }
1833        delta = 1;
1834        i = head_idx.min(buffer_rows.len() as u32 - 1);
1835        while i > 0 && buffer_rows[i as usize].is_none() {
1836            i -= 1;
1837        }
1838
1839        while i > 0 {
1840            i -= 1;
1841            if buffer_rows[i as usize].is_some() {
1842                if rows.contains(&DisplayRow(i + start.0)) {
1843                    relative_rows.insert(DisplayRow(i + start.0), delta);
1844                }
1845                delta += 1;
1846            }
1847        }
1848
1849        relative_rows
1850    }
1851
1852    fn layout_line_numbers(
1853        &self,
1854        rows: Range<DisplayRow>,
1855        buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1856        active_rows: &BTreeMap<DisplayRow, bool>,
1857        newest_selection_head: Option<DisplayPoint>,
1858        snapshot: &EditorSnapshot,
1859        cx: &mut WindowContext,
1860    ) -> Vec<Option<ShapedLine>> {
1861        let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1862            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1863        });
1864        if !include_line_numbers {
1865            return Vec::new();
1866        }
1867
1868        let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
1869            let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1870                let newest = editor.selections.newest::<Point>(cx);
1871                SelectionLayout::new(
1872                    newest,
1873                    editor.selections.line_mode,
1874                    editor.cursor_shape,
1875                    &snapshot.display_snapshot,
1876                    true,
1877                    true,
1878                    None,
1879                )
1880                .head
1881            });
1882            let is_relative = editor.should_use_relative_line_numbers(cx);
1883            (newest_selection_head, is_relative)
1884        });
1885        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1886
1887        let relative_to = if is_relative {
1888            Some(newest_selection_head.row())
1889        } else {
1890            None
1891        };
1892        let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1893        let mut line_number = String::new();
1894        buffer_rows
1895            .into_iter()
1896            .enumerate()
1897            .map(|(ix, multibuffer_row)| {
1898                let multibuffer_row = multibuffer_row?;
1899                let display_row = DisplayRow(rows.start.0 + ix as u32);
1900                let color = if active_rows.contains_key(&display_row) {
1901                    cx.theme().colors().editor_active_line_number
1902                } else {
1903                    cx.theme().colors().editor_line_number
1904                };
1905                line_number.clear();
1906                let default_number = multibuffer_row.0 + 1;
1907                let number = relative_rows
1908                    .get(&DisplayRow(ix as u32 + rows.start.0))
1909                    .unwrap_or(&default_number);
1910                write!(&mut line_number, "{number}").unwrap();
1911                let run = TextRun {
1912                    len: line_number.len(),
1913                    font: self.style.text.font(),
1914                    color,
1915                    background_color: None,
1916                    underline: None,
1917                    strikethrough: None,
1918                };
1919                let shaped_line = cx
1920                    .text_system()
1921                    .shape_line(line_number.clone().into(), font_size, &[run])
1922                    .unwrap();
1923                Some(shaped_line)
1924            })
1925            .collect()
1926    }
1927
1928    fn layout_crease_toggles(
1929        &self,
1930        rows: Range<DisplayRow>,
1931        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1932        active_rows: &BTreeMap<DisplayRow, bool>,
1933        snapshot: &EditorSnapshot,
1934        cx: &mut WindowContext,
1935    ) -> Vec<Option<AnyElement>> {
1936        let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1937            && snapshot.mode == EditorMode::Full
1938            && self.editor.read(cx).is_singleton(cx);
1939        if include_fold_statuses {
1940            buffer_rows
1941                .into_iter()
1942                .enumerate()
1943                .map(|(ix, row)| {
1944                    if let Some(multibuffer_row) = row {
1945                        let display_row = DisplayRow(rows.start.0 + ix as u32);
1946                        let active = active_rows.contains_key(&display_row);
1947                        snapshot.render_crease_toggle(
1948                            multibuffer_row,
1949                            active,
1950                            self.editor.clone(),
1951                            cx,
1952                        )
1953                    } else {
1954                        None
1955                    }
1956                })
1957                .collect()
1958        } else {
1959            Vec::new()
1960        }
1961    }
1962
1963    fn layout_crease_trailers(
1964        &self,
1965        buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1966        snapshot: &EditorSnapshot,
1967        cx: &mut WindowContext,
1968    ) -> Vec<Option<AnyElement>> {
1969        buffer_rows
1970            .into_iter()
1971            .map(|row| {
1972                if let Some(multibuffer_row) = row {
1973                    snapshot.render_crease_trailer(multibuffer_row, cx)
1974                } else {
1975                    None
1976                }
1977            })
1978            .collect()
1979    }
1980
1981    fn layout_lines(
1982        rows: Range<DisplayRow>,
1983        snapshot: &EditorSnapshot,
1984        style: &EditorStyle,
1985        editor_width: Pixels,
1986        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
1987        cx: &mut WindowContext,
1988    ) -> Vec<LineWithInvisibles> {
1989        if rows.start >= rows.end {
1990            return Vec::new();
1991        }
1992
1993        // Show the placeholder when the editor is empty
1994        if snapshot.is_empty() {
1995            let font_size = style.text.font_size.to_pixels(cx.rem_size());
1996            let placeholder_color = cx.theme().colors().text_placeholder;
1997            let placeholder_text = snapshot.placeholder_text();
1998
1999            let placeholder_lines = placeholder_text
2000                .as_ref()
2001                .map_or("", AsRef::as_ref)
2002                .split('\n')
2003                .skip(rows.start.0 as usize)
2004                .chain(iter::repeat(""))
2005                .take(rows.len());
2006            placeholder_lines
2007                .filter_map(move |line| {
2008                    let run = TextRun {
2009                        len: line.len(),
2010                        font: style.text.font(),
2011                        color: placeholder_color,
2012                        background_color: None,
2013                        underline: Default::default(),
2014                        strikethrough: None,
2015                    };
2016                    cx.text_system()
2017                        .shape_line(line.to_string().into(), font_size, &[run])
2018                        .log_err()
2019                })
2020                .map(|line| LineWithInvisibles {
2021                    width: line.width,
2022                    len: line.len,
2023                    fragments: smallvec![LineFragment::Text(line)],
2024                    invisibles: Vec::new(),
2025                    font_size,
2026                })
2027                .collect()
2028        } else {
2029            let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
2030            LineWithInvisibles::from_chunks(
2031                chunks,
2032                &style,
2033                MAX_LINE_LEN,
2034                rows.len(),
2035                snapshot.mode,
2036                editor_width,
2037                is_row_soft_wrapped,
2038                cx,
2039            )
2040        }
2041    }
2042
2043    fn prepaint_lines(
2044        &self,
2045        start_row: DisplayRow,
2046        line_layouts: &mut [LineWithInvisibles],
2047        line_height: Pixels,
2048        scroll_pixel_position: gpui::Point<Pixels>,
2049        content_origin: gpui::Point<Pixels>,
2050        cx: &mut WindowContext,
2051    ) -> SmallVec<[AnyElement; 1]> {
2052        let mut line_elements = SmallVec::new();
2053        for (ix, line) in line_layouts.iter_mut().enumerate() {
2054            let row = start_row + DisplayRow(ix as u32);
2055            line.prepaint(
2056                line_height,
2057                scroll_pixel_position,
2058                row,
2059                content_origin,
2060                &mut line_elements,
2061                cx,
2062            );
2063        }
2064        line_elements
2065    }
2066
2067    #[allow(clippy::too_many_arguments)]
2068    fn render_block(
2069        &self,
2070        block: &Block,
2071        available_width: AvailableSpace,
2072        block_id: BlockId,
2073        block_row_start: DisplayRow,
2074        snapshot: &EditorSnapshot,
2075        text_x: Pixels,
2076        rows: &Range<DisplayRow>,
2077        line_layouts: &[LineWithInvisibles],
2078        gutter_dimensions: &GutterDimensions,
2079        line_height: Pixels,
2080        em_width: Pixels,
2081        text_hitbox: &Hitbox,
2082        editor_width: Pixels,
2083        scroll_width: &mut Pixels,
2084        resized_blocks: &mut HashMap<CustomBlockId, u32>,
2085        selections: &[Selection<Point>],
2086        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2087        cx: &mut WindowContext,
2088    ) -> (AnyElement, Size<Pixels>) {
2089        let mut element = match block {
2090            Block::Custom(block) => {
2091                let block_start = block.start().to_point(&snapshot.buffer_snapshot);
2092                let block_end = block.end().to_point(&snapshot.buffer_snapshot);
2093                let align_to = block_start.to_display_point(snapshot);
2094                let anchor_x = text_x
2095                    + if rows.contains(&align_to.row()) {
2096                        line_layouts[align_to.row().minus(rows.start) as usize]
2097                            .x_for_index(align_to.column() as usize)
2098                    } else {
2099                        layout_line(
2100                            align_to.row(),
2101                            snapshot,
2102                            &self.style,
2103                            editor_width,
2104                            is_row_soft_wrapped,
2105                            cx,
2106                        )
2107                        .x_for_index(align_to.column() as usize)
2108                    };
2109
2110                let selected = selections
2111                    .binary_search_by(|selection| {
2112                        if selection.end <= block_start {
2113                            Ordering::Less
2114                        } else if selection.start >= block_end {
2115                            Ordering::Greater
2116                        } else {
2117                            Ordering::Equal
2118                        }
2119                    })
2120                    .is_ok();
2121
2122                div()
2123                    .size_full()
2124                    .child(block.render(&mut BlockContext {
2125                        context: cx,
2126                        anchor_x,
2127                        gutter_dimensions,
2128                        line_height,
2129                        em_width,
2130                        block_id,
2131                        selected,
2132                        max_width: text_hitbox.size.width.max(*scroll_width),
2133                        editor_style: &self.style,
2134                    }))
2135                    .into_any()
2136            }
2137
2138            Block::ExcerptBoundary {
2139                prev_excerpt,
2140                next_excerpt,
2141                show_excerpt_controls,
2142                starts_new_buffer,
2143                height,
2144                ..
2145            } => {
2146                let icon_offset = gutter_dimensions.width
2147                    - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2148
2149                let header_padding = px(6.0);
2150
2151                let mut result = v_flex().id(block_id).w_full();
2152
2153                if let Some(prev_excerpt) = prev_excerpt {
2154                    if *show_excerpt_controls {
2155                        result = result.child(
2156                            h_flex()
2157                                .w(icon_offset)
2158                                .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2159                                .flex_none()
2160                                .justify_end()
2161                                .child(self.render_expand_excerpt_button(
2162                                    prev_excerpt.id,
2163                                    ExpandExcerptDirection::Down,
2164                                    IconName::ArrowDownFromLine,
2165                                    cx,
2166                                )),
2167                        );
2168                    }
2169                }
2170
2171                if let Some(next_excerpt) = next_excerpt {
2172                    let buffer = &next_excerpt.buffer;
2173                    let range = &next_excerpt.range;
2174                    let jump_data = {
2175                        let jump_path =
2176                            project::File::from_dyn(buffer.file()).map(|file| ProjectPath {
2177                                worktree_id: file.worktree_id(cx),
2178                                path: file.path.clone(),
2179                            });
2180                        let jump_anchor = range
2181                            .primary
2182                            .as_ref()
2183                            .map_or(range.context.start, |primary| primary.start);
2184
2185                        let excerpt_start = range.context.start;
2186                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2187                        let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2188                            0
2189                        } else {
2190                            let excerpt_start_row =
2191                                language::ToPoint::to_point(&jump_anchor, buffer).row;
2192                            jump_position.row - excerpt_start_row
2193                        };
2194                        let line_offset_from_top =
2195                            block_row_start.0 + *height + offset_from_excerpt_start
2196                                - snapshot
2197                                    .scroll_anchor
2198                                    .scroll_position(&snapshot.display_snapshot)
2199                                    .y as u32;
2200                        JumpData {
2201                            excerpt_id: next_excerpt.id,
2202                            anchor: jump_anchor,
2203                            position: language::ToPoint::to_point(&jump_anchor, buffer),
2204                            path: jump_path,
2205                            line_offset_from_top,
2206                        }
2207                    };
2208
2209                    if *starts_new_buffer {
2210                        let include_root = self
2211                            .editor
2212                            .read(cx)
2213                            .project
2214                            .as_ref()
2215                            .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2216                            .unwrap_or_default();
2217                        let path = buffer.resolve_file_path(cx, include_root);
2218                        let filename = path
2219                            .as_ref()
2220                            .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2221                        let parent_path = path.as_ref().and_then(|path| {
2222                            Some(path.parent()?.to_string_lossy().to_string() + "/")
2223                        });
2224
2225                        result = result.child(
2226                            div()
2227                                .px(header_padding)
2228                                .pt(header_padding)
2229                                .w_full()
2230                                .h(FILE_HEADER_HEIGHT as f32 * cx.line_height())
2231                                .child(
2232                                    h_flex()
2233                                        .id("path header block")
2234                                        .size_full()
2235                                        .flex_basis(Length::Definite(DefiniteLength::Fraction(
2236                                            0.667,
2237                                        )))
2238                                        .px(gpui::px(12.))
2239                                        .rounded_md()
2240                                        .shadow_md()
2241                                        .border_1()
2242                                        .border_color(cx.theme().colors().border)
2243                                        .bg(cx.theme().colors().editor_subheader_background)
2244                                        .justify_between()
2245                                        .hover(|style| style.bg(cx.theme().colors().element_hover))
2246                                        .child(
2247                                            h_flex().gap_3().child(
2248                                                h_flex()
2249                                                    .gap_2()
2250                                                    .child(
2251                                                        filename
2252                                                            .map(SharedString::from)
2253                                                            .unwrap_or_else(|| "untitled".into()),
2254                                                    )
2255                                                    .when_some(parent_path, |then, path| {
2256                                                        then.child(div().child(path).text_color(
2257                                                            cx.theme().colors().text_muted,
2258                                                        ))
2259                                                    }),
2260                                            ),
2261                                        )
2262                                        .child(Icon::new(IconName::ArrowUpRight))
2263                                        .cursor_pointer()
2264                                        .tooltip(|cx| {
2265                                            Tooltip::for_action("Jump to File", &OpenExcerpts, cx)
2266                                        })
2267                                        .on_mouse_down(MouseButton::Left, |_, cx| {
2268                                            cx.stop_propagation()
2269                                        })
2270                                        .on_click(cx.listener_for(&self.editor, {
2271                                            move |editor, e: &ClickEvent, cx| {
2272                                                editor.open_excerpts_common(
2273                                                    Some(jump_data.clone()),
2274                                                    e.down.modifiers.secondary(),
2275                                                    cx,
2276                                                );
2277                                            }
2278                                        })),
2279                                ),
2280                        );
2281                        if *show_excerpt_controls {
2282                            result = result.child(
2283                                h_flex()
2284                                    .w(icon_offset)
2285                                    .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2286                                    .flex_none()
2287                                    .justify_end()
2288                                    .child(self.render_expand_excerpt_button(
2289                                        next_excerpt.id,
2290                                        ExpandExcerptDirection::Up,
2291                                        IconName::ArrowUpFromLine,
2292                                        cx,
2293                                    )),
2294                            );
2295                        }
2296                    } else {
2297                        let editor = self.editor.clone();
2298                        result = result.child(
2299                            h_flex()
2300                                .id("excerpt header block")
2301                                .group("excerpt-jump-action")
2302                                .justify_start()
2303                                .w_full()
2304                                .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * cx.line_height())
2305                                .relative()
2306                                .child(
2307                                    div()
2308                                        .top(px(0.))
2309                                        .absolute()
2310                                        .w_full()
2311                                        .h_px()
2312                                        .bg(cx.theme().colors().border_variant)
2313                                        .group_hover("excerpt-jump-action", |style| {
2314                                            style.bg(cx.theme().colors().border)
2315                                        }),
2316                                )
2317                                .cursor_pointer()
2318                                .on_click({
2319                                    let jump_data = jump_data.clone();
2320                                    cx.listener_for(&self.editor, {
2321                                        let jump_data = jump_data.clone();
2322                                        move |editor, e: &ClickEvent, cx| {
2323                                            cx.stop_propagation();
2324                                            editor.open_excerpts_common(
2325                                                Some(jump_data.clone()),
2326                                                e.down.modifiers.secondary(),
2327                                                cx,
2328                                            );
2329                                        }
2330                                    })
2331                                })
2332                                .tooltip({
2333                                    let jump_data = jump_data.clone();
2334                                    move |cx| {
2335                                        let jump_message = format!(
2336                                            "Jump to {}:L{}",
2337                                            match &jump_data.path {
2338                                                Some(project_path) =>
2339                                                    project_path.path.display().to_string(),
2340                                                None => {
2341                                                    let editor = editor.read(cx);
2342                                                    editor
2343                                                        .file_at(jump_data.position, cx)
2344                                                        .map(|file| {
2345                                                            file.full_path(cx).display().to_string()
2346                                                        })
2347                                                        .or_else(|| {
2348                                                            Some(
2349                                                                editor
2350                                                                    .tab_description(0, cx)?
2351                                                                    .to_string(),
2352                                                            )
2353                                                        })
2354                                                        .unwrap_or_else(|| {
2355                                                            "Unknown buffer".to_string()
2356                                                        })
2357                                                }
2358                                            },
2359                                            jump_data.position.row + 1
2360                                        );
2361                                        Tooltip::for_action(jump_message, &OpenExcerpts, cx)
2362                                    }
2363                                })
2364                                .child(
2365                                    h_flex()
2366                                        .w(icon_offset)
2367                                        .h(MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32
2368                                            * cx.line_height())
2369                                        .flex_none()
2370                                        .justify_end()
2371                                        .child(if *show_excerpt_controls {
2372                                            self.render_expand_excerpt_button(
2373                                                next_excerpt.id,
2374                                                ExpandExcerptDirection::Up,
2375                                                IconName::ArrowUpFromLine,
2376                                                cx,
2377                                            )
2378                                        } else {
2379                                            ButtonLike::new("jump-icon")
2380                                                .style(ButtonStyle::Transparent)
2381                                                .child(
2382                                                    svg()
2383                                                        .path(IconName::ArrowUpRight.path())
2384                                                        .size(IconSize::XSmall.rems())
2385                                                        .text_color(
2386                                                            cx.theme().colors().border_variant,
2387                                                        )
2388                                                        .group_hover(
2389                                                            "excerpt-jump-action",
2390                                                            |style| {
2391                                                                style.text_color(
2392                                                                    cx.theme().colors().border,
2393                                                                )
2394                                                            },
2395                                                        ),
2396                                                )
2397                                        }),
2398                                ),
2399                        );
2400                    }
2401                }
2402
2403                result.into_any()
2404            }
2405        };
2406
2407        // Discover the element's content height, then round up to the nearest multiple of line height.
2408        let preliminary_size =
2409            element.layout_as_root(size(available_width, AvailableSpace::MinContent), cx);
2410        let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2411        let final_size = if preliminary_size.height == quantized_height {
2412            preliminary_size
2413        } else {
2414            element.layout_as_root(size(available_width, quantized_height.into()), cx)
2415        };
2416
2417        if let BlockId::Custom(custom_block_id) = block_id {
2418            if block.height() > 0 {
2419                let element_height_in_lines =
2420                    ((final_size.height / line_height).ceil() as u32).max(1);
2421                if element_height_in_lines != block.height() {
2422                    resized_blocks.insert(custom_block_id, element_height_in_lines);
2423                }
2424            }
2425        }
2426
2427        (element, final_size)
2428    }
2429
2430    fn render_expand_excerpt_button(
2431        &self,
2432        excerpt_id: ExcerptId,
2433        direction: ExpandExcerptDirection,
2434        icon: IconName,
2435        cx: &mut WindowContext,
2436    ) -> ButtonLike {
2437        ButtonLike::new("expand-icon")
2438            .style(ButtonStyle::Transparent)
2439            .child(
2440                svg()
2441                    .path(icon.path())
2442                    .size(IconSize::XSmall.rems())
2443                    .text_color(cx.theme().colors().editor_line_number)
2444                    .group("")
2445                    .hover(|style| style.text_color(cx.theme().colors().editor_active_line_number)),
2446            )
2447            .on_click(cx.listener_for(&self.editor, {
2448                move |editor, _, cx| {
2449                    editor.expand_excerpt(excerpt_id, direction, cx);
2450                }
2451            }))
2452            .tooltip({
2453                move |cx| Tooltip::for_action("Expand Excerpt", &ExpandExcerpts { lines: 0 }, cx)
2454            })
2455    }
2456
2457    #[allow(clippy::too_many_arguments)]
2458    fn render_blocks(
2459        &self,
2460        rows: Range<DisplayRow>,
2461        snapshot: &EditorSnapshot,
2462        hitbox: &Hitbox,
2463        text_hitbox: &Hitbox,
2464        editor_width: Pixels,
2465        scroll_width: &mut Pixels,
2466        gutter_dimensions: &GutterDimensions,
2467        em_width: Pixels,
2468        text_x: Pixels,
2469        line_height: Pixels,
2470        line_layouts: &[LineWithInvisibles],
2471        selections: &[Selection<Point>],
2472        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2473        cx: &mut WindowContext,
2474    ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2475        let (fixed_blocks, non_fixed_blocks) = snapshot
2476            .blocks_in_range(rows.clone())
2477            .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2478
2479        let mut focused_block = self
2480            .editor
2481            .update(cx, |editor, _| editor.take_focused_block());
2482        let mut fixed_block_max_width = Pixels::ZERO;
2483        let mut blocks = Vec::new();
2484        let mut resized_blocks = HashMap::default();
2485
2486        for (row, block) in fixed_blocks {
2487            let block_id = block.id();
2488
2489            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2490                focused_block = None;
2491            }
2492
2493            let (element, element_size) = self.render_block(
2494                block,
2495                AvailableSpace::MinContent,
2496                block_id,
2497                row,
2498                snapshot,
2499                text_x,
2500                &rows,
2501                line_layouts,
2502                gutter_dimensions,
2503                line_height,
2504                em_width,
2505                text_hitbox,
2506                editor_width,
2507                scroll_width,
2508                &mut resized_blocks,
2509                selections,
2510                is_row_soft_wrapped,
2511                cx,
2512            );
2513            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2514            blocks.push(BlockLayout {
2515                id: block_id,
2516                row: Some(row),
2517                element,
2518                available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2519                style: BlockStyle::Fixed,
2520            });
2521        }
2522        for (row, block) in non_fixed_blocks {
2523            let style = block.style();
2524            let width = match style {
2525                BlockStyle::Sticky => hitbox.size.width,
2526                BlockStyle::Flex => hitbox
2527                    .size
2528                    .width
2529                    .max(fixed_block_max_width)
2530                    .max(gutter_dimensions.width + *scroll_width),
2531                BlockStyle::Fixed => unreachable!(),
2532            };
2533            let block_id = block.id();
2534
2535            if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2536                focused_block = None;
2537            }
2538
2539            let (element, element_size) = self.render_block(
2540                block,
2541                width.into(),
2542                block_id,
2543                row,
2544                snapshot,
2545                text_x,
2546                &rows,
2547                line_layouts,
2548                gutter_dimensions,
2549                line_height,
2550                em_width,
2551                text_hitbox,
2552                editor_width,
2553                scroll_width,
2554                &mut resized_blocks,
2555                selections,
2556                is_row_soft_wrapped,
2557                cx,
2558            );
2559
2560            blocks.push(BlockLayout {
2561                id: block_id,
2562                row: Some(row),
2563                element,
2564                available_space: size(width.into(), element_size.height.into()),
2565                style,
2566            });
2567        }
2568
2569        if let Some(focused_block) = focused_block {
2570            if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2571                if focus_handle.is_focused(cx) {
2572                    if let Some(block) = snapshot.block_for_id(focused_block.id) {
2573                        let style = block.style();
2574                        let width = match style {
2575                            BlockStyle::Fixed => AvailableSpace::MinContent,
2576                            BlockStyle::Flex => AvailableSpace::Definite(
2577                                hitbox
2578                                    .size
2579                                    .width
2580                                    .max(fixed_block_max_width)
2581                                    .max(gutter_dimensions.width + *scroll_width),
2582                            ),
2583                            BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2584                        };
2585
2586                        let (element, element_size) = self.render_block(
2587                            &block,
2588                            width,
2589                            focused_block.id,
2590                            rows.end,
2591                            snapshot,
2592                            text_x,
2593                            &rows,
2594                            line_layouts,
2595                            gutter_dimensions,
2596                            line_height,
2597                            em_width,
2598                            text_hitbox,
2599                            editor_width,
2600                            scroll_width,
2601                            &mut resized_blocks,
2602                            selections,
2603                            is_row_soft_wrapped,
2604                            cx,
2605                        );
2606
2607                        blocks.push(BlockLayout {
2608                            id: block.id(),
2609                            row: None,
2610                            element,
2611                            available_space: size(width, element_size.height.into()),
2612                            style,
2613                        });
2614                    }
2615                }
2616            }
2617        }
2618
2619        if resized_blocks.is_empty() {
2620            *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2621            Ok(blocks)
2622        } else {
2623            Err(resized_blocks)
2624        }
2625    }
2626
2627    /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2628    /// a restart of rendering for the editor based on the new sizes.
2629    fn layout_blocks(
2630        &self,
2631        blocks: &mut Vec<BlockLayout>,
2632        block_starts: &mut HashSet<DisplayRow>,
2633        hitbox: &Hitbox,
2634        line_height: Pixels,
2635        scroll_pixel_position: gpui::Point<Pixels>,
2636        cx: &mut WindowContext,
2637    ) {
2638        for block in blocks {
2639            let mut origin = if let Some(row) = block.row {
2640                block_starts.insert(row);
2641                hitbox.origin
2642                    + point(
2643                        Pixels::ZERO,
2644                        row.as_f32() * line_height - scroll_pixel_position.y,
2645                    )
2646            } else {
2647                // Position the block outside the visible area
2648                hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2649            };
2650
2651            if !matches!(block.style, BlockStyle::Sticky) {
2652                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2653            }
2654
2655            let focus_handle = block
2656                .element
2657                .prepaint_as_root(origin, block.available_space, cx);
2658
2659            if let Some(focus_handle) = focus_handle {
2660                self.editor.update(cx, |editor, _cx| {
2661                    editor.set_focused_block(FocusedBlock {
2662                        id: block.id,
2663                        focus_handle: focus_handle.downgrade(),
2664                    });
2665                });
2666            }
2667        }
2668    }
2669
2670    #[allow(clippy::too_many_arguments)]
2671    fn layout_context_menu(
2672        &self,
2673        line_height: Pixels,
2674        hitbox: &Hitbox,
2675        text_hitbox: &Hitbox,
2676        content_origin: gpui::Point<Pixels>,
2677        start_row: DisplayRow,
2678        scroll_pixel_position: gpui::Point<Pixels>,
2679        line_layouts: &[LineWithInvisibles],
2680        newest_selection_head: DisplayPoint,
2681        gutter_overshoot: Pixels,
2682        cx: &mut WindowContext,
2683    ) -> bool {
2684        let max_height = cmp::min(
2685            12. * line_height,
2686            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2687        );
2688        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2689            if editor.context_menu_visible() {
2690                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2691            } else {
2692                None
2693            }
2694        }) else {
2695            return false;
2696        };
2697
2698        let context_menu_size = context_menu.layout_as_root(AvailableSpace::min_size(), cx);
2699
2700        let (x, y) = match position {
2701            crate::ContextMenuOrigin::EditorPoint(point) => {
2702                let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2703                let x = cursor_row_layout.x_for_index(point.column() as usize)
2704                    - scroll_pixel_position.x;
2705                let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2706                (x, y)
2707            }
2708            crate::ContextMenuOrigin::GutterIndicator(row) => {
2709                // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
2710                // text field.
2711                let x = -gutter_overshoot;
2712                let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2713                (x, y)
2714            }
2715        };
2716
2717        let mut list_origin = content_origin + point(x, y);
2718        let list_width = context_menu_size.width;
2719        let list_height = context_menu_size.height;
2720
2721        // Snap the right edge of the list to the right edge of the window if
2722        // its horizontal bounds overflow.
2723        if list_origin.x + list_width > cx.viewport_size().width {
2724            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2725        }
2726
2727        if list_origin.y + list_height > text_hitbox.lower_right().y {
2728            list_origin.y -= line_height + list_height;
2729        }
2730
2731        cx.defer_draw(context_menu, list_origin, 1);
2732        true
2733    }
2734
2735    #[allow(clippy::too_many_arguments)]
2736    fn layout_inline_completion_popover(
2737        &self,
2738        text_bounds: &Bounds<Pixels>,
2739        editor_snapshot: &EditorSnapshot,
2740        visible_row_range: Range<DisplayRow>,
2741        scroll_top: f32,
2742        scroll_bottom: f32,
2743        line_layouts: &[LineWithInvisibles],
2744        line_height: Pixels,
2745        scroll_pixel_position: gpui::Point<Pixels>,
2746        editor_width: Pixels,
2747        style: &EditorStyle,
2748        cx: &mut WindowContext,
2749    ) -> Option<AnyElement> {
2750        const PADDING_X: Pixels = Pixels(25.);
2751        const PADDING_Y: Pixels = Pixels(2.);
2752
2753        let active_inline_completion = self.editor.read(cx).active_inline_completion.as_ref()?;
2754
2755        match &active_inline_completion.completion {
2756            InlineCompletion::Move(target_position) => {
2757                let container_element = div()
2758                    .bg(cx.theme().colors().editor_background)
2759                    .border_1()
2760                    .border_color(cx.theme().colors().border)
2761                    .rounded_md()
2762                    .px_1();
2763
2764                let target_display_point = target_position.to_display_point(editor_snapshot);
2765                if target_display_point.row().as_f32() < scroll_top {
2766                    let mut element = container_element
2767                        .child(
2768                            h_flex()
2769                                .gap_1()
2770                                .child(Icon::new(IconName::Tab))
2771                                .child(Label::new("Jump to Edit"))
2772                                .child(Icon::new(IconName::ArrowUp)),
2773                        )
2774                        .into_any();
2775                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2776                    let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
2777                    element.prepaint_at(text_bounds.origin + offset, cx);
2778                    Some(element)
2779                } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
2780                    let mut element = container_element
2781                        .child(
2782                            h_flex()
2783                                .gap_1()
2784                                .child(Icon::new(IconName::Tab))
2785                                .child(Label::new("Jump to Edit"))
2786                                .child(Icon::new(IconName::ArrowDown)),
2787                        )
2788                        .into_any();
2789                    let size = element.layout_as_root(AvailableSpace::min_size(), cx);
2790                    let offset = point(
2791                        (text_bounds.size.width - size.width) / 2.,
2792                        text_bounds.size.height - size.height - PADDING_Y,
2793                    );
2794                    element.prepaint_at(text_bounds.origin + offset, cx);
2795                    Some(element)
2796                } else {
2797                    let mut element = container_element
2798                        .child(
2799                            h_flex()
2800                                .gap_1()
2801                                .child(Icon::new(IconName::Tab))
2802                                .child(Label::new("Jump to Edit")),
2803                        )
2804                        .into_any();
2805
2806                    let target_line_end = DisplayPoint::new(
2807                        target_display_point.row(),
2808                        editor_snapshot.line_len(target_display_point.row()),
2809                    );
2810                    let origin = self.editor.update(cx, |editor, cx| {
2811                        editor.display_to_pixel_point(target_line_end, editor_snapshot, cx)
2812                    })?;
2813                    element.prepaint_as_root(
2814                        text_bounds.origin + origin + point(PADDING_X, px(0.)),
2815                        AvailableSpace::min_size(),
2816                        cx,
2817                    );
2818                    Some(element)
2819                }
2820            }
2821            InlineCompletion::Edit(edits) => {
2822                let edit_start = edits
2823                    .first()
2824                    .unwrap()
2825                    .0
2826                    .start
2827                    .to_display_point(editor_snapshot);
2828                let edit_end = edits
2829                    .last()
2830                    .unwrap()
2831                    .0
2832                    .end
2833                    .to_display_point(editor_snapshot);
2834
2835                let is_visible = visible_row_range.contains(&edit_start.row())
2836                    || visible_row_range.contains(&edit_end.row());
2837                if !is_visible {
2838                    return None;
2839                }
2840
2841                if all_edits_insertions_or_deletions(edits, &editor_snapshot.buffer_snapshot) {
2842                    return None;
2843                }
2844
2845                let (text, highlights) = inline_completion_popover_text(editor_snapshot, edits, cx);
2846
2847                let longest_row =
2848                    editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
2849                let longest_line_width = if visible_row_range.contains(&longest_row) {
2850                    line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
2851                } else {
2852                    layout_line(
2853                        longest_row,
2854                        editor_snapshot,
2855                        style,
2856                        editor_width,
2857                        |_| false,
2858                        cx,
2859                    )
2860                    .width
2861                };
2862
2863                let text = gpui::StyledText::new(text).with_highlights(&style.text, highlights);
2864
2865                let mut element = div()
2866                    .bg(cx.theme().colors().editor_background)
2867                    .border_1()
2868                    .border_color(cx.theme().colors().border)
2869                    .rounded_md()
2870                    .px_1()
2871                    .child(text)
2872                    .into_any();
2873
2874                let origin = text_bounds.origin
2875                    + point(
2876                        longest_line_width + PADDING_X - scroll_pixel_position.x,
2877                        edit_start.row().as_f32() * line_height - scroll_pixel_position.y,
2878                    );
2879                element.prepaint_as_root(origin, AvailableSpace::min_size(), cx);
2880                Some(element)
2881            }
2882        }
2883    }
2884
2885    fn layout_mouse_context_menu(
2886        &self,
2887        editor_snapshot: &EditorSnapshot,
2888        visible_range: Range<DisplayRow>,
2889        content_origin: gpui::Point<Pixels>,
2890        cx: &mut WindowContext,
2891    ) -> Option<AnyElement> {
2892        let position = self.editor.update(cx, |editor, cx| {
2893            let visible_start_point = editor.display_to_pixel_point(
2894                DisplayPoint::new(visible_range.start, 0),
2895                editor_snapshot,
2896                cx,
2897            )?;
2898            let visible_end_point = editor.display_to_pixel_point(
2899                DisplayPoint::new(visible_range.end, 0),
2900                editor_snapshot,
2901                cx,
2902            )?;
2903
2904            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2905            let (source_display_point, position) = match mouse_context_menu.position {
2906                MenuPosition::PinnedToScreen(point) => (None, point),
2907                MenuPosition::PinnedToEditor { source, offset } => {
2908                    let source_display_point = source.to_display_point(editor_snapshot);
2909                    let source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2910                    let position = content_origin + source_point + offset;
2911                    (Some(source_display_point), position)
2912                }
2913            };
2914
2915            let source_included = source_display_point.map_or(true, |source_display_point| {
2916                visible_range
2917                    .to_inclusive()
2918                    .contains(&source_display_point.row())
2919            });
2920            let position_included =
2921                visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2922            if !source_included && !position_included {
2923                None
2924            } else {
2925                Some(position)
2926            }
2927        })?;
2928
2929        let mut element = self.editor.update(cx, |editor, _| {
2930            let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2931            let context_menu = mouse_context_menu.context_menu.clone();
2932
2933            Some(
2934                deferred(
2935                    anchored()
2936                        .position(position)
2937                        .child(context_menu)
2938                        .anchor(AnchorCorner::TopLeft)
2939                        .snap_to_window_with_margin(px(8.)),
2940                )
2941                .with_priority(1)
2942                .into_any(),
2943            )
2944        })?;
2945
2946        element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
2947        Some(element)
2948    }
2949
2950    #[allow(clippy::too_many_arguments)]
2951    fn layout_hover_popovers(
2952        &self,
2953        snapshot: &EditorSnapshot,
2954        hitbox: &Hitbox,
2955        text_hitbox: &Hitbox,
2956        visible_display_row_range: Range<DisplayRow>,
2957        content_origin: gpui::Point<Pixels>,
2958        scroll_pixel_position: gpui::Point<Pixels>,
2959        line_layouts: &[LineWithInvisibles],
2960        line_height: Pixels,
2961        em_width: Pixels,
2962        cx: &mut WindowContext,
2963    ) {
2964        struct MeasuredHoverPopover {
2965            element: AnyElement,
2966            size: Size<Pixels>,
2967            horizontal_offset: Pixels,
2968        }
2969
2970        let max_size = size(
2971            (120. * em_width) // Default size
2972                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2973                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2974            (16. * line_height) // Default size
2975                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2976                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2977        );
2978
2979        let hover_popovers = self.editor.update(cx, |editor, cx| {
2980            editor
2981                .hover_state
2982                .render(snapshot, visible_display_row_range.clone(), max_size, cx)
2983        });
2984        let Some((position, hover_popovers)) = hover_popovers else {
2985            return;
2986        };
2987
2988        // This is safe because we check on layout whether the required row is available
2989        let hovered_row_layout =
2990            &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2991
2992        // Compute Hovered Point
2993        let x =
2994            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2995        let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2996        let hovered_point = content_origin + point(x, y);
2997
2998        let mut overall_height = Pixels::ZERO;
2999        let mut measured_hover_popovers = Vec::new();
3000        for mut hover_popover in hover_popovers {
3001            let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
3002            let horizontal_offset =
3003                (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3004
3005            overall_height += HOVER_POPOVER_GAP + size.height;
3006
3007            measured_hover_popovers.push(MeasuredHoverPopover {
3008                element: hover_popover,
3009                size,
3010                horizontal_offset,
3011            });
3012        }
3013        overall_height += HOVER_POPOVER_GAP;
3014
3015        fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
3016            let mut occlusion = div()
3017                .size_full()
3018                .occlude()
3019                .on_mouse_move(|_, cx| cx.stop_propagation())
3020                .into_any_element();
3021            occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
3022            cx.defer_draw(occlusion, origin, 2);
3023        }
3024
3025        if hovered_point.y > overall_height {
3026            // There is enough space above. Render popovers above the hovered point
3027            let mut current_y = hovered_point.y;
3028            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3029                let size = popover.size;
3030                let popover_origin = point(
3031                    hovered_point.x + popover.horizontal_offset,
3032                    current_y - size.height,
3033                );
3034
3035                cx.defer_draw(popover.element, popover_origin, 2);
3036                if position != itertools::Position::Last {
3037                    let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3038                    draw_occluder(size.width, origin, cx);
3039                }
3040
3041                current_y = popover_origin.y - HOVER_POPOVER_GAP;
3042            }
3043        } else {
3044            // There is not enough space above. Render popovers below the hovered point
3045            let mut current_y = hovered_point.y + line_height;
3046            for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3047                let size = popover.size;
3048                let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3049
3050                cx.defer_draw(popover.element, popover_origin, 2);
3051                if position != itertools::Position::Last {
3052                    let origin = point(popover_origin.x, popover_origin.y + size.height);
3053                    draw_occluder(size.width, origin, cx);
3054                }
3055
3056                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3057            }
3058        }
3059    }
3060
3061    #[allow(clippy::too_many_arguments)]
3062    fn layout_signature_help(
3063        &self,
3064        hitbox: &Hitbox,
3065        content_origin: gpui::Point<Pixels>,
3066        scroll_pixel_position: gpui::Point<Pixels>,
3067        newest_selection_head: Option<DisplayPoint>,
3068        start_row: DisplayRow,
3069        line_layouts: &[LineWithInvisibles],
3070        line_height: Pixels,
3071        em_width: Pixels,
3072        cx: &mut WindowContext,
3073    ) {
3074        if !self.editor.focus_handle(cx).is_focused(cx) {
3075            return;
3076        }
3077        let Some(newest_selection_head) = newest_selection_head else {
3078            return;
3079        };
3080        let selection_row = newest_selection_head.row();
3081        if selection_row < start_row {
3082            return;
3083        }
3084        let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
3085        else {
3086            return;
3087        };
3088
3089        let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
3090            - scroll_pixel_position.x
3091            + content_origin.x;
3092        let start_y =
3093            selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
3094
3095        let max_size = size(
3096            (120. * em_width) // Default size
3097                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3098                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3099            (16. * line_height) // Default size
3100                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3101                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3102        );
3103
3104        let maybe_element = self.editor.update(cx, |editor, cx| {
3105            if let Some(popover) = editor.signature_help_state.popover_mut() {
3106                let element = popover.render(
3107                    &self.style,
3108                    max_size,
3109                    editor.workspace.as_ref().map(|(w, _)| w.clone()),
3110                    cx,
3111                );
3112                Some(element)
3113            } else {
3114                None
3115            }
3116        });
3117        if let Some(mut element) = maybe_element {
3118            let window_size = cx.viewport_size();
3119            let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
3120            let mut point = point(start_x, start_y - size.height);
3121
3122            // Adjusting to ensure the popover does not overflow in the X-axis direction.
3123            if point.x + size.width >= window_size.width {
3124                point.x = window_size.width - size.width;
3125            }
3126
3127            cx.defer_draw(element, point, 1)
3128        }
3129    }
3130
3131    fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
3132        cx.paint_layer(layout.hitbox.bounds, |cx| {
3133            let scroll_top = layout.position_map.snapshot.scroll_position().y;
3134            let gutter_bg = cx.theme().colors().editor_gutter_background;
3135            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
3136            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
3137
3138            if let EditorMode::Full = layout.mode {
3139                let mut active_rows = layout.active_rows.iter().peekable();
3140                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
3141                    let mut end_row = start_row.0;
3142                    while active_rows
3143                        .peek()
3144                        .map_or(false, |(active_row, has_selection)| {
3145                            active_row.0 == end_row + 1
3146                                && *has_selection == contains_non_empty_selection
3147                        })
3148                    {
3149                        active_rows.next().unwrap();
3150                        end_row += 1;
3151                    }
3152
3153                    if !contains_non_empty_selection {
3154                        let highlight_h_range =
3155                            match layout.position_map.snapshot.current_line_highlight {
3156                                CurrentLineHighlight::Gutter => Some(Range {
3157                                    start: layout.hitbox.left(),
3158                                    end: layout.gutter_hitbox.right(),
3159                                }),
3160                                CurrentLineHighlight::Line => Some(Range {
3161                                    start: layout.text_hitbox.bounds.left(),
3162                                    end: layout.text_hitbox.bounds.right(),
3163                                }),
3164                                CurrentLineHighlight::All => Some(Range {
3165                                    start: layout.hitbox.left(),
3166                                    end: layout.hitbox.right(),
3167                                }),
3168                                CurrentLineHighlight::None => None,
3169                            };
3170                        if let Some(range) = highlight_h_range {
3171                            let active_line_bg = cx.theme().colors().editor_active_line_background;
3172                            let bounds = Bounds {
3173                                origin: point(
3174                                    range.start,
3175                                    layout.hitbox.origin.y
3176                                        + (start_row.as_f32() - scroll_top)
3177                                            * layout.position_map.line_height,
3178                                ),
3179                                size: size(
3180                                    range.end - range.start,
3181                                    layout.position_map.line_height
3182                                        * (end_row - start_row.0 + 1) as f32,
3183                                ),
3184                            };
3185                            cx.paint_quad(fill(bounds, active_line_bg));
3186                        }
3187                    }
3188                }
3189
3190                let mut paint_highlight =
3191                    |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3192                        let origin = point(
3193                            layout.hitbox.origin.x,
3194                            layout.hitbox.origin.y
3195                                + (highlight_row_start.as_f32() - scroll_top)
3196                                    * layout.position_map.line_height,
3197                        );
3198                        let size = size(
3199                            layout.hitbox.size.width,
3200                            layout.position_map.line_height
3201                                * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3202                        );
3203                        cx.paint_quad(fill(Bounds { origin, size }, color));
3204                    };
3205
3206                let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3207                for (&new_row, &new_color) in &layout.highlighted_rows {
3208                    match &mut current_paint {
3209                        Some((current_color, current_range)) => {
3210                            let current_color = *current_color;
3211                            let new_range_started = current_color != new_color
3212                                || current_range.end.next_row() != new_row;
3213                            if new_range_started {
3214                                paint_highlight(
3215                                    current_range.start,
3216                                    current_range.end,
3217                                    current_color,
3218                                );
3219                                current_paint = Some((new_color, new_row..new_row));
3220                                continue;
3221                            } else {
3222                                current_range.end = current_range.end.next_row();
3223                            }
3224                        }
3225                        None => current_paint = Some((new_color, new_row..new_row)),
3226                    };
3227                }
3228                if let Some((color, range)) = current_paint {
3229                    paint_highlight(range.start, range.end, color);
3230                }
3231
3232                let scroll_left =
3233                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3234
3235                for (wrap_position, active) in layout.wrap_guides.iter() {
3236                    let x = (layout.text_hitbox.origin.x
3237                        + *wrap_position
3238                        + layout.position_map.em_width / 2.)
3239                        - scroll_left;
3240
3241                    let show_scrollbars = layout
3242                        .scrollbar_layout
3243                        .as_ref()
3244                        .map_or(false, |scrollbar| scrollbar.visible);
3245                    if x < layout.text_hitbox.origin.x
3246                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3247                    {
3248                        continue;
3249                    }
3250
3251                    let color = if *active {
3252                        cx.theme().colors().editor_active_wrap_guide
3253                    } else {
3254                        cx.theme().colors().editor_wrap_guide
3255                    };
3256                    cx.paint_quad(fill(
3257                        Bounds {
3258                            origin: point(x, layout.text_hitbox.origin.y),
3259                            size: size(px(1.), layout.text_hitbox.size.height),
3260                        },
3261                        color,
3262                    ));
3263                }
3264            }
3265        })
3266    }
3267
3268    fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3269        let Some(indent_guides) = &layout.indent_guides else {
3270            return;
3271        };
3272
3273        let faded_color = |color: Hsla, alpha: f32| {
3274            let mut faded = color;
3275            faded.a = alpha;
3276            faded
3277        };
3278
3279        for indent_guide in indent_guides {
3280            let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3281            let settings = indent_guide.settings;
3282
3283            // TODO fixed for now, expose them through themes later
3284            const INDENT_AWARE_ALPHA: f32 = 0.2;
3285            const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3286            const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3287            const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3288
3289            let line_color = match (settings.coloring, indent_guide.active) {
3290                (IndentGuideColoring::Disabled, _) => None,
3291                (IndentGuideColoring::Fixed, false) => {
3292                    Some(cx.theme().colors().editor_indent_guide)
3293                }
3294                (IndentGuideColoring::Fixed, true) => {
3295                    Some(cx.theme().colors().editor_indent_guide_active)
3296                }
3297                (IndentGuideColoring::IndentAware, false) => {
3298                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3299                }
3300                (IndentGuideColoring::IndentAware, true) => {
3301                    Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3302                }
3303            };
3304
3305            let background_color = match (settings.background_coloring, indent_guide.active) {
3306                (IndentGuideBackgroundColoring::Disabled, _) => None,
3307                (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3308                    indent_accent_colors,
3309                    INDENT_AWARE_BACKGROUND_ALPHA,
3310                )),
3311                (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3312                    indent_accent_colors,
3313                    INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3314                )),
3315            };
3316
3317            let requested_line_width = if indent_guide.active {
3318                settings.active_line_width
3319            } else {
3320                settings.line_width
3321            }
3322            .clamp(1, 10);
3323            let mut line_indicator_width = 0.;
3324            if let Some(color) = line_color {
3325                cx.paint_quad(fill(
3326                    Bounds {
3327                        origin: indent_guide.origin,
3328                        size: size(px(requested_line_width as f32), indent_guide.length),
3329                    },
3330                    color,
3331                ));
3332                line_indicator_width = requested_line_width as f32;
3333            }
3334
3335            if let Some(color) = background_color {
3336                let width = indent_guide.single_indent_width - px(line_indicator_width);
3337                cx.paint_quad(fill(
3338                    Bounds {
3339                        origin: point(
3340                            indent_guide.origin.x + px(line_indicator_width),
3341                            indent_guide.origin.y,
3342                        ),
3343                        size: size(width, indent_guide.length),
3344                    },
3345                    color,
3346                ));
3347            }
3348        }
3349    }
3350
3351    fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3352        let line_height = layout.position_map.line_height;
3353        let scroll_position = layout.position_map.snapshot.scroll_position();
3354        let scroll_top = scroll_position.y * line_height;
3355
3356        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3357
3358        for (ix, line) in layout.line_numbers.iter().enumerate() {
3359            if let Some(line) = line {
3360                let line_origin = layout.gutter_hitbox.origin
3361                    + point(
3362                        layout.gutter_hitbox.size.width
3363                            - line.width
3364                            - layout.gutter_dimensions.right_padding,
3365                        ix as f32 * line_height - (scroll_top % line_height),
3366                    );
3367
3368                line.paint(line_origin, line_height, cx).log_err();
3369            }
3370        }
3371    }
3372
3373    fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3374        if layout.display_hunks.is_empty() {
3375            return;
3376        }
3377
3378        let line_height = layout.position_map.line_height;
3379        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3380            for (hunk, hitbox) in &layout.display_hunks {
3381                let hunk_to_paint = match hunk {
3382                    DisplayDiffHunk::Folded { .. } => {
3383                        let hunk_bounds = Self::diff_hunk_bounds(
3384                            &layout.position_map.snapshot,
3385                            line_height,
3386                            layout.gutter_hitbox.bounds,
3387                            hunk,
3388                        );
3389                        Some((
3390                            hunk_bounds,
3391                            cx.theme().status().modified,
3392                            Corners::all(px(0.)),
3393                        ))
3394                    }
3395                    DisplayDiffHunk::Unfolded { status, .. } => {
3396                        hitbox.as_ref().map(|hunk_hitbox| match status {
3397                            DiffHunkStatus::Added => (
3398                                hunk_hitbox.bounds,
3399                                cx.theme().status().created,
3400                                Corners::all(px(0.)),
3401                            ),
3402                            DiffHunkStatus::Modified => (
3403                                hunk_hitbox.bounds,
3404                                cx.theme().status().modified,
3405                                Corners::all(px(0.)),
3406                            ),
3407                            DiffHunkStatus::Removed => (
3408                                Bounds::new(
3409                                    point(
3410                                        hunk_hitbox.origin.x - hunk_hitbox.size.width,
3411                                        hunk_hitbox.origin.y,
3412                                    ),
3413                                    size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3414                                ),
3415                                cx.theme().status().deleted,
3416                                Corners::all(1. * line_height),
3417                            ),
3418                        })
3419                    }
3420                };
3421
3422                if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3423                    cx.paint_quad(quad(
3424                        hunk_bounds,
3425                        corner_radii,
3426                        background_color,
3427                        Edges::default(),
3428                        transparent_black(),
3429                    ));
3430                }
3431            }
3432        });
3433    }
3434
3435    pub(super) fn diff_hunk_bounds(
3436        snapshot: &EditorSnapshot,
3437        line_height: Pixels,
3438        gutter_bounds: Bounds<Pixels>,
3439        hunk: &DisplayDiffHunk,
3440    ) -> Bounds<Pixels> {
3441        let scroll_position = snapshot.scroll_position();
3442        let scroll_top = scroll_position.y * line_height;
3443
3444        match hunk {
3445            DisplayDiffHunk::Folded { display_row, .. } => {
3446                let start_y = display_row.as_f32() * line_height - scroll_top;
3447                let end_y = start_y + line_height;
3448
3449                let width = Self::diff_hunk_strip_width(line_height);
3450                let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3451                let highlight_size = size(width, end_y - start_y);
3452                Bounds::new(highlight_origin, highlight_size)
3453            }
3454            DisplayDiffHunk::Unfolded {
3455                display_row_range,
3456                status,
3457                ..
3458            } => match status {
3459                DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3460                    let start_row = display_row_range.start;
3461                    let end_row = display_row_range.end;
3462                    // If we're in a multibuffer, row range span might include an
3463                    // excerpt header, so if we were to draw the marker straight away,
3464                    // the hunk might include the rows of that header.
3465                    // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3466                    // Instead, we simply check whether the range we're dealing with includes
3467                    // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3468                    let end_row_in_current_excerpt = snapshot
3469                        .blocks_in_range(start_row..end_row)
3470                        .find_map(|(start_row, block)| {
3471                            if matches!(block, Block::ExcerptBoundary { .. }) {
3472                                Some(start_row)
3473                            } else {
3474                                None
3475                            }
3476                        })
3477                        .unwrap_or(end_row);
3478
3479                    let start_y = start_row.as_f32() * line_height - scroll_top;
3480                    let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3481
3482                    let width = Self::diff_hunk_strip_width(line_height);
3483                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3484                    let highlight_size = size(width, end_y - start_y);
3485                    Bounds::new(highlight_origin, highlight_size)
3486                }
3487                DiffHunkStatus::Removed => {
3488                    let row = display_row_range.start;
3489
3490                    let offset = line_height / 2.;
3491                    let start_y = row.as_f32() * line_height - offset - scroll_top;
3492                    let end_y = start_y + line_height;
3493
3494                    let width = (0.35 * line_height).floor();
3495                    let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3496                    let highlight_size = size(width, end_y - start_y);
3497                    Bounds::new(highlight_origin, highlight_size)
3498                }
3499            },
3500        }
3501    }
3502
3503    /// Returns the width of the diff strip that will be displayed in the gutter.
3504    pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3505        // We floor the value to prevent pixel rounding.
3506        (0.275 * line_height).floor()
3507    }
3508
3509    fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3510        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3511            cx.with_element_namespace("crease_toggles", |cx| {
3512                for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
3513                    crease_toggle.paint(cx);
3514                }
3515            });
3516
3517            for test_indicator in layout.test_indicators.iter_mut() {
3518                test_indicator.paint(cx);
3519            }
3520
3521            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3522                indicator.paint(cx);
3523            }
3524        });
3525    }
3526
3527    fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3528        for (_, hunk_hitbox) in &layout.display_hunks {
3529            if let Some(hunk_hitbox) = hunk_hitbox {
3530                cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3531            }
3532        }
3533
3534        let show_git_gutter = layout
3535            .position_map
3536            .snapshot
3537            .show_git_diff_gutter
3538            .unwrap_or_else(|| {
3539                matches!(
3540                    ProjectSettings::get_global(cx).git.git_gutter,
3541                    Some(GitGutterSetting::TrackedFiles)
3542                )
3543            });
3544        if show_git_gutter {
3545            Self::paint_diff_hunks(layout, cx)
3546        }
3547
3548        let highlight_width = 0.275 * layout.position_map.line_height;
3549        let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3550        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3551            for (range, color) in &layout.highlighted_gutter_ranges {
3552                let start_row = if range.start.row() < layout.visible_display_row_range.start {
3553                    layout.visible_display_row_range.start - DisplayRow(1)
3554                } else {
3555                    range.start.row()
3556                };
3557                let end_row = if range.end.row() > layout.visible_display_row_range.end {
3558                    layout.visible_display_row_range.end + DisplayRow(1)
3559                } else {
3560                    range.end.row()
3561                };
3562
3563                let start_y = layout.gutter_hitbox.top()
3564                    + start_row.0 as f32 * layout.position_map.line_height
3565                    - layout.position_map.scroll_pixel_position.y;
3566                let end_y = layout.gutter_hitbox.top()
3567                    + (end_row.0 + 1) as f32 * layout.position_map.line_height
3568                    - layout.position_map.scroll_pixel_position.y;
3569                let bounds = Bounds::from_corners(
3570                    point(layout.gutter_hitbox.left(), start_y),
3571                    point(layout.gutter_hitbox.left() + highlight_width, end_y),
3572                );
3573                cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3574            }
3575        });
3576    }
3577
3578    fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3579        let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3580            return;
3581        };
3582
3583        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3584            for mut blame_element in blamed_display_rows.into_iter() {
3585                blame_element.paint(cx);
3586            }
3587        })
3588    }
3589
3590    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3591        cx.with_content_mask(
3592            Some(ContentMask {
3593                bounds: layout.text_hitbox.bounds,
3594            }),
3595            |cx| {
3596                let cursor_style = if self
3597                    .editor
3598                    .read(cx)
3599                    .hovered_link_state
3600                    .as_ref()
3601                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3602                {
3603                    CursorStyle::PointingHand
3604                } else {
3605                    CursorStyle::IBeam
3606                };
3607                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3608
3609                let invisible_display_ranges = self.paint_highlights(layout, cx);
3610                self.paint_lines(&invisible_display_ranges, layout, cx);
3611                self.paint_redactions(layout, cx);
3612                self.paint_cursors(layout, cx);
3613                self.paint_inline_blame(layout, cx);
3614                cx.with_element_namespace("crease_trailers", |cx| {
3615                    for trailer in layout.crease_trailers.iter_mut().flatten() {
3616                        trailer.element.paint(cx);
3617                    }
3618                });
3619            },
3620        )
3621    }
3622
3623    fn paint_highlights(
3624        &mut self,
3625        layout: &mut EditorLayout,
3626        cx: &mut WindowContext,
3627    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3628        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3629            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3630            let line_end_overshoot = 0.15 * layout.position_map.line_height;
3631            for (range, color) in &layout.highlighted_ranges {
3632                self.paint_highlighted_range(
3633                    range.clone(),
3634                    *color,
3635                    Pixels::ZERO,
3636                    line_end_overshoot,
3637                    layout,
3638                    cx,
3639                );
3640            }
3641
3642            let corner_radius = 0.15 * layout.position_map.line_height;
3643
3644            for (player_color, selections) in &layout.selections {
3645                for selection in selections.iter() {
3646                    self.paint_highlighted_range(
3647                        selection.range.clone(),
3648                        player_color.selection,
3649                        corner_radius,
3650                        corner_radius * 2.,
3651                        layout,
3652                        cx,
3653                    );
3654
3655                    if selection.is_local && !selection.range.is_empty() {
3656                        invisible_display_ranges.push(selection.range.clone());
3657                    }
3658                }
3659            }
3660            invisible_display_ranges
3661        })
3662    }
3663
3664    fn paint_lines(
3665        &mut self,
3666        invisible_display_ranges: &[Range<DisplayPoint>],
3667        layout: &mut EditorLayout,
3668        cx: &mut WindowContext,
3669    ) {
3670        let whitespace_setting = self
3671            .editor
3672            .read(cx)
3673            .buffer
3674            .read(cx)
3675            .settings_at(0, cx)
3676            .show_whitespaces;
3677
3678        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3679            let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3680            line_with_invisibles.draw(
3681                layout,
3682                row,
3683                layout.content_origin,
3684                whitespace_setting,
3685                invisible_display_ranges,
3686                cx,
3687            )
3688        }
3689
3690        for line_element in &mut layout.line_elements {
3691            line_element.paint(cx);
3692        }
3693    }
3694
3695    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3696        if layout.redacted_ranges.is_empty() {
3697            return;
3698        }
3699
3700        let line_end_overshoot = layout.line_end_overshoot();
3701
3702        // A softer than perfect black
3703        let redaction_color = gpui::rgb(0x0e1111);
3704
3705        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3706            for range in layout.redacted_ranges.iter() {
3707                self.paint_highlighted_range(
3708                    range.clone(),
3709                    redaction_color.into(),
3710                    Pixels::ZERO,
3711                    line_end_overshoot,
3712                    layout,
3713                    cx,
3714                );
3715            }
3716        });
3717    }
3718
3719    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3720        for cursor in &mut layout.visible_cursors {
3721            cursor.paint(layout.content_origin, cx);
3722        }
3723    }
3724
3725    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3726        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3727            return;
3728        };
3729
3730        let thumb_bounds = scrollbar_layout.thumb_bounds();
3731        if scrollbar_layout.visible {
3732            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3733                cx.paint_quad(quad(
3734                    scrollbar_layout.hitbox.bounds,
3735                    Corners::default(),
3736                    cx.theme().colors().scrollbar_track_background,
3737                    Edges {
3738                        top: Pixels::ZERO,
3739                        right: Pixels::ZERO,
3740                        bottom: Pixels::ZERO,
3741                        left: ScrollbarLayout::BORDER_WIDTH,
3742                    },
3743                    cx.theme().colors().scrollbar_track_border,
3744                ));
3745
3746                let fast_markers =
3747                    self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3748                // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3749                self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3750
3751                let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3752                for marker in markers.iter().chain(&fast_markers) {
3753                    let mut marker = marker.clone();
3754                    marker.bounds.origin += scrollbar_layout.hitbox.origin;
3755                    cx.paint_quad(marker);
3756                }
3757
3758                cx.paint_quad(quad(
3759                    thumb_bounds,
3760                    Corners::default(),
3761                    cx.theme().colors().scrollbar_thumb_background,
3762                    Edges {
3763                        top: Pixels::ZERO,
3764                        right: Pixels::ZERO,
3765                        bottom: Pixels::ZERO,
3766                        left: ScrollbarLayout::BORDER_WIDTH,
3767                    },
3768                    cx.theme().colors().scrollbar_thumb_border,
3769                ));
3770            });
3771        }
3772
3773        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3774
3775        let row_height = scrollbar_layout.row_height;
3776        let row_range = scrollbar_layout.visible_row_range.clone();
3777
3778        cx.on_mouse_event({
3779            let editor = self.editor.clone();
3780            let hitbox = scrollbar_layout.hitbox.clone();
3781            let mut mouse_position = cx.mouse_position();
3782            move |event: &MouseMoveEvent, phase, cx| {
3783                if phase == DispatchPhase::Capture {
3784                    return;
3785                }
3786
3787                editor.update(cx, |editor, cx| {
3788                    if event.pressed_button == Some(MouseButton::Left)
3789                        && editor.scroll_manager.is_dragging_scrollbar()
3790                    {
3791                        let y = mouse_position.y;
3792                        let new_y = event.position.y;
3793                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
3794                            let mut position = editor.scroll_position(cx);
3795                            position.y += (new_y - y) / row_height;
3796                            if position.y < 0.0 {
3797                                position.y = 0.0;
3798                            }
3799                            editor.set_scroll_position(position, cx);
3800                        }
3801
3802                        cx.stop_propagation();
3803                    } else {
3804                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3805                        if hitbox.is_hovered(cx) {
3806                            editor.scroll_manager.show_scrollbar(cx);
3807                        }
3808                    }
3809                    mouse_position = event.position;
3810                })
3811            }
3812        });
3813
3814        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3815            cx.on_mouse_event({
3816                let editor = self.editor.clone();
3817                move |_: &MouseUpEvent, phase, cx| {
3818                    if phase == DispatchPhase::Capture {
3819                        return;
3820                    }
3821
3822                    editor.update(cx, |editor, cx| {
3823                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3824                        cx.stop_propagation();
3825                    });
3826                }
3827            });
3828        } else {
3829            cx.on_mouse_event({
3830                let editor = self.editor.clone();
3831                let hitbox = scrollbar_layout.hitbox.clone();
3832                move |event: &MouseDownEvent, phase, cx| {
3833                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3834                        return;
3835                    }
3836
3837                    editor.update(cx, |editor, cx| {
3838                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3839
3840                        let y = event.position.y;
3841                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3842                            let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3843                            let top_row = center_row
3844                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3845                            let mut position = editor.scroll_position(cx);
3846                            position.y = top_row as f32;
3847                            editor.set_scroll_position(position, cx);
3848                        } else {
3849                            editor.scroll_manager.show_scrollbar(cx);
3850                        }
3851
3852                        cx.stop_propagation();
3853                    });
3854                }
3855            });
3856        }
3857    }
3858
3859    fn collect_fast_scrollbar_markers(
3860        &self,
3861        layout: &EditorLayout,
3862        scrollbar_layout: &ScrollbarLayout,
3863        cx: &mut WindowContext,
3864    ) -> Vec<PaintQuad> {
3865        const LIMIT: usize = 100;
3866        if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3867            return vec![];
3868        }
3869        let cursor_ranges = layout
3870            .cursors
3871            .iter()
3872            .map(|(point, color)| ColoredRange {
3873                start: point.row(),
3874                end: point.row(),
3875                color: *color,
3876            })
3877            .collect_vec();
3878        scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3879    }
3880
3881    fn refresh_slow_scrollbar_markers(
3882        &self,
3883        layout: &EditorLayout,
3884        scrollbar_layout: &ScrollbarLayout,
3885        cx: &mut WindowContext,
3886    ) {
3887        self.editor.update(cx, |editor, cx| {
3888            if !editor.is_singleton(cx)
3889                || !editor
3890                    .scrollbar_marker_state
3891                    .should_refresh(scrollbar_layout.hitbox.size)
3892            {
3893                return;
3894            }
3895
3896            let scrollbar_layout = scrollbar_layout.clone();
3897            let background_highlights = editor.background_highlights.clone();
3898            let snapshot = layout.position_map.snapshot.clone();
3899            let theme = cx.theme().clone();
3900            let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3901
3902            editor.scrollbar_marker_state.dirty = false;
3903            editor.scrollbar_marker_state.pending_refresh =
3904                Some(cx.spawn(|editor, mut cx| async move {
3905                    let scrollbar_size = scrollbar_layout.hitbox.size;
3906                    let scrollbar_markers = cx
3907                        .background_executor()
3908                        .spawn(async move {
3909                            let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3910                            let mut marker_quads = Vec::new();
3911                            if scrollbar_settings.git_diff {
3912                                let marker_row_ranges = snapshot
3913                                    .diff_map
3914                                    .diff_hunks(&snapshot.buffer_snapshot)
3915                                    .map(|hunk| {
3916                                        let start_display_row =
3917                                            MultiBufferPoint::new(hunk.row_range.start.0, 0)
3918                                                .to_display_point(&snapshot.display_snapshot)
3919                                                .row();
3920                                        let mut end_display_row =
3921                                            MultiBufferPoint::new(hunk.row_range.end.0, 0)
3922                                                .to_display_point(&snapshot.display_snapshot)
3923                                                .row();
3924                                        if end_display_row != start_display_row {
3925                                            end_display_row.0 -= 1;
3926                                        }
3927                                        let color = match hunk_status(&hunk) {
3928                                            DiffHunkStatus::Added => theme.status().created,
3929                                            DiffHunkStatus::Modified => theme.status().modified,
3930                                            DiffHunkStatus::Removed => theme.status().deleted,
3931                                        };
3932                                        ColoredRange {
3933                                            start: start_display_row,
3934                                            end: end_display_row,
3935                                            color,
3936                                        }
3937                                    });
3938
3939                                marker_quads.extend(
3940                                    scrollbar_layout
3941                                        .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3942                                );
3943                            }
3944
3945                            for (background_highlight_id, (_, background_ranges)) in
3946                                background_highlights.iter()
3947                            {
3948                                let is_search_highlights = *background_highlight_id
3949                                    == TypeId::of::<BufferSearchHighlights>();
3950                                let is_symbol_occurrences = *background_highlight_id
3951                                    == TypeId::of::<DocumentHighlightRead>()
3952                                    || *background_highlight_id
3953                                        == TypeId::of::<DocumentHighlightWrite>();
3954                                if (is_search_highlights && scrollbar_settings.search_results)
3955                                    || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3956                                {
3957                                    let mut color = theme.status().info;
3958                                    if is_symbol_occurrences {
3959                                        color.fade_out(0.5);
3960                                    }
3961                                    let marker_row_ranges = background_ranges.iter().map(|range| {
3962                                        let display_start = range
3963                                            .start
3964                                            .to_display_point(&snapshot.display_snapshot);
3965                                        let display_end =
3966                                            range.end.to_display_point(&snapshot.display_snapshot);
3967                                        ColoredRange {
3968                                            start: display_start.row(),
3969                                            end: display_end.row(),
3970                                            color,
3971                                        }
3972                                    });
3973                                    marker_quads.extend(
3974                                        scrollbar_layout
3975                                            .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3976                                    );
3977                                }
3978                            }
3979
3980                            if scrollbar_settings.diagnostics {
3981                                let diagnostics = snapshot
3982                                    .buffer_snapshot
3983                                    .diagnostics_in_range::<_, Point>(
3984                                        Point::zero()..max_point,
3985                                        false,
3986                                    )
3987                                    // We want to sort by severity, in order to paint the most severe diagnostics last.
3988                                    .sorted_by_key(|diagnostic| {
3989                                        std::cmp::Reverse(diagnostic.diagnostic.severity)
3990                                    });
3991
3992                                let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3993                                    let start_display = diagnostic
3994                                        .range
3995                                        .start
3996                                        .to_display_point(&snapshot.display_snapshot);
3997                                    let end_display = diagnostic
3998                                        .range
3999                                        .end
4000                                        .to_display_point(&snapshot.display_snapshot);
4001                                    let color = match diagnostic.diagnostic.severity {
4002                                        DiagnosticSeverity::ERROR => theme.status().error,
4003                                        DiagnosticSeverity::WARNING => theme.status().warning,
4004                                        DiagnosticSeverity::INFORMATION => theme.status().info,
4005                                        _ => theme.status().hint,
4006                                    };
4007                                    ColoredRange {
4008                                        start: start_display.row(),
4009                                        end: end_display.row(),
4010                                        color,
4011                                    }
4012                                });
4013                                marker_quads.extend(
4014                                    scrollbar_layout
4015                                        .marker_quads_for_ranges(marker_row_ranges, Some(2)),
4016                                );
4017                            }
4018
4019                            Arc::from(marker_quads)
4020                        })
4021                        .await;
4022
4023                    editor.update(&mut cx, |editor, cx| {
4024                        editor.scrollbar_marker_state.markers = scrollbar_markers;
4025                        editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
4026                        editor.scrollbar_marker_state.pending_refresh = None;
4027                        cx.notify();
4028                    })?;
4029
4030                    Ok(())
4031                }));
4032        });
4033    }
4034
4035    #[allow(clippy::too_many_arguments)]
4036    fn paint_highlighted_range(
4037        &self,
4038        range: Range<DisplayPoint>,
4039        color: Hsla,
4040        corner_radius: Pixels,
4041        line_end_overshoot: Pixels,
4042        layout: &EditorLayout,
4043        cx: &mut WindowContext,
4044    ) {
4045        let start_row = layout.visible_display_row_range.start;
4046        let end_row = layout.visible_display_row_range.end;
4047        if range.start != range.end {
4048            let row_range = if range.end.column() == 0 {
4049                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
4050            } else {
4051                cmp::max(range.start.row(), start_row)
4052                    ..cmp::min(range.end.row().next_row(), end_row)
4053            };
4054
4055            let highlighted_range = HighlightedRange {
4056                color,
4057                line_height: layout.position_map.line_height,
4058                corner_radius,
4059                start_y: layout.content_origin.y
4060                    + row_range.start.as_f32() * layout.position_map.line_height
4061                    - layout.position_map.scroll_pixel_position.y,
4062                lines: row_range
4063                    .iter_rows()
4064                    .map(|row| {
4065                        let line_layout =
4066                            &layout.position_map.line_layouts[row.minus(start_row) as usize];
4067                        HighlightedRangeLine {
4068                            start_x: if row == range.start.row() {
4069                                layout.content_origin.x
4070                                    + line_layout.x_for_index(range.start.column() as usize)
4071                                    - layout.position_map.scroll_pixel_position.x
4072                            } else {
4073                                layout.content_origin.x
4074                                    - layout.position_map.scroll_pixel_position.x
4075                            },
4076                            end_x: if row == range.end.row() {
4077                                layout.content_origin.x
4078                                    + line_layout.x_for_index(range.end.column() as usize)
4079                                    - layout.position_map.scroll_pixel_position.x
4080                            } else {
4081                                layout.content_origin.x + line_layout.width + line_end_overshoot
4082                                    - layout.position_map.scroll_pixel_position.x
4083                            },
4084                        }
4085                    })
4086                    .collect(),
4087            };
4088
4089            highlighted_range.paint(layout.text_hitbox.bounds, cx);
4090        }
4091    }
4092
4093    fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4094        if let Some(mut inline_blame) = layout.inline_blame.take() {
4095            cx.paint_layer(layout.text_hitbox.bounds, |cx| {
4096                inline_blame.paint(cx);
4097            })
4098        }
4099    }
4100
4101    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4102        for mut block in layout.blocks.drain(..) {
4103            block.element.paint(cx);
4104        }
4105    }
4106
4107    fn paint_inline_completion_popover(
4108        &mut self,
4109        layout: &mut EditorLayout,
4110        cx: &mut WindowContext,
4111    ) {
4112        if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
4113            inline_completion_popover.paint(cx);
4114        }
4115    }
4116
4117    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
4118        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
4119            mouse_context_menu.paint(cx);
4120        }
4121    }
4122
4123    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
4124        cx.on_mouse_event({
4125            let position_map = layout.position_map.clone();
4126            let editor = self.editor.clone();
4127            let hitbox = layout.hitbox.clone();
4128            let mut delta = ScrollDelta::default();
4129
4130            // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
4131            // accidentally turn off their scrolling.
4132            let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
4133
4134            move |event: &ScrollWheelEvent, phase, cx| {
4135                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
4136                    delta = delta.coalesce(event.delta);
4137                    editor.update(cx, |editor, cx| {
4138                        let position_map: &PositionMap = &position_map;
4139
4140                        let line_height = position_map.line_height;
4141                        let max_glyph_width = position_map.em_width;
4142                        let (delta, axis) = match delta {
4143                            gpui::ScrollDelta::Pixels(mut pixels) => {
4144                                //Trackpad
4145                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
4146                                (pixels, axis)
4147                            }
4148
4149                            gpui::ScrollDelta::Lines(lines) => {
4150                                //Not trackpad
4151                                let pixels =
4152                                    point(lines.x * max_glyph_width, lines.y * line_height);
4153                                (pixels, None)
4154                            }
4155                        };
4156
4157                        let current_scroll_position = position_map.snapshot.scroll_position();
4158                        let x = (current_scroll_position.x * max_glyph_width
4159                            - (delta.x * scroll_sensitivity))
4160                            / max_glyph_width;
4161                        let y = (current_scroll_position.y * line_height
4162                            - (delta.y * scroll_sensitivity))
4163                            / line_height;
4164                        let mut scroll_position =
4165                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
4166                        let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
4167                        if forbid_vertical_scroll {
4168                            scroll_position.y = current_scroll_position.y;
4169                        }
4170
4171                        if scroll_position != current_scroll_position {
4172                            editor.scroll(scroll_position, axis, cx);
4173                            cx.stop_propagation();
4174                        } else if y < 0. {
4175                            // Due to clamping, we may fail to detect cases of overscroll to the top;
4176                            // We want the scroll manager to get an update in such cases and detect the change of direction
4177                            // on the next frame.
4178                            cx.notify();
4179                        }
4180                    });
4181                }
4182            }
4183        });
4184    }
4185
4186    fn paint_mouse_listeners(
4187        &mut self,
4188        layout: &EditorLayout,
4189        hovered_hunk: Option<HoveredHunk>,
4190        cx: &mut WindowContext,
4191    ) {
4192        self.paint_scroll_wheel_listener(layout, cx);
4193
4194        cx.on_mouse_event({
4195            let position_map = layout.position_map.clone();
4196            let editor = self.editor.clone();
4197            let text_hitbox = layout.text_hitbox.clone();
4198            let gutter_hitbox = layout.gutter_hitbox.clone();
4199
4200            move |event: &MouseDownEvent, phase, cx| {
4201                if phase == DispatchPhase::Bubble {
4202                    match event.button {
4203                        MouseButton::Left => editor.update(cx, |editor, cx| {
4204                            Self::mouse_left_down(
4205                                editor,
4206                                event,
4207                                hovered_hunk.clone(),
4208                                &position_map,
4209                                &text_hitbox,
4210                                &gutter_hitbox,
4211                                cx,
4212                            );
4213                        }),
4214                        MouseButton::Right => editor.update(cx, |editor, cx| {
4215                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4216                        }),
4217                        MouseButton::Middle => editor.update(cx, |editor, cx| {
4218                            Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4219                        }),
4220                        _ => {}
4221                    };
4222                }
4223            }
4224        });
4225
4226        cx.on_mouse_event({
4227            let editor = self.editor.clone();
4228            let position_map = layout.position_map.clone();
4229            let text_hitbox = layout.text_hitbox.clone();
4230
4231            move |event: &MouseUpEvent, phase, cx| {
4232                if phase == DispatchPhase::Bubble {
4233                    editor.update(cx, |editor, cx| {
4234                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4235                    });
4236                }
4237            }
4238        });
4239        cx.on_mouse_event({
4240            let position_map = layout.position_map.clone();
4241            let editor = self.editor.clone();
4242            let text_hitbox = layout.text_hitbox.clone();
4243            let gutter_hitbox = layout.gutter_hitbox.clone();
4244
4245            move |event: &MouseMoveEvent, phase, cx| {
4246                if phase == DispatchPhase::Bubble {
4247                    editor.update(cx, |editor, cx| {
4248                        if editor.hover_state.focused(cx) {
4249                            return;
4250                        }
4251                        if event.pressed_button == Some(MouseButton::Left)
4252                            || event.pressed_button == Some(MouseButton::Middle)
4253                        {
4254                            Self::mouse_dragged(
4255                                editor,
4256                                event,
4257                                &position_map,
4258                                text_hitbox.bounds,
4259                                cx,
4260                            )
4261                        }
4262
4263                        Self::mouse_moved(
4264                            editor,
4265                            event,
4266                            &position_map,
4267                            &text_hitbox,
4268                            &gutter_hitbox,
4269                            cx,
4270                        )
4271                    });
4272                }
4273            }
4274        });
4275    }
4276
4277    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4278        bounds.upper_right().x - self.style.scrollbar_width
4279    }
4280
4281    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4282        let style = &self.style;
4283        let font_size = style.text.font_size.to_pixels(cx.rem_size());
4284        let layout = cx
4285            .text_system()
4286            .shape_line(
4287                SharedString::from(" ".repeat(column)),
4288                font_size,
4289                &[TextRun {
4290                    len: column,
4291                    font: style.text.font(),
4292                    color: Hsla::default(),
4293                    background_color: None,
4294                    underline: None,
4295                    strikethrough: None,
4296                }],
4297            )
4298            .unwrap();
4299
4300        layout.width
4301    }
4302
4303    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4304        let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
4305        self.column_pixels(digit_count, cx)
4306    }
4307}
4308
4309fn inline_completion_popover_text(
4310    editor_snapshot: &EditorSnapshot,
4311    edits: &Vec<(Range<Anchor>, String)>,
4312    cx: &WindowContext,
4313) -> (String, Vec<(Range<usize>, HighlightStyle)>) {
4314    let edit_start = edits
4315        .first()
4316        .unwrap()
4317        .0
4318        .start
4319        .to_display_point(editor_snapshot);
4320
4321    let mut text = String::new();
4322    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
4323    let mut highlights = Vec::new();
4324    for (old_range, new_text) in edits {
4325        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
4326        text.extend(
4327            editor_snapshot
4328                .buffer_snapshot
4329                .chunks(offset..old_offset_range.start, false)
4330                .map(|chunk| chunk.text),
4331        );
4332        offset = old_offset_range.end;
4333
4334        let start = text.len();
4335        text.push_str(new_text);
4336        let end = text.len();
4337        highlights.push((
4338            start..end,
4339            HighlightStyle {
4340                background_color: Some(cx.theme().status().created_background),
4341                ..Default::default()
4342            },
4343        ));
4344    }
4345
4346    let edit_end = edits
4347        .last()
4348        .unwrap()
4349        .0
4350        .end
4351        .to_display_point(editor_snapshot);
4352    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
4353        .to_offset(editor_snapshot, Bias::Right);
4354    text.extend(
4355        editor_snapshot
4356            .buffer_snapshot
4357            .chunks(offset..end_of_line, false)
4358            .map(|chunk| chunk.text),
4359    );
4360
4361    (text, highlights)
4362}
4363
4364fn all_edits_insertions_or_deletions(
4365    edits: &Vec<(Range<Anchor>, String)>,
4366    snapshot: &MultiBufferSnapshot,
4367) -> bool {
4368    let mut all_insertions = true;
4369    let mut all_deletions = true;
4370
4371    for (range, new_text) in edits.iter() {
4372        let range_is_empty = range.to_offset(&snapshot).is_empty();
4373        let text_is_empty = new_text.is_empty();
4374
4375        if range_is_empty != text_is_empty {
4376            if range_is_empty {
4377                all_deletions = false;
4378            } else {
4379                all_insertions = false;
4380            }
4381        } else {
4382            return false;
4383        }
4384
4385        if !all_insertions && !all_deletions {
4386            return false;
4387        }
4388    }
4389    all_insertions || all_deletions
4390}
4391
4392#[allow(clippy::too_many_arguments)]
4393fn prepaint_gutter_button(
4394    button: IconButton,
4395    row: DisplayRow,
4396    line_height: Pixels,
4397    gutter_dimensions: &GutterDimensions,
4398    scroll_pixel_position: gpui::Point<Pixels>,
4399    gutter_hitbox: &Hitbox,
4400    rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4401    cx: &mut WindowContext<'_>,
4402) -> AnyElement {
4403    let mut button = button.into_any_element();
4404    let available_space = size(
4405        AvailableSpace::MinContent,
4406        AvailableSpace::Definite(line_height),
4407    );
4408    let indicator_size = button.layout_as_root(available_space, cx);
4409
4410    let blame_width = gutter_dimensions.git_blame_entries_width;
4411    let gutter_width = rows_with_hunk_bounds
4412        .get(&row)
4413        .map(|bounds| bounds.size.width);
4414    let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4415
4416    let mut x = left_offset;
4417    let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4418        - indicator_size.width
4419        - left_offset;
4420    x += available_width / 2.;
4421
4422    let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4423    y += (line_height - indicator_size.height) / 2.;
4424
4425    button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4426    button
4427}
4428
4429fn render_inline_blame_entry(
4430    blame: &gpui::Model<GitBlame>,
4431    blame_entry: BlameEntry,
4432    style: &EditorStyle,
4433    workspace: Option<WeakView<Workspace>>,
4434    cx: &mut WindowContext<'_>,
4435) -> AnyElement {
4436    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4437
4438    let author = blame_entry.author.as_deref().unwrap_or_default();
4439    let summary_enabled = ProjectSettings::get_global(cx)
4440        .git
4441        .show_inline_commit_summary();
4442
4443    let text = match blame_entry.summary.as_ref() {
4444        Some(summary) if summary_enabled => {
4445            format!("{}, {} - {}", author, relative_timestamp, summary)
4446        }
4447        _ => format!("{}, {}", author, relative_timestamp),
4448    };
4449
4450    let details = blame.read(cx).details_for_entry(&blame_entry);
4451
4452    let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4453
4454    h_flex()
4455        .id("inline-blame")
4456        .w_full()
4457        .font_family(style.text.font().family)
4458        .text_color(cx.theme().status().hint)
4459        .line_height(style.text.line_height)
4460        .child(Icon::new(IconName::FileGit).color(Color::Hint))
4461        .child(text)
4462        .gap_2()
4463        .hoverable_tooltip(move |_| tooltip.clone().into())
4464        .into_any()
4465}
4466
4467fn render_blame_entry(
4468    ix: usize,
4469    blame: &gpui::Model<GitBlame>,
4470    blame_entry: BlameEntry,
4471    style: &EditorStyle,
4472    last_used_color: &mut Option<(PlayerColor, Oid)>,
4473    editor: View<Editor>,
4474    cx: &mut WindowContext<'_>,
4475) -> AnyElement {
4476    let mut sha_color = cx
4477        .theme()
4478        .players()
4479        .color_for_participant(blame_entry.sha.into());
4480    // If the last color we used is the same as the one we get for this line, but
4481    // the commit SHAs are different, then we try again to get a different color.
4482    match *last_used_color {
4483        Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4484            let index: u32 = blame_entry.sha.into();
4485            sha_color = cx.theme().players().color_for_participant(index + 1);
4486        }
4487        _ => {}
4488    };
4489    last_used_color.replace((sha_color, blame_entry.sha));
4490
4491    let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4492
4493    let short_commit_id = blame_entry.sha.display_short();
4494
4495    let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4496    let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4497
4498    let details = blame.read(cx).details_for_entry(&blame_entry);
4499
4500    let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4501
4502    let tooltip = cx.new_view(|_| {
4503        BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4504    });
4505
4506    h_flex()
4507        .w_full()
4508        .justify_between()
4509        .font_family(style.text.font().family)
4510        .line_height(style.text.line_height)
4511        .id(("blame", ix))
4512        .text_color(cx.theme().status().hint)
4513        .pr_2()
4514        .gap_2()
4515        .child(
4516            h_flex()
4517                .items_center()
4518                .gap_2()
4519                .child(div().text_color(sha_color.cursor).child(short_commit_id))
4520                .child(name),
4521        )
4522        .child(relative_timestamp)
4523        .on_mouse_down(MouseButton::Right, {
4524            let blame_entry = blame_entry.clone();
4525            let details = details.clone();
4526            move |event, cx| {
4527                deploy_blame_entry_context_menu(
4528                    &blame_entry,
4529                    details.as_ref(),
4530                    editor.clone(),
4531                    event.position,
4532                    cx,
4533                );
4534            }
4535        })
4536        .hover(|style| style.bg(cx.theme().colors().element_hover))
4537        .when_some(
4538            details.and_then(|details| details.permalink),
4539            |this, url| {
4540                let url = url.clone();
4541                this.cursor_pointer().on_click(move |_, cx| {
4542                    cx.stop_propagation();
4543                    cx.open_url(url.as_str())
4544                })
4545            },
4546        )
4547        .hoverable_tooltip(move |_| tooltip.clone().into())
4548        .into_any()
4549}
4550
4551fn deploy_blame_entry_context_menu(
4552    blame_entry: &BlameEntry,
4553    details: Option<&CommitDetails>,
4554    editor: View<Editor>,
4555    position: gpui::Point<Pixels>,
4556    cx: &mut WindowContext<'_>,
4557) {
4558    let context_menu = ContextMenu::build(cx, move |menu, _| {
4559        let sha = format!("{}", blame_entry.sha);
4560        menu.on_blur_subscription(Subscription::new(|| {}))
4561            .entry("Copy commit SHA", None, move |cx| {
4562                cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4563            })
4564            .when_some(
4565                details.and_then(|details| details.permalink.clone()),
4566                |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4567            )
4568    });
4569
4570    editor.update(cx, move |editor, cx| {
4571        editor.mouse_context_menu = Some(MouseContextMenu::new(
4572            MenuPosition::PinnedToScreen(position),
4573            context_menu,
4574            cx,
4575        ));
4576        cx.notify();
4577    });
4578}
4579
4580#[derive(Debug)]
4581pub(crate) struct LineWithInvisibles {
4582    fragments: SmallVec<[LineFragment; 1]>,
4583    invisibles: Vec<Invisible>,
4584    len: usize,
4585    width: Pixels,
4586    font_size: Pixels,
4587}
4588
4589#[allow(clippy::large_enum_variant)]
4590enum LineFragment {
4591    Text(ShapedLine),
4592    Element {
4593        element: Option<AnyElement>,
4594        size: Size<Pixels>,
4595        len: usize,
4596    },
4597}
4598
4599impl fmt::Debug for LineFragment {
4600    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4601        match self {
4602            LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4603            LineFragment::Element { size, len, .. } => f
4604                .debug_struct("Element")
4605                .field("size", size)
4606                .field("len", len)
4607                .finish(),
4608        }
4609    }
4610}
4611
4612impl LineWithInvisibles {
4613    #[allow(clippy::too_many_arguments)]
4614    fn from_chunks<'a>(
4615        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4616        editor_style: &EditorStyle,
4617        max_line_len: usize,
4618        max_line_count: usize,
4619        editor_mode: EditorMode,
4620        text_width: Pixels,
4621        is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4622        cx: &mut WindowContext,
4623    ) -> Vec<Self> {
4624        let text_style = &editor_style.text;
4625        let mut layouts = Vec::with_capacity(max_line_count);
4626        let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4627        let mut line = String::new();
4628        let mut invisibles = Vec::new();
4629        let mut width = Pixels::ZERO;
4630        let mut len = 0;
4631        let mut styles = Vec::new();
4632        let mut non_whitespace_added = false;
4633        let mut row = 0;
4634        let mut line_exceeded_max_len = false;
4635        let font_size = text_style.font_size.to_pixels(cx.rem_size());
4636
4637        let ellipsis = SharedString::from("");
4638
4639        for highlighted_chunk in chunks.chain([HighlightedChunk {
4640            text: "\n",
4641            style: None,
4642            is_tab: false,
4643            replacement: None,
4644        }]) {
4645            if let Some(replacement) = highlighted_chunk.replacement {
4646                if !line.is_empty() {
4647                    let shaped_line = cx
4648                        .text_system()
4649                        .shape_line(line.clone().into(), font_size, &styles)
4650                        .unwrap();
4651                    width += shaped_line.width;
4652                    len += shaped_line.len;
4653                    fragments.push(LineFragment::Text(shaped_line));
4654                    line.clear();
4655                    styles.clear();
4656                }
4657
4658                match replacement {
4659                    ChunkReplacement::Renderer(renderer) => {
4660                        let available_width = if renderer.constrain_width {
4661                            let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4662                                ellipsis.clone()
4663                            } else {
4664                                SharedString::from(Arc::from(highlighted_chunk.text))
4665                            };
4666                            let shaped_line = cx
4667                                .text_system()
4668                                .shape_line(
4669                                    chunk,
4670                                    font_size,
4671                                    &[text_style.to_run(highlighted_chunk.text.len())],
4672                                )
4673                                .unwrap();
4674                            AvailableSpace::Definite(shaped_line.width)
4675                        } else {
4676                            AvailableSpace::MinContent
4677                        };
4678
4679                        let mut element = (renderer.render)(&mut ChunkRendererContext {
4680                            context: cx,
4681                            max_width: text_width,
4682                        });
4683                        let line_height = text_style.line_height_in_pixels(cx.rem_size());
4684                        let size = element.layout_as_root(
4685                            size(available_width, AvailableSpace::Definite(line_height)),
4686                            cx,
4687                        );
4688
4689                        width += size.width;
4690                        len += highlighted_chunk.text.len();
4691                        fragments.push(LineFragment::Element {
4692                            element: Some(element),
4693                            size,
4694                            len: highlighted_chunk.text.len(),
4695                        });
4696                    }
4697                    ChunkReplacement::Str(x) => {
4698                        let text_style = if let Some(style) = highlighted_chunk.style {
4699                            Cow::Owned(text_style.clone().highlight(style))
4700                        } else {
4701                            Cow::Borrowed(text_style)
4702                        };
4703
4704                        let run = TextRun {
4705                            len: x.len(),
4706                            font: text_style.font(),
4707                            color: text_style.color,
4708                            background_color: text_style.background_color,
4709                            underline: text_style.underline,
4710                            strikethrough: text_style.strikethrough,
4711                        };
4712                        let line_layout = cx
4713                            .text_system()
4714                            .shape_line(x, font_size, &[run])
4715                            .unwrap()
4716                            .with_len(highlighted_chunk.text.len());
4717
4718                        width += line_layout.width;
4719                        len += highlighted_chunk.text.len();
4720                        fragments.push(LineFragment::Text(line_layout))
4721                    }
4722                }
4723            } else {
4724                for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4725                    if ix > 0 {
4726                        let shaped_line = cx
4727                            .text_system()
4728                            .shape_line(line.clone().into(), font_size, &styles)
4729                            .unwrap();
4730                        width += shaped_line.width;
4731                        len += shaped_line.len;
4732                        fragments.push(LineFragment::Text(shaped_line));
4733                        layouts.push(Self {
4734                            width: mem::take(&mut width),
4735                            len: mem::take(&mut len),
4736                            fragments: mem::take(&mut fragments),
4737                            invisibles: std::mem::take(&mut invisibles),
4738                            font_size,
4739                        });
4740
4741                        line.clear();
4742                        styles.clear();
4743                        row += 1;
4744                        line_exceeded_max_len = false;
4745                        non_whitespace_added = false;
4746                        if row == max_line_count {
4747                            return layouts;
4748                        }
4749                    }
4750
4751                    if !line_chunk.is_empty() && !line_exceeded_max_len {
4752                        let text_style = if let Some(style) = highlighted_chunk.style {
4753                            Cow::Owned(text_style.clone().highlight(style))
4754                        } else {
4755                            Cow::Borrowed(text_style)
4756                        };
4757
4758                        if line.len() + line_chunk.len() > max_line_len {
4759                            let mut chunk_len = max_line_len - line.len();
4760                            while !line_chunk.is_char_boundary(chunk_len) {
4761                                chunk_len -= 1;
4762                            }
4763                            line_chunk = &line_chunk[..chunk_len];
4764                            line_exceeded_max_len = true;
4765                        }
4766
4767                        styles.push(TextRun {
4768                            len: line_chunk.len(),
4769                            font: text_style.font(),
4770                            color: text_style.color,
4771                            background_color: text_style.background_color,
4772                            underline: text_style.underline,
4773                            strikethrough: text_style.strikethrough,
4774                        });
4775
4776                        if editor_mode == EditorMode::Full {
4777                            // Line wrap pads its contents with fake whitespaces,
4778                            // avoid printing them
4779                            let is_soft_wrapped = is_row_soft_wrapped(row);
4780                            if highlighted_chunk.is_tab {
4781                                if non_whitespace_added || !is_soft_wrapped {
4782                                    invisibles.push(Invisible::Tab {
4783                                        line_start_offset: line.len(),
4784                                        line_end_offset: line.len() + line_chunk.len(),
4785                                    });
4786                                }
4787                            } else {
4788                                invisibles.extend(
4789                                    line_chunk
4790                                        .bytes()
4791                                        .enumerate()
4792                                        .filter(|(_, line_byte)| {
4793                                            let is_whitespace =
4794                                                (*line_byte as char).is_whitespace();
4795                                            non_whitespace_added |= !is_whitespace;
4796                                            is_whitespace
4797                                                && (non_whitespace_added || !is_soft_wrapped)
4798                                        })
4799                                        .map(|(whitespace_index, _)| Invisible::Whitespace {
4800                                            line_offset: line.len() + whitespace_index,
4801                                        }),
4802                                )
4803                            }
4804                        }
4805
4806                        line.push_str(line_chunk);
4807                    }
4808                }
4809            }
4810        }
4811
4812        layouts
4813    }
4814
4815    fn prepaint(
4816        &mut self,
4817        line_height: Pixels,
4818        scroll_pixel_position: gpui::Point<Pixels>,
4819        row: DisplayRow,
4820        content_origin: gpui::Point<Pixels>,
4821        line_elements: &mut SmallVec<[AnyElement; 1]>,
4822        cx: &mut WindowContext,
4823    ) {
4824        let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4825        let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4826        for fragment in &mut self.fragments {
4827            match fragment {
4828                LineFragment::Text(line) => {
4829                    fragment_origin.x += line.width;
4830                }
4831                LineFragment::Element { element, size, .. } => {
4832                    let mut element = element
4833                        .take()
4834                        .expect("you can't prepaint LineWithInvisibles twice");
4835
4836                    // Center the element vertically within the line.
4837                    let mut element_origin = fragment_origin;
4838                    element_origin.y += (line_height - size.height) / 2.;
4839                    element.prepaint_at(element_origin, cx);
4840                    line_elements.push(element);
4841
4842                    fragment_origin.x += size.width;
4843                }
4844            }
4845        }
4846    }
4847
4848    fn draw(
4849        &self,
4850        layout: &EditorLayout,
4851        row: DisplayRow,
4852        content_origin: gpui::Point<Pixels>,
4853        whitespace_setting: ShowWhitespaceSetting,
4854        selection_ranges: &[Range<DisplayPoint>],
4855        cx: &mut WindowContext,
4856    ) {
4857        let line_height = layout.position_map.line_height;
4858        let line_y = line_height
4859            * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4860
4861        let mut fragment_origin =
4862            content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4863
4864        for fragment in &self.fragments {
4865            match fragment {
4866                LineFragment::Text(line) => {
4867                    line.paint(fragment_origin, line_height, cx).log_err();
4868                    fragment_origin.x += line.width;
4869                }
4870                LineFragment::Element { size, .. } => {
4871                    fragment_origin.x += size.width;
4872                }
4873            }
4874        }
4875
4876        self.draw_invisibles(
4877            selection_ranges,
4878            layout,
4879            content_origin,
4880            line_y,
4881            row,
4882            line_height,
4883            whitespace_setting,
4884            cx,
4885        );
4886    }
4887
4888    #[allow(clippy::too_many_arguments)]
4889    fn draw_invisibles(
4890        &self,
4891        selection_ranges: &[Range<DisplayPoint>],
4892        layout: &EditorLayout,
4893        content_origin: gpui::Point<Pixels>,
4894        line_y: Pixels,
4895        row: DisplayRow,
4896        line_height: Pixels,
4897        whitespace_setting: ShowWhitespaceSetting,
4898        cx: &mut WindowContext,
4899    ) {
4900        let extract_whitespace_info = |invisible: &Invisible| {
4901            let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4902                Invisible::Tab {
4903                    line_start_offset,
4904                    line_end_offset,
4905                } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4906                Invisible::Whitespace { line_offset } => {
4907                    (*line_offset, line_offset + 1, &layout.space_invisible)
4908                }
4909            };
4910
4911            let x_offset = self.x_for_index(token_offset);
4912            let invisible_offset =
4913                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4914            let origin = content_origin
4915                + gpui::point(
4916                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4917                    line_y,
4918                );
4919
4920            (
4921                [token_offset, token_end_offset],
4922                Box::new(move |cx: &mut WindowContext| {
4923                    invisible_symbol.paint(origin, line_height, cx).log_err();
4924                }),
4925            )
4926        };
4927
4928        let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4929        match whitespace_setting {
4930            ShowWhitespaceSetting::None => (),
4931            ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4932            ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4933                let invisible_point = DisplayPoint::new(row, start as u32);
4934                if !selection_ranges
4935                    .iter()
4936                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
4937                {
4938                    return;
4939                }
4940
4941                paint(cx);
4942            }),
4943
4944            // For a whitespace to be on a boundary, any of the following conditions need to be met:
4945            // - It is a tab
4946            // - It is adjacent to an edge (start or end)
4947            // - It is adjacent to a whitespace (left or right)
4948            ShowWhitespaceSetting::Boundary => {
4949                // We'll need to keep track of the last invisible we've seen and then check if we are adjacent to it for some of
4950                // the above cases.
4951                // Note: We zip in the original `invisibles` to check for tab equality
4952                let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4953                for (([start, end], paint), invisible) in
4954                    invisible_iter.zip_eq(self.invisibles.iter())
4955                {
4956                    let should_render = match (&last_seen, invisible) {
4957                        (_, Invisible::Tab { .. }) => true,
4958                        (Some((_, last_end, _)), _) => *last_end == start,
4959                        _ => false,
4960                    };
4961
4962                    if should_render || start == 0 || end == self.len {
4963                        paint(cx);
4964
4965                        // Since we are scanning from the left, we will skip over the first available whitespace that is part
4966                        // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4967                        if let Some((should_render_last, last_end, paint_last)) = last_seen {
4968                            // Note that we need to make sure that the last one is actually adjacent
4969                            if !should_render_last && last_end == start {
4970                                paint_last(cx);
4971                            }
4972                        }
4973                    }
4974
4975                    // Manually render anything within a selection
4976                    let invisible_point = DisplayPoint::new(row, start as u32);
4977                    if selection_ranges.iter().any(|region| {
4978                        region.start <= invisible_point && invisible_point < region.end
4979                    }) {
4980                        paint(cx);
4981                    }
4982
4983                    last_seen = Some((should_render, end, paint));
4984                }
4985            }
4986        }
4987    }
4988
4989    pub fn x_for_index(&self, index: usize) -> Pixels {
4990        let mut fragment_start_x = Pixels::ZERO;
4991        let mut fragment_start_index = 0;
4992
4993        for fragment in &self.fragments {
4994            match fragment {
4995                LineFragment::Text(shaped_line) => {
4996                    let fragment_end_index = fragment_start_index + shaped_line.len;
4997                    if index < fragment_end_index {
4998                        return fragment_start_x
4999                            + shaped_line.x_for_index(index - fragment_start_index);
5000                    }
5001                    fragment_start_x += shaped_line.width;
5002                    fragment_start_index = fragment_end_index;
5003                }
5004                LineFragment::Element { len, size, .. } => {
5005                    let fragment_end_index = fragment_start_index + len;
5006                    if index < fragment_end_index {
5007                        return fragment_start_x;
5008                    }
5009                    fragment_start_x += size.width;
5010                    fragment_start_index = fragment_end_index;
5011                }
5012            }
5013        }
5014
5015        fragment_start_x
5016    }
5017
5018    pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
5019        let mut fragment_start_x = Pixels::ZERO;
5020        let mut fragment_start_index = 0;
5021
5022        for fragment in &self.fragments {
5023            match fragment {
5024                LineFragment::Text(shaped_line) => {
5025                    let fragment_end_x = fragment_start_x + shaped_line.width;
5026                    if x < fragment_end_x {
5027                        return Some(
5028                            fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
5029                        );
5030                    }
5031                    fragment_start_x = fragment_end_x;
5032                    fragment_start_index += shaped_line.len;
5033                }
5034                LineFragment::Element { len, size, .. } => {
5035                    let fragment_end_x = fragment_start_x + size.width;
5036                    if x < fragment_end_x {
5037                        return Some(fragment_start_index);
5038                    }
5039                    fragment_start_index += len;
5040                    fragment_start_x = fragment_end_x;
5041                }
5042            }
5043        }
5044
5045        None
5046    }
5047
5048    pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
5049        let mut fragment_start_index = 0;
5050
5051        for fragment in &self.fragments {
5052            match fragment {
5053                LineFragment::Text(shaped_line) => {
5054                    let fragment_end_index = fragment_start_index + shaped_line.len;
5055                    if index < fragment_end_index {
5056                        return shaped_line.font_id_for_index(index - fragment_start_index);
5057                    }
5058                    fragment_start_index = fragment_end_index;
5059                }
5060                LineFragment::Element { len, .. } => {
5061                    let fragment_end_index = fragment_start_index + len;
5062                    if index < fragment_end_index {
5063                        return None;
5064                    }
5065                    fragment_start_index = fragment_end_index;
5066                }
5067            }
5068        }
5069
5070        None
5071    }
5072}
5073
5074#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5075enum Invisible {
5076    /// A tab character
5077    ///
5078    /// A tab character is internally represented by spaces (configured by the user's tab width)
5079    /// aligned to the nearest column, so it's necessary to store the start and end offset for
5080    /// adjacency checks.
5081    Tab {
5082        line_start_offset: usize,
5083        line_end_offset: usize,
5084    },
5085    Whitespace {
5086        line_offset: usize,
5087    },
5088}
5089
5090impl EditorElement {
5091    /// Returns the rem size to use when rendering the [`EditorElement`].
5092    ///
5093    /// This allows UI elements to scale based on the `buffer_font_size`.
5094    fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
5095        match self.editor.read(cx).mode {
5096            EditorMode::Full => {
5097                let buffer_font_size = self.style.text.font_size;
5098                match buffer_font_size {
5099                    AbsoluteLength::Pixels(pixels) => {
5100                        let rem_size_scale = {
5101                            // Our default UI font size is 14px on a 16px base scale.
5102                            // This means the default UI font size is 0.875rems.
5103                            let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
5104
5105                            // We then determine the delta between a single rem and the default font
5106                            // size scale.
5107                            let default_font_size_delta = 1. - default_font_size_scale;
5108
5109                            // Finally, we add this delta to 1rem to get the scale factor that
5110                            // should be used to scale up the UI.
5111                            1. + default_font_size_delta
5112                        };
5113
5114                        Some(pixels * rem_size_scale)
5115                    }
5116                    AbsoluteLength::Rems(rems) => {
5117                        Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
5118                    }
5119                }
5120            }
5121            // We currently use single-line and auto-height editors in UI contexts,
5122            // so we don't want to scale everything with the buffer font size, as it
5123            // ends up looking off.
5124            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
5125        }
5126    }
5127}
5128
5129impl Element for EditorElement {
5130    type RequestLayoutState = ();
5131    type PrepaintState = EditorLayout;
5132
5133    fn id(&self) -> Option<ElementId> {
5134        None
5135    }
5136
5137    fn request_layout(
5138        &mut self,
5139        _: Option<&GlobalElementId>,
5140        cx: &mut WindowContext,
5141    ) -> (gpui::LayoutId, ()) {
5142        let rem_size = self.rem_size(cx);
5143        cx.with_rem_size(rem_size, |cx| {
5144            self.editor.update(cx, |editor, cx| {
5145                editor.set_style(self.style.clone(), cx);
5146
5147                let layout_id = match editor.mode {
5148                    EditorMode::SingleLine { auto_width } => {
5149                        let rem_size = cx.rem_size();
5150
5151                        let height = self.style.text.line_height_in_pixels(rem_size);
5152                        if auto_width {
5153                            let editor_handle = cx.view().clone();
5154                            let style = self.style.clone();
5155                            cx.request_measured_layout(Style::default(), move |_, _, cx| {
5156                                let editor_snapshot =
5157                                    editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
5158                                let line = Self::layout_lines(
5159                                    DisplayRow(0)..DisplayRow(1),
5160                                    &editor_snapshot,
5161                                    &style,
5162                                    px(f32::MAX),
5163                                    |_| false, // Single lines never soft wrap
5164                                    cx,
5165                                )
5166                                .pop()
5167                                .unwrap();
5168
5169                                let font_id = cx.text_system().resolve_font(&style.text.font());
5170                                let font_size = style.text.font_size.to_pixels(cx.rem_size());
5171                                let em_width = cx
5172                                    .text_system()
5173                                    .typographic_bounds(font_id, font_size, 'm')
5174                                    .unwrap()
5175                                    .size
5176                                    .width;
5177
5178                                size(line.width + em_width, height)
5179                            })
5180                        } else {
5181                            let mut style = Style::default();
5182                            style.size.height = height.into();
5183                            style.size.width = relative(1.).into();
5184                            cx.request_layout(style, None)
5185                        }
5186                    }
5187                    EditorMode::AutoHeight { max_lines } => {
5188                        let editor_handle = cx.view().clone();
5189                        let max_line_number_width =
5190                            self.max_line_number_width(&editor.snapshot(cx), cx);
5191                        cx.request_measured_layout(
5192                            Style::default(),
5193                            move |known_dimensions, available_space, cx| {
5194                                editor_handle
5195                                    .update(cx, |editor, cx| {
5196                                        compute_auto_height_layout(
5197                                            editor,
5198                                            max_lines,
5199                                            max_line_number_width,
5200                                            known_dimensions,
5201                                            available_space.width,
5202                                            cx,
5203                                        )
5204                                    })
5205                                    .unwrap_or_default()
5206                            },
5207                        )
5208                    }
5209                    EditorMode::Full => {
5210                        let mut style = Style::default();
5211                        style.size.width = relative(1.).into();
5212                        style.size.height = relative(1.).into();
5213                        cx.request_layout(style, None)
5214                    }
5215                };
5216
5217                (layout_id, ())
5218            })
5219        })
5220    }
5221
5222    fn prepaint(
5223        &mut self,
5224        _: Option<&GlobalElementId>,
5225        bounds: Bounds<Pixels>,
5226        _: &mut Self::RequestLayoutState,
5227        cx: &mut WindowContext,
5228    ) -> Self::PrepaintState {
5229        let text_style = TextStyleRefinement {
5230            font_size: Some(self.style.text.font_size),
5231            line_height: Some(self.style.text.line_height),
5232            ..Default::default()
5233        };
5234        let focus_handle = self.editor.focus_handle(cx);
5235        cx.set_view_id(self.editor.entity_id());
5236        cx.set_focus_handle(&focus_handle);
5237
5238        let rem_size = self.rem_size(cx);
5239        cx.with_rem_size(rem_size, |cx| {
5240            cx.with_text_style(Some(text_style), |cx| {
5241                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5242                    let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
5243                    let style = self.style.clone();
5244
5245                    let font_id = cx.text_system().resolve_font(&style.text.font());
5246                    let font_size = style.text.font_size.to_pixels(cx.rem_size());
5247                    let line_height = style.text.line_height_in_pixels(cx.rem_size());
5248                    let em_width = cx
5249                        .text_system()
5250                        .typographic_bounds(font_id, font_size, 'm')
5251                        .unwrap()
5252                        .size
5253                        .width;
5254                    let em_advance = cx
5255                        .text_system()
5256                        .advance(font_id, font_size, 'm')
5257                        .unwrap()
5258                        .width;
5259
5260                    let gutter_dimensions = snapshot.gutter_dimensions(
5261                        font_id,
5262                        font_size,
5263                        em_width,
5264                        em_advance,
5265                        self.max_line_number_width(&snapshot, cx),
5266                        cx,
5267                    );
5268                    let text_width = bounds.size.width - gutter_dimensions.width;
5269
5270                    let right_margin = if snapshot.mode == EditorMode::Full {
5271                        EditorElement::SCROLLBAR_WIDTH
5272                    } else {
5273                        px(0.)
5274                    };
5275                    let overscroll = size(em_width + right_margin, px(0.));
5276
5277                    let editor_width =
5278                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
5279
5280                    snapshot = self.editor.update(cx, |editor, cx| {
5281                        editor.last_bounds = Some(bounds);
5282                        editor.gutter_dimensions = gutter_dimensions;
5283                        editor.set_visible_line_count(bounds.size.height / line_height, cx);
5284
5285                        if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5286                            snapshot
5287                        } else {
5288                            let wrap_width = match editor.soft_wrap_mode(cx) {
5289                                SoftWrap::GitDiff => None,
5290                                SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5291                                SoftWrap::EditorWidth => Some(editor_width),
5292                                SoftWrap::Column(column) => Some(column as f32 * em_advance),
5293                                SoftWrap::Bounded(column) => {
5294                                    Some(editor_width.min(column as f32 * em_advance))
5295                                }
5296                            };
5297
5298                            if editor.set_wrap_width(wrap_width, cx) {
5299                                editor.snapshot(cx)
5300                            } else {
5301                                snapshot
5302                            }
5303                        }
5304                    });
5305
5306                    let wrap_guides = self
5307                        .editor
5308                        .read(cx)
5309                        .wrap_guides(cx)
5310                        .iter()
5311                        .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5312                        .collect::<SmallVec<[_; 2]>>();
5313
5314                    let hitbox = cx.insert_hitbox(bounds, false);
5315                    let gutter_hitbox =
5316                        cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5317                    let text_hitbox = cx.insert_hitbox(
5318                        Bounds {
5319                            origin: gutter_hitbox.upper_right(),
5320                            size: size(text_width, bounds.size.height),
5321                        },
5322                        false,
5323                    );
5324                    // Offset the content_bounds from the text_bounds by the gutter margin (which
5325                    // is roughly half a character wide) to make hit testing work more like how we want.
5326                    let content_origin =
5327                        text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5328
5329                    let height_in_lines = bounds.size.height / line_height;
5330                    let max_row = snapshot.max_point().row().as_f32();
5331                    let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5332                        (max_row - height_in_lines + 1.).max(0.)
5333                    } else {
5334                        let settings = EditorSettings::get_global(cx);
5335                        match settings.scroll_beyond_last_line {
5336                            ScrollBeyondLastLine::OnePage => max_row,
5337                            ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5338                            ScrollBeyondLastLine::VerticalScrollMargin => {
5339                                (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5340                                    .max(0.)
5341                            }
5342                        }
5343                    };
5344
5345                    let mut autoscroll_request = None;
5346                    let mut autoscroll_containing_element = false;
5347                    let mut autoscroll_horizontally = false;
5348                    self.editor.update(cx, |editor, cx| {
5349                        autoscroll_request = editor.autoscroll_request();
5350                        autoscroll_containing_element =
5351                            autoscroll_request.is_some() || editor.has_pending_selection();
5352                        autoscroll_horizontally =
5353                            editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5354                        snapshot = editor.snapshot(cx);
5355                    });
5356
5357                    let mut scroll_position = snapshot.scroll_position();
5358                    // The scroll position is a fractional point, the whole number of which represents
5359                    // the top of the window in terms of display rows.
5360                    let start_row = DisplayRow(scroll_position.y as u32);
5361                    let max_row = snapshot.max_point().row();
5362                    let end_row = cmp::min(
5363                        (scroll_position.y + height_in_lines).ceil() as u32,
5364                        max_row.next_row().0,
5365                    );
5366                    let end_row = DisplayRow(end_row);
5367
5368                    let buffer_rows = snapshot
5369                        .buffer_rows(start_row)
5370                        .take((start_row..end_row).len())
5371                        .collect::<Vec<_>>();
5372                    let is_row_soft_wrapped =
5373                        |row| buffer_rows.get(row).copied().flatten().is_none();
5374
5375                    let start_anchor = if start_row == Default::default() {
5376                        Anchor::min()
5377                    } else {
5378                        snapshot.buffer_snapshot.anchor_before(
5379                            DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5380                        )
5381                    };
5382                    let end_anchor = if end_row > max_row {
5383                        Anchor::max()
5384                    } else {
5385                        snapshot.buffer_snapshot.anchor_before(
5386                            DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5387                        )
5388                    };
5389
5390                    let highlighted_rows = self
5391                        .editor
5392                        .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5393                    let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5394                        start_anchor..end_anchor,
5395                        &snapshot.display_snapshot,
5396                        cx.theme().colors(),
5397                    );
5398                    let highlighted_gutter_ranges =
5399                        self.editor.read(cx).gutter_highlights_in_range(
5400                            start_anchor..end_anchor,
5401                            &snapshot.display_snapshot,
5402                            cx,
5403                        );
5404
5405                    let redacted_ranges = self.editor.read(cx).redacted_ranges(
5406                        start_anchor..end_anchor,
5407                        &snapshot.display_snapshot,
5408                        cx,
5409                    );
5410
5411                    let local_selections: Vec<Selection<Point>> =
5412                        self.editor.update(cx, |editor, cx| {
5413                            let mut selections = editor
5414                                .selections
5415                                .disjoint_in_range(start_anchor..end_anchor, cx);
5416                            selections.extend(editor.selections.pending(cx));
5417                            selections
5418                        });
5419
5420                    let (selections, active_rows, newest_selection_head) = self.layout_selections(
5421                        start_anchor,
5422                        end_anchor,
5423                        &local_selections,
5424                        &snapshot,
5425                        start_row,
5426                        end_row,
5427                        cx,
5428                    );
5429
5430                    let line_numbers = self.layout_line_numbers(
5431                        start_row..end_row,
5432                        buffer_rows.iter().copied(),
5433                        &active_rows,
5434                        newest_selection_head,
5435                        &snapshot,
5436                        cx,
5437                    );
5438
5439                    let mut crease_toggles = cx.with_element_namespace("crease_toggles", |cx| {
5440                        self.layout_crease_toggles(
5441                            start_row..end_row,
5442                            buffer_rows.iter().copied(),
5443                            &active_rows,
5444                            &snapshot,
5445                            cx,
5446                        )
5447                    });
5448                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5449                        self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5450                    });
5451
5452                    let display_hunks = self.layout_gutter_git_hunks(
5453                        line_height,
5454                        &gutter_hitbox,
5455                        start_row..end_row,
5456                        start_anchor..end_anchor,
5457                        &snapshot,
5458                        cx,
5459                    );
5460
5461                    let mut max_visible_line_width = Pixels::ZERO;
5462                    let mut line_layouts = Self::layout_lines(
5463                        start_row..end_row,
5464                        &snapshot,
5465                        &self.style,
5466                        editor_width,
5467                        is_row_soft_wrapped,
5468                        cx,
5469                    );
5470                    for line_with_invisibles in &line_layouts {
5471                        if line_with_invisibles.width > max_visible_line_width {
5472                            max_visible_line_width = line_with_invisibles.width;
5473                        }
5474                    }
5475
5476                    let longest_line_width = layout_line(
5477                        snapshot.longest_row(),
5478                        &snapshot,
5479                        &style,
5480                        editor_width,
5481                        is_row_soft_wrapped,
5482                        cx,
5483                    )
5484                    .width;
5485                    let mut scroll_width =
5486                        longest_line_width.max(max_visible_line_width) + overscroll.width;
5487
5488                    let blocks = cx.with_element_namespace("blocks", |cx| {
5489                        self.render_blocks(
5490                            start_row..end_row,
5491                            &snapshot,
5492                            &hitbox,
5493                            &text_hitbox,
5494                            editor_width,
5495                            &mut scroll_width,
5496                            &gutter_dimensions,
5497                            em_width,
5498                            gutter_dimensions.full_width(),
5499                            line_height,
5500                            &line_layouts,
5501                            &local_selections,
5502                            is_row_soft_wrapped,
5503                            cx,
5504                        )
5505                    });
5506                    let mut blocks = match blocks {
5507                        Ok(blocks) => blocks,
5508                        Err(resized_blocks) => {
5509                            self.editor.update(cx, |editor, cx| {
5510                                editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5511                            });
5512                            return self.prepaint(None, bounds, &mut (), cx);
5513                        }
5514                    };
5515
5516                    let start_buffer_row =
5517                        MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5518                    let end_buffer_row =
5519                        MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5520
5521                    let scroll_max = point(
5522                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5523                        max_row.as_f32(),
5524                    );
5525
5526                    self.editor.update(cx, |editor, cx| {
5527                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5528
5529                        let autoscrolled = if autoscroll_horizontally {
5530                            editor.autoscroll_horizontally(
5531                                start_row,
5532                                text_hitbox.size.width,
5533                                scroll_width,
5534                                em_width,
5535                                &line_layouts,
5536                                cx,
5537                            )
5538                        } else {
5539                            false
5540                        };
5541
5542                        if clamped || autoscrolled {
5543                            snapshot = editor.snapshot(cx);
5544                            scroll_position = snapshot.scroll_position();
5545                        }
5546                    });
5547
5548                    let scroll_pixel_position = point(
5549                        scroll_position.x * em_width,
5550                        scroll_position.y * line_height,
5551                    );
5552
5553                    let indent_guides = self.layout_indent_guides(
5554                        content_origin,
5555                        text_hitbox.origin,
5556                        start_buffer_row..end_buffer_row,
5557                        scroll_pixel_position,
5558                        line_height,
5559                        &snapshot,
5560                        cx,
5561                    );
5562
5563                    let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5564                        self.prepaint_crease_trailers(
5565                            crease_trailers,
5566                            &line_layouts,
5567                            line_height,
5568                            content_origin,
5569                            scroll_pixel_position,
5570                            em_width,
5571                            cx,
5572                        )
5573                    });
5574
5575                    let mut inline_blame = None;
5576                    if let Some(newest_selection_head) = newest_selection_head {
5577                        let display_row = newest_selection_head.row();
5578                        if (start_row..end_row).contains(&display_row) {
5579                            let line_ix = display_row.minus(start_row) as usize;
5580                            let line_layout = &line_layouts[line_ix];
5581                            let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5582                            inline_blame = self.layout_inline_blame(
5583                                display_row,
5584                                &snapshot.display_snapshot,
5585                                line_layout,
5586                                crease_trailer_layout,
5587                                em_width,
5588                                content_origin,
5589                                scroll_pixel_position,
5590                                line_height,
5591                                cx,
5592                            );
5593                        }
5594                    }
5595
5596                    let blamed_display_rows = self.layout_blame_entries(
5597                        buffer_rows.into_iter(),
5598                        em_width,
5599                        scroll_position,
5600                        line_height,
5601                        &gutter_hitbox,
5602                        gutter_dimensions.git_blame_entries_width,
5603                        cx,
5604                    );
5605
5606                    let scroll_max = point(
5607                        ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5608                        max_scroll_top,
5609                    );
5610
5611                    self.editor.update(cx, |editor, cx| {
5612                        let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5613
5614                        let autoscrolled = if autoscroll_horizontally {
5615                            editor.autoscroll_horizontally(
5616                                start_row,
5617                                text_hitbox.size.width,
5618                                scroll_width,
5619                                em_width,
5620                                &line_layouts,
5621                                cx,
5622                            )
5623                        } else {
5624                            false
5625                        };
5626
5627                        if clamped || autoscrolled {
5628                            snapshot = editor.snapshot(cx);
5629                            scroll_position = snapshot.scroll_position();
5630                        }
5631                    });
5632
5633                    let line_elements = self.prepaint_lines(
5634                        start_row,
5635                        &mut line_layouts,
5636                        line_height,
5637                        scroll_pixel_position,
5638                        content_origin,
5639                        cx,
5640                    );
5641
5642                    let mut block_start_rows = HashSet::default();
5643                    cx.with_element_namespace("blocks", |cx| {
5644                        self.layout_blocks(
5645                            &mut blocks,
5646                            &mut block_start_rows,
5647                            &hitbox,
5648                            line_height,
5649                            scroll_pixel_position,
5650                            cx,
5651                        );
5652                    });
5653
5654                    let cursors = self.collect_cursors(&snapshot, cx);
5655                    let visible_row_range = start_row..end_row;
5656                    let non_visible_cursors = cursors
5657                        .iter()
5658                        .any(move |c| !visible_row_range.contains(&c.0.row()));
5659
5660                    let visible_cursors = self.layout_visible_cursors(
5661                        &snapshot,
5662                        &selections,
5663                        &block_start_rows,
5664                        start_row..end_row,
5665                        &line_layouts,
5666                        &text_hitbox,
5667                        content_origin,
5668                        scroll_position,
5669                        scroll_pixel_position,
5670                        line_height,
5671                        em_width,
5672                        autoscroll_containing_element,
5673                        cx,
5674                    );
5675
5676                    let scrollbar_layout = self.layout_scrollbar(
5677                        &snapshot,
5678                        bounds,
5679                        scroll_position,
5680                        height_in_lines,
5681                        non_visible_cursors,
5682                        cx,
5683                    );
5684
5685                    let gutter_settings = EditorSettings::get_global(cx).gutter;
5686
5687                    let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5688                        editor
5689                            .diff_map
5690                            .hunks(false)
5691                            .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5692                            .map(|expanded_hunk| {
5693                                let start_row = expanded_hunk
5694                                    .hunk_range
5695                                    .start
5696                                    .to_display_point(&snapshot)
5697                                    .row();
5698                                (start_row, expanded_hunk.clone())
5699                            })
5700                            .collect::<HashMap<_, _>>()
5701                    });
5702
5703                    let rows_with_hunk_bounds = display_hunks
5704                        .iter()
5705                        .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5706                        .fold(
5707                            HashMap::default(),
5708                            |mut rows_with_hunk_bounds, (hunk, bounds)| {
5709                                match hunk {
5710                                    DisplayDiffHunk::Folded { display_row } => {
5711                                        rows_with_hunk_bounds.insert(*display_row, bounds);
5712                                    }
5713                                    DisplayDiffHunk::Unfolded {
5714                                        display_row_range, ..
5715                                    } => {
5716                                        for display_row in display_row_range.iter_rows() {
5717                                            rows_with_hunk_bounds.insert(display_row, bounds);
5718                                        }
5719                                    }
5720                                }
5721                                rows_with_hunk_bounds
5722                            },
5723                        );
5724                    let mut _context_menu_visible = false;
5725                    let mut code_actions_indicator = None;
5726                    if let Some(newest_selection_head) = newest_selection_head {
5727                        if (start_row..end_row).contains(&newest_selection_head.row()) {
5728                            _context_menu_visible = self.layout_context_menu(
5729                                line_height,
5730                                &hitbox,
5731                                &text_hitbox,
5732                                content_origin,
5733                                start_row,
5734                                scroll_pixel_position,
5735                                &line_layouts,
5736                                newest_selection_head,
5737                                gutter_dimensions.width - gutter_dimensions.left_padding,
5738                                cx,
5739                            );
5740
5741                            let show_code_actions = snapshot
5742                                .show_code_actions
5743                                .unwrap_or(gutter_settings.code_actions);
5744                            if show_code_actions {
5745                                let newest_selection_point =
5746                                    newest_selection_head.to_point(&snapshot.display_snapshot);
5747                                let newest_selection_display_row =
5748                                    newest_selection_point.to_display_point(&snapshot).row();
5749                                if !expanded_add_hunks_by_rows
5750                                    .contains_key(&newest_selection_display_row)
5751                                {
5752                                    let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5753                                        MultiBufferRow(newest_selection_point.row),
5754                                    );
5755                                    if let Some((buffer, range)) = buffer {
5756                                        let buffer_id = buffer.remote_id();
5757                                        let row = range.start.row;
5758                                        let has_test_indicator = self
5759                                            .editor
5760                                            .read(cx)
5761                                            .tasks
5762                                            .contains_key(&(buffer_id, row));
5763
5764                                        if !has_test_indicator {
5765                                            code_actions_indicator = self
5766                                                .layout_code_actions_indicator(
5767                                                    line_height,
5768                                                    newest_selection_head,
5769                                                    scroll_pixel_position,
5770                                                    &gutter_dimensions,
5771                                                    &gutter_hitbox,
5772                                                    &rows_with_hunk_bounds,
5773                                                    cx,
5774                                                );
5775                                        }
5776                                    }
5777                                }
5778                            }
5779                        }
5780                    }
5781
5782                    let test_indicators = if gutter_settings.runnables {
5783                        self.layout_run_indicators(
5784                            line_height,
5785                            start_row..end_row,
5786                            scroll_pixel_position,
5787                            &gutter_dimensions,
5788                            &gutter_hitbox,
5789                            &rows_with_hunk_bounds,
5790                            &snapshot,
5791                            cx,
5792                        )
5793                    } else {
5794                        Vec::new()
5795                    };
5796
5797                    self.layout_signature_help(
5798                        &hitbox,
5799                        content_origin,
5800                        scroll_pixel_position,
5801                        newest_selection_head,
5802                        start_row,
5803                        &line_layouts,
5804                        line_height,
5805                        em_width,
5806                        cx,
5807                    );
5808
5809                    if !cx.has_active_drag() {
5810                        self.layout_hover_popovers(
5811                            &snapshot,
5812                            &hitbox,
5813                            &text_hitbox,
5814                            start_row..end_row,
5815                            content_origin,
5816                            scroll_pixel_position,
5817                            &line_layouts,
5818                            line_height,
5819                            em_width,
5820                            cx,
5821                        );
5822                    }
5823
5824                    let inline_completion_popover = self.layout_inline_completion_popover(
5825                        &text_hitbox.bounds,
5826                        &snapshot,
5827                        start_row..end_row,
5828                        scroll_position.y,
5829                        scroll_position.y + height_in_lines,
5830                        &line_layouts,
5831                        line_height,
5832                        scroll_pixel_position,
5833                        editor_width,
5834                        &style,
5835                        cx,
5836                    );
5837
5838                    let mouse_context_menu = self.layout_mouse_context_menu(
5839                        &snapshot,
5840                        start_row..end_row,
5841                        content_origin,
5842                        cx,
5843                    );
5844
5845                    cx.with_element_namespace("crease_toggles", |cx| {
5846                        self.prepaint_crease_toggles(
5847                            &mut crease_toggles,
5848                            line_height,
5849                            &gutter_dimensions,
5850                            gutter_settings,
5851                            scroll_pixel_position,
5852                            &gutter_hitbox,
5853                            cx,
5854                        )
5855                    });
5856
5857                    let invisible_symbol_font_size = font_size / 2.;
5858                    let tab_invisible = cx
5859                        .text_system()
5860                        .shape_line(
5861                            "".into(),
5862                            invisible_symbol_font_size,
5863                            &[TextRun {
5864                                len: "".len(),
5865                                font: self.style.text.font(),
5866                                color: cx.theme().colors().editor_invisible,
5867                                background_color: None,
5868                                underline: None,
5869                                strikethrough: None,
5870                            }],
5871                        )
5872                        .unwrap();
5873                    let space_invisible = cx
5874                        .text_system()
5875                        .shape_line(
5876                            "".into(),
5877                            invisible_symbol_font_size,
5878                            &[TextRun {
5879                                len: "".len(),
5880                                font: self.style.text.font(),
5881                                color: cx.theme().colors().editor_invisible,
5882                                background_color: None,
5883                                underline: None,
5884                                strikethrough: None,
5885                            }],
5886                        )
5887                        .unwrap();
5888
5889                    EditorLayout {
5890                        mode: snapshot.mode,
5891                        position_map: Rc::new(PositionMap {
5892                            size: bounds.size,
5893                            scroll_pixel_position,
5894                            scroll_max,
5895                            line_layouts,
5896                            line_height,
5897                            em_width,
5898                            em_advance,
5899                            snapshot,
5900                        }),
5901                        visible_display_row_range: start_row..end_row,
5902                        wrap_guides,
5903                        indent_guides,
5904                        hitbox,
5905                        text_hitbox,
5906                        gutter_hitbox,
5907                        gutter_dimensions,
5908                        display_hunks,
5909                        content_origin,
5910                        scrollbar_layout,
5911                        active_rows,
5912                        highlighted_rows,
5913                        highlighted_ranges,
5914                        highlighted_gutter_ranges,
5915                        redacted_ranges,
5916                        line_elements,
5917                        line_numbers,
5918                        blamed_display_rows,
5919                        inline_blame,
5920                        blocks,
5921                        cursors,
5922                        visible_cursors,
5923                        selections,
5924                        inline_completion_popover,
5925                        mouse_context_menu,
5926                        test_indicators,
5927                        code_actions_indicator,
5928                        crease_toggles,
5929                        crease_trailers,
5930                        tab_invisible,
5931                        space_invisible,
5932                    }
5933                })
5934            })
5935        })
5936    }
5937
5938    fn paint(
5939        &mut self,
5940        _: Option<&GlobalElementId>,
5941        bounds: Bounds<gpui::Pixels>,
5942        _: &mut Self::RequestLayoutState,
5943        layout: &mut Self::PrepaintState,
5944        cx: &mut WindowContext,
5945    ) {
5946        let focus_handle = self.editor.focus_handle(cx);
5947        let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
5948        cx.set_key_context(key_context);
5949        cx.handle_input(
5950            &focus_handle,
5951            ElementInputHandler::new(bounds, self.editor.clone()),
5952        );
5953        self.register_actions(cx);
5954        self.register_key_listeners(cx, layout);
5955
5956        let text_style = TextStyleRefinement {
5957            font_size: Some(self.style.text.font_size),
5958            line_height: Some(self.style.text.line_height),
5959            ..Default::default()
5960        };
5961        let hovered_hunk = layout
5962            .display_hunks
5963            .iter()
5964            .find_map(|(hunk, hunk_hitbox)| match hunk {
5965                DisplayDiffHunk::Folded { .. } => None,
5966                DisplayDiffHunk::Unfolded {
5967                    diff_base_byte_range,
5968                    multi_buffer_range,
5969                    status,
5970                    ..
5971                } => {
5972                    if hunk_hitbox
5973                        .as_ref()
5974                        .map(|hitbox| hitbox.is_hovered(cx))
5975                        .unwrap_or(false)
5976                    {
5977                        Some(HoveredHunk {
5978                            status: *status,
5979                            multi_buffer_range: multi_buffer_range.clone(),
5980                            diff_base_byte_range: diff_base_byte_range.clone(),
5981                        })
5982                    } else {
5983                        None
5984                    }
5985                }
5986            });
5987        let rem_size = self.rem_size(cx);
5988        cx.with_rem_size(rem_size, |cx| {
5989            cx.with_text_style(Some(text_style), |cx| {
5990                cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5991                    self.paint_mouse_listeners(layout, hovered_hunk, cx);
5992                    self.paint_background(layout, cx);
5993                    self.paint_indent_guides(layout, cx);
5994
5995                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
5996                        self.paint_blamed_display_rows(layout, cx);
5997                        self.paint_line_numbers(layout, cx);
5998                    }
5999
6000                    self.paint_text(layout, cx);
6001
6002                    if layout.gutter_hitbox.size.width > Pixels::ZERO {
6003                        self.paint_gutter_highlights(layout, cx);
6004                        self.paint_gutter_indicators(layout, cx);
6005                    }
6006
6007                    if !layout.blocks.is_empty() {
6008                        cx.with_element_namespace("blocks", |cx| {
6009                            self.paint_blocks(layout, cx);
6010                        });
6011                    }
6012
6013                    self.paint_scrollbar(layout, cx);
6014                    self.paint_inline_completion_popover(layout, cx);
6015                    self.paint_mouse_context_menu(layout, cx);
6016                });
6017            })
6018        })
6019    }
6020}
6021
6022pub(super) fn gutter_bounds(
6023    editor_bounds: Bounds<Pixels>,
6024    gutter_dimensions: GutterDimensions,
6025) -> Bounds<Pixels> {
6026    Bounds {
6027        origin: editor_bounds.origin,
6028        size: size(gutter_dimensions.width, editor_bounds.size.height),
6029    }
6030}
6031
6032impl IntoElement for EditorElement {
6033    type Element = Self;
6034
6035    fn into_element(self) -> Self::Element {
6036        self
6037    }
6038}
6039
6040pub struct EditorLayout {
6041    position_map: Rc<PositionMap>,
6042    hitbox: Hitbox,
6043    text_hitbox: Hitbox,
6044    gutter_hitbox: Hitbox,
6045    gutter_dimensions: GutterDimensions,
6046    content_origin: gpui::Point<Pixels>,
6047    scrollbar_layout: Option<ScrollbarLayout>,
6048    mode: EditorMode,
6049    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
6050    indent_guides: Option<Vec<IndentGuideLayout>>,
6051    visible_display_row_range: Range<DisplayRow>,
6052    active_rows: BTreeMap<DisplayRow, bool>,
6053    highlighted_rows: BTreeMap<DisplayRow, Hsla>,
6054    line_elements: SmallVec<[AnyElement; 1]>,
6055    line_numbers: Vec<Option<ShapedLine>>,
6056    display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
6057    blamed_display_rows: Option<Vec<AnyElement>>,
6058    inline_blame: Option<AnyElement>,
6059    blocks: Vec<BlockLayout>,
6060    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6061    highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
6062    redacted_ranges: Vec<Range<DisplayPoint>>,
6063    cursors: Vec<(DisplayPoint, Hsla)>,
6064    visible_cursors: Vec<CursorLayout>,
6065    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
6066    code_actions_indicator: Option<AnyElement>,
6067    test_indicators: Vec<AnyElement>,
6068    crease_toggles: Vec<Option<AnyElement>>,
6069    crease_trailers: Vec<Option<CreaseTrailerLayout>>,
6070    inline_completion_popover: Option<AnyElement>,
6071    mouse_context_menu: Option<AnyElement>,
6072    tab_invisible: ShapedLine,
6073    space_invisible: ShapedLine,
6074}
6075
6076impl EditorLayout {
6077    fn line_end_overshoot(&self) -> Pixels {
6078        0.15 * self.position_map.line_height
6079    }
6080}
6081
6082struct ColoredRange<T> {
6083    start: T,
6084    end: T,
6085    color: Hsla,
6086}
6087
6088#[derive(Clone)]
6089struct ScrollbarLayout {
6090    hitbox: Hitbox,
6091    visible_row_range: Range<f32>,
6092    visible: bool,
6093    row_height: Pixels,
6094    thumb_height: Pixels,
6095}
6096
6097impl ScrollbarLayout {
6098    const BORDER_WIDTH: Pixels = px(1.0);
6099    const LINE_MARKER_HEIGHT: Pixels = px(2.0);
6100    const MIN_MARKER_HEIGHT: Pixels = px(5.0);
6101    const MIN_THUMB_HEIGHT: Pixels = px(20.0);
6102
6103    fn thumb_bounds(&self) -> Bounds<Pixels> {
6104        let thumb_top = self.y_for_row(self.visible_row_range.start);
6105        let thumb_bottom = thumb_top + self.thumb_height;
6106        Bounds::from_corners(
6107            point(self.hitbox.left(), thumb_top),
6108            point(self.hitbox.right(), thumb_bottom),
6109        )
6110    }
6111
6112    fn y_for_row(&self, row: f32) -> Pixels {
6113        self.hitbox.top() + row * self.row_height
6114    }
6115
6116    fn marker_quads_for_ranges(
6117        &self,
6118        row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
6119        column: Option<usize>,
6120    ) -> Vec<PaintQuad> {
6121        struct MinMax {
6122            min: Pixels,
6123            max: Pixels,
6124        }
6125        let (x_range, height_limit) = if let Some(column) = column {
6126            let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
6127            let start = Self::BORDER_WIDTH + (column as f32 * column_width);
6128            let end = start + column_width;
6129            (
6130                Range { start, end },
6131                MinMax {
6132                    min: Self::MIN_MARKER_HEIGHT,
6133                    max: px(f32::MAX),
6134                },
6135            )
6136        } else {
6137            (
6138                Range {
6139                    start: Self::BORDER_WIDTH,
6140                    end: self.hitbox.size.width,
6141                },
6142                MinMax {
6143                    min: Self::LINE_MARKER_HEIGHT,
6144                    max: Self::LINE_MARKER_HEIGHT,
6145                },
6146            )
6147        };
6148
6149        let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
6150        let mut pixel_ranges = row_ranges
6151            .into_iter()
6152            .map(|range| {
6153                let start_y = row_to_y(range.start);
6154                let end_y = row_to_y(range.end)
6155                    + self.row_height.max(height_limit.min).min(height_limit.max);
6156                ColoredRange {
6157                    start: start_y,
6158                    end: end_y,
6159                    color: range.color,
6160                }
6161            })
6162            .peekable();
6163
6164        let mut quads = Vec::new();
6165        while let Some(mut pixel_range) = pixel_ranges.next() {
6166            while let Some(next_pixel_range) = pixel_ranges.peek() {
6167                if pixel_range.end >= next_pixel_range.start - px(1.0)
6168                    && pixel_range.color == next_pixel_range.color
6169                {
6170                    pixel_range.end = next_pixel_range.end.max(pixel_range.end);
6171                    pixel_ranges.next();
6172                } else {
6173                    break;
6174                }
6175            }
6176
6177            let bounds = Bounds::from_corners(
6178                point(x_range.start, pixel_range.start),
6179                point(x_range.end, pixel_range.end),
6180            );
6181            quads.push(quad(
6182                bounds,
6183                Corners::default(),
6184                pixel_range.color,
6185                Edges::default(),
6186                Hsla::transparent_black(),
6187            ));
6188        }
6189
6190        quads
6191    }
6192}
6193
6194struct CreaseTrailerLayout {
6195    element: AnyElement,
6196    bounds: Bounds<Pixels>,
6197}
6198
6199struct PositionMap {
6200    size: Size<Pixels>,
6201    line_height: Pixels,
6202    scroll_pixel_position: gpui::Point<Pixels>,
6203    scroll_max: gpui::Point<f32>,
6204    em_width: Pixels,
6205    em_advance: Pixels,
6206    line_layouts: Vec<LineWithInvisibles>,
6207    snapshot: EditorSnapshot,
6208}
6209
6210#[derive(Debug, Copy, Clone)]
6211pub struct PointForPosition {
6212    pub previous_valid: DisplayPoint,
6213    pub next_valid: DisplayPoint,
6214    pub exact_unclipped: DisplayPoint,
6215    pub column_overshoot_after_line_end: u32,
6216}
6217
6218impl PointForPosition {
6219    pub fn as_valid(&self) -> Option<DisplayPoint> {
6220        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
6221            Some(self.previous_valid)
6222        } else {
6223            None
6224        }
6225    }
6226}
6227
6228impl PositionMap {
6229    fn point_for_position(
6230        &self,
6231        text_bounds: Bounds<Pixels>,
6232        position: gpui::Point<Pixels>,
6233    ) -> PointForPosition {
6234        let scroll_position = self.snapshot.scroll_position();
6235        let position = position - text_bounds.origin;
6236        let y = position.y.max(px(0.)).min(self.size.height);
6237        let x = position.x + (scroll_position.x * self.em_width);
6238        let row = ((y / self.line_height) + scroll_position.y) as u32;
6239
6240        let (column, x_overshoot_after_line_end) = if let Some(line) = self
6241            .line_layouts
6242            .get(row as usize - scroll_position.y as usize)
6243        {
6244            if let Some(ix) = line.index_for_x(x) {
6245                (ix as u32, px(0.))
6246            } else {
6247                (line.len as u32, px(0.).max(x - line.width))
6248            }
6249        } else {
6250            (0, x)
6251        };
6252
6253        let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
6254        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
6255        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
6256
6257        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
6258        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
6259        PointForPosition {
6260            previous_valid,
6261            next_valid,
6262            exact_unclipped,
6263            column_overshoot_after_line_end,
6264        }
6265    }
6266}
6267
6268struct BlockLayout {
6269    id: BlockId,
6270    row: Option<DisplayRow>,
6271    element: AnyElement,
6272    available_space: Size<AvailableSpace>,
6273    style: BlockStyle,
6274}
6275
6276fn layout_line(
6277    row: DisplayRow,
6278    snapshot: &EditorSnapshot,
6279    style: &EditorStyle,
6280    text_width: Pixels,
6281    is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6282    cx: &mut WindowContext,
6283) -> LineWithInvisibles {
6284    let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
6285    LineWithInvisibles::from_chunks(
6286        chunks,
6287        &style,
6288        MAX_LINE_LEN,
6289        1,
6290        snapshot.mode,
6291        text_width,
6292        is_row_soft_wrapped,
6293        cx,
6294    )
6295    .pop()
6296    .unwrap()
6297}
6298
6299#[derive(Debug)]
6300pub struct IndentGuideLayout {
6301    origin: gpui::Point<Pixels>,
6302    length: Pixels,
6303    single_indent_width: Pixels,
6304    depth: u32,
6305    active: bool,
6306    settings: IndentGuideSettings,
6307}
6308
6309pub struct CursorLayout {
6310    origin: gpui::Point<Pixels>,
6311    block_width: Pixels,
6312    line_height: Pixels,
6313    color: Hsla,
6314    shape: CursorShape,
6315    block_text: Option<ShapedLine>,
6316    cursor_name: Option<AnyElement>,
6317}
6318
6319#[derive(Debug)]
6320pub struct CursorName {
6321    string: SharedString,
6322    color: Hsla,
6323    is_top_row: bool,
6324}
6325
6326impl CursorLayout {
6327    pub fn new(
6328        origin: gpui::Point<Pixels>,
6329        block_width: Pixels,
6330        line_height: Pixels,
6331        color: Hsla,
6332        shape: CursorShape,
6333        block_text: Option<ShapedLine>,
6334    ) -> CursorLayout {
6335        CursorLayout {
6336            origin,
6337            block_width,
6338            line_height,
6339            color,
6340            shape,
6341            block_text,
6342            cursor_name: None,
6343        }
6344    }
6345
6346    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6347        Bounds {
6348            origin: self.origin + origin,
6349            size: size(self.block_width, self.line_height),
6350        }
6351    }
6352
6353    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6354        match self.shape {
6355            CursorShape::Bar => Bounds {
6356                origin: self.origin + origin,
6357                size: size(px(2.0), self.line_height),
6358            },
6359            CursorShape::Block | CursorShape::Hollow => Bounds {
6360                origin: self.origin + origin,
6361                size: size(self.block_width, self.line_height),
6362            },
6363            CursorShape::Underline => Bounds {
6364                origin: self.origin
6365                    + origin
6366                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6367                size: size(self.block_width, px(2.0)),
6368            },
6369        }
6370    }
6371
6372    pub fn layout(
6373        &mut self,
6374        origin: gpui::Point<Pixels>,
6375        cursor_name: Option<CursorName>,
6376        cx: &mut WindowContext,
6377    ) {
6378        if let Some(cursor_name) = cursor_name {
6379            let bounds = self.bounds(origin);
6380            let text_size = self.line_height / 1.5;
6381
6382            let name_origin = if cursor_name.is_top_row {
6383                point(bounds.right() - px(1.), bounds.top())
6384            } else {
6385                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6386            };
6387            let mut name_element = div()
6388                .bg(self.color)
6389                .text_size(text_size)
6390                .px_0p5()
6391                .line_height(text_size + px(2.))
6392                .text_color(cursor_name.color)
6393                .child(cursor_name.string.clone())
6394                .into_any_element();
6395
6396            name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6397
6398            self.cursor_name = Some(name_element);
6399        }
6400    }
6401
6402    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6403        let bounds = self.bounds(origin);
6404
6405        //Draw background or border quad
6406        let cursor = if matches!(self.shape, CursorShape::Hollow) {
6407            outline(bounds, self.color)
6408        } else {
6409            fill(bounds, self.color)
6410        };
6411
6412        if let Some(name) = &mut self.cursor_name {
6413            name.paint(cx);
6414        }
6415
6416        cx.paint_quad(cursor);
6417
6418        if let Some(block_text) = &self.block_text {
6419            block_text
6420                .paint(self.origin + origin, self.line_height, cx)
6421                .log_err();
6422        }
6423    }
6424
6425    pub fn shape(&self) -> CursorShape {
6426        self.shape
6427    }
6428}
6429
6430#[derive(Debug)]
6431pub struct HighlightedRange {
6432    pub start_y: Pixels,
6433    pub line_height: Pixels,
6434    pub lines: Vec<HighlightedRangeLine>,
6435    pub color: Hsla,
6436    pub corner_radius: Pixels,
6437}
6438
6439#[derive(Debug)]
6440pub struct HighlightedRangeLine {
6441    pub start_x: Pixels,
6442    pub end_x: Pixels,
6443}
6444
6445impl HighlightedRange {
6446    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6447        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6448            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6449            self.paint_lines(
6450                self.start_y + self.line_height,
6451                &self.lines[1..],
6452                bounds,
6453                cx,
6454            );
6455        } else {
6456            self.paint_lines(self.start_y, &self.lines, bounds, cx);
6457        }
6458    }
6459
6460    fn paint_lines(
6461        &self,
6462        start_y: Pixels,
6463        lines: &[HighlightedRangeLine],
6464        _bounds: Bounds<Pixels>,
6465        cx: &mut WindowContext,
6466    ) {
6467        if lines.is_empty() {
6468            return;
6469        }
6470
6471        let first_line = lines.first().unwrap();
6472        let last_line = lines.last().unwrap();
6473
6474        let first_top_left = point(first_line.start_x, start_y);
6475        let first_top_right = point(first_line.end_x, start_y);
6476
6477        let curve_height = point(Pixels::ZERO, self.corner_radius);
6478        let curve_width = |start_x: Pixels, end_x: Pixels| {
6479            let max = (end_x - start_x) / 2.;
6480            let width = if max < self.corner_radius {
6481                max
6482            } else {
6483                self.corner_radius
6484            };
6485
6486            point(width, Pixels::ZERO)
6487        };
6488
6489        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6490        let mut path = gpui::Path::new(first_top_right - top_curve_width);
6491        path.curve_to(first_top_right + curve_height, first_top_right);
6492
6493        let mut iter = lines.iter().enumerate().peekable();
6494        while let Some((ix, line)) = iter.next() {
6495            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6496
6497            if let Some((_, next_line)) = iter.peek() {
6498                let next_top_right = point(next_line.end_x, bottom_right.y);
6499
6500                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6501                    Ordering::Equal => {
6502                        path.line_to(bottom_right);
6503                    }
6504                    Ordering::Less => {
6505                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
6506                        path.line_to(bottom_right - curve_height);
6507                        if self.corner_radius > Pixels::ZERO {
6508                            path.curve_to(bottom_right - curve_width, bottom_right);
6509                        }
6510                        path.line_to(next_top_right + curve_width);
6511                        if self.corner_radius > Pixels::ZERO {
6512                            path.curve_to(next_top_right + curve_height, next_top_right);
6513                        }
6514                    }
6515                    Ordering::Greater => {
6516                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
6517                        path.line_to(bottom_right - curve_height);
6518                        if self.corner_radius > Pixels::ZERO {
6519                            path.curve_to(bottom_right + curve_width, bottom_right);
6520                        }
6521                        path.line_to(next_top_right - curve_width);
6522                        if self.corner_radius > Pixels::ZERO {
6523                            path.curve_to(next_top_right + curve_height, next_top_right);
6524                        }
6525                    }
6526                }
6527            } else {
6528                let curve_width = curve_width(line.start_x, line.end_x);
6529                path.line_to(bottom_right - curve_height);
6530                if self.corner_radius > Pixels::ZERO {
6531                    path.curve_to(bottom_right - curve_width, bottom_right);
6532                }
6533
6534                let bottom_left = point(line.start_x, bottom_right.y);
6535                path.line_to(bottom_left + curve_width);
6536                if self.corner_radius > Pixels::ZERO {
6537                    path.curve_to(bottom_left - curve_height, bottom_left);
6538                }
6539            }
6540        }
6541
6542        if first_line.start_x > last_line.start_x {
6543            let curve_width = curve_width(last_line.start_x, first_line.start_x);
6544            let second_top_left = point(last_line.start_x, start_y + self.line_height);
6545            path.line_to(second_top_left + curve_height);
6546            if self.corner_radius > Pixels::ZERO {
6547                path.curve_to(second_top_left + curve_width, second_top_left);
6548            }
6549            let first_bottom_left = point(first_line.start_x, second_top_left.y);
6550            path.line_to(first_bottom_left - curve_width);
6551            if self.corner_radius > Pixels::ZERO {
6552                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6553            }
6554        }
6555
6556        path.line_to(first_top_left + curve_height);
6557        if self.corner_radius > Pixels::ZERO {
6558            path.curve_to(first_top_left + top_curve_width, first_top_left);
6559        }
6560        path.line_to(first_top_right - top_curve_width);
6561
6562        cx.paint_path(path, self.color);
6563    }
6564}
6565
6566pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6567    (delta.pow(1.5) / 100.0).into()
6568}
6569
6570fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6571    (delta.pow(1.2) / 300.0).into()
6572}
6573
6574pub fn register_action<T: Action>(
6575    view: &View<Editor>,
6576    cx: &mut WindowContext,
6577    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6578) {
6579    let view = view.clone();
6580    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6581        let action = action.downcast_ref().unwrap();
6582        if phase == DispatchPhase::Bubble {
6583            view.update(cx, |editor, cx| {
6584                listener(editor, action, cx);
6585            })
6586        }
6587    })
6588}
6589
6590fn compute_auto_height_layout(
6591    editor: &mut Editor,
6592    max_lines: usize,
6593    max_line_number_width: Pixels,
6594    known_dimensions: Size<Option<Pixels>>,
6595    available_width: AvailableSpace,
6596    cx: &mut ViewContext<Editor>,
6597) -> Option<Size<Pixels>> {
6598    let width = known_dimensions.width.or({
6599        if let AvailableSpace::Definite(available_width) = available_width {
6600            Some(available_width)
6601        } else {
6602            None
6603        }
6604    })?;
6605    if let Some(height) = known_dimensions.height {
6606        return Some(size(width, height));
6607    }
6608
6609    let style = editor.style.as_ref().unwrap();
6610    let font_id = cx.text_system().resolve_font(&style.text.font());
6611    let font_size = style.text.font_size.to_pixels(cx.rem_size());
6612    let line_height = style.text.line_height_in_pixels(cx.rem_size());
6613    let em_width = cx
6614        .text_system()
6615        .typographic_bounds(font_id, font_size, 'm')
6616        .unwrap()
6617        .size
6618        .width;
6619    let em_advance = cx
6620        .text_system()
6621        .advance(font_id, font_size, 'm')
6622        .unwrap()
6623        .width;
6624
6625    let mut snapshot = editor.snapshot(cx);
6626    let gutter_dimensions = snapshot.gutter_dimensions(
6627        font_id,
6628        font_size,
6629        em_width,
6630        em_advance,
6631        max_line_number_width,
6632        cx,
6633    );
6634
6635    editor.gutter_dimensions = gutter_dimensions;
6636    let text_width = width - gutter_dimensions.width;
6637    let overscroll = size(em_width, px(0.));
6638
6639    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6640    if editor.set_wrap_width(Some(editor_width), cx) {
6641        snapshot = editor.snapshot(cx);
6642    }
6643
6644    let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6645    let height = scroll_height
6646        .max(line_height)
6647        .min(line_height * max_lines as f32);
6648
6649    Some(size(width, height))
6650}
6651
6652#[cfg(test)]
6653mod tests {
6654    use super::*;
6655    use crate::{
6656        display_map::{BlockPlacement, BlockProperties},
6657        editor_tests::{init_test, update_test_language_settings},
6658        Editor, MultiBuffer,
6659    };
6660    use gpui::{TestAppContext, VisualTestContext};
6661    use language::language_settings;
6662    use log::info;
6663    use std::num::NonZeroU32;
6664    use ui::Context;
6665    use util::test::sample_text;
6666
6667    #[gpui::test]
6668    fn test_shape_line_numbers(cx: &mut TestAppContext) {
6669        init_test(cx, |_| {});
6670        let window = cx.add_window(|cx| {
6671            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6672            Editor::new(EditorMode::Full, buffer, None, true, cx)
6673        });
6674
6675        let editor = window.root(cx).unwrap();
6676        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6677        let element = EditorElement::new(&editor, style);
6678        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6679
6680        let layouts = cx
6681            .update_window(*window, |_, cx| {
6682                element.layout_line_numbers(
6683                    DisplayRow(0)..DisplayRow(6),
6684                    (0..6).map(MultiBufferRow).map(Some),
6685                    &Default::default(),
6686                    Some(DisplayPoint::new(DisplayRow(0), 0)),
6687                    &snapshot,
6688                    cx,
6689                )
6690            })
6691            .unwrap();
6692        assert_eq!(layouts.len(), 6);
6693
6694        let relative_rows = window
6695            .update(cx, |editor, cx| {
6696                let snapshot = editor.snapshot(cx);
6697                element.calculate_relative_line_numbers(
6698                    &snapshot,
6699                    &(DisplayRow(0)..DisplayRow(6)),
6700                    Some(DisplayRow(3)),
6701                )
6702            })
6703            .unwrap();
6704        assert_eq!(relative_rows[&DisplayRow(0)], 3);
6705        assert_eq!(relative_rows[&DisplayRow(1)], 2);
6706        assert_eq!(relative_rows[&DisplayRow(2)], 1);
6707        // current line has no relative number
6708        assert_eq!(relative_rows[&DisplayRow(4)], 1);
6709        assert_eq!(relative_rows[&DisplayRow(5)], 2);
6710
6711        // works if cursor is before screen
6712        let relative_rows = window
6713            .update(cx, |editor, cx| {
6714                let snapshot = editor.snapshot(cx);
6715                element.calculate_relative_line_numbers(
6716                    &snapshot,
6717                    &(DisplayRow(3)..DisplayRow(6)),
6718                    Some(DisplayRow(1)),
6719                )
6720            })
6721            .unwrap();
6722        assert_eq!(relative_rows.len(), 3);
6723        assert_eq!(relative_rows[&DisplayRow(3)], 2);
6724        assert_eq!(relative_rows[&DisplayRow(4)], 3);
6725        assert_eq!(relative_rows[&DisplayRow(5)], 4);
6726
6727        // works if cursor is after screen
6728        let relative_rows = window
6729            .update(cx, |editor, cx| {
6730                let snapshot = editor.snapshot(cx);
6731                element.calculate_relative_line_numbers(
6732                    &snapshot,
6733                    &(DisplayRow(0)..DisplayRow(3)),
6734                    Some(DisplayRow(6)),
6735                )
6736            })
6737            .unwrap();
6738        assert_eq!(relative_rows.len(), 3);
6739        assert_eq!(relative_rows[&DisplayRow(0)], 5);
6740        assert_eq!(relative_rows[&DisplayRow(1)], 4);
6741        assert_eq!(relative_rows[&DisplayRow(2)], 3);
6742    }
6743
6744    #[gpui::test]
6745    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6746        init_test(cx, |_| {});
6747
6748        let window = cx.add_window(|cx| {
6749            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6750            Editor::new(EditorMode::Full, buffer, None, true, cx)
6751        });
6752        let cx = &mut VisualTestContext::from_window(*window, cx);
6753        let editor = window.root(cx).unwrap();
6754        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6755
6756        window
6757            .update(cx, |editor, cx| {
6758                editor.cursor_shape = CursorShape::Block;
6759                editor.change_selections(None, cx, |s| {
6760                    s.select_ranges([
6761                        Point::new(0, 0)..Point::new(1, 0),
6762                        Point::new(3, 2)..Point::new(3, 3),
6763                        Point::new(5, 6)..Point::new(6, 0),
6764                    ]);
6765                });
6766            })
6767            .unwrap();
6768
6769        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6770            EditorElement::new(&editor, style)
6771        });
6772
6773        assert_eq!(state.selections.len(), 1);
6774        let local_selections = &state.selections[0].1;
6775        assert_eq!(local_selections.len(), 3);
6776        // moves cursor back one line
6777        assert_eq!(
6778            local_selections[0].head,
6779            DisplayPoint::new(DisplayRow(0), 6)
6780        );
6781        assert_eq!(
6782            local_selections[0].range,
6783            DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6784        );
6785
6786        // moves cursor back one column
6787        assert_eq!(
6788            local_selections[1].range,
6789            DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6790        );
6791        assert_eq!(
6792            local_selections[1].head,
6793            DisplayPoint::new(DisplayRow(3), 2)
6794        );
6795
6796        // leaves cursor on the max point
6797        assert_eq!(
6798            local_selections[2].range,
6799            DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6800        );
6801        assert_eq!(
6802            local_selections[2].head,
6803            DisplayPoint::new(DisplayRow(6), 0)
6804        );
6805
6806        // active lines does not include 1 (even though the range of the selection does)
6807        assert_eq!(
6808            state.active_rows.keys().cloned().collect::<Vec<_>>(),
6809            vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6810        );
6811
6812        // multi-buffer support
6813        // in DisplayPoint coordinates, this is what we're dealing with:
6814        //  0: [[file
6815        //  1:   header
6816        //  2:   section]]
6817        //  3: aaaaaa
6818        //  4: bbbbbb
6819        //  5: cccccc
6820        //  6:
6821        //  7: [[footer]]
6822        //  8: [[header]]
6823        //  9: ffffff
6824        // 10: gggggg
6825        // 11: hhhhhh
6826        // 12:
6827        // 13: [[footer]]
6828        // 14: [[file
6829        // 15:   header
6830        // 16:   section]]
6831        // 17: bbbbbb
6832        // 18: cccccc
6833        // 19: dddddd
6834        // 20: [[footer]]
6835        let window = cx.add_window(|cx| {
6836            let buffer = MultiBuffer::build_multi(
6837                [
6838                    (
6839                        &(sample_text(8, 6, 'a') + "\n"),
6840                        vec![
6841                            Point::new(0, 0)..Point::new(3, 0),
6842                            Point::new(4, 0)..Point::new(7, 0),
6843                        ],
6844                    ),
6845                    (
6846                        &(sample_text(8, 6, 'a') + "\n"),
6847                        vec![Point::new(1, 0)..Point::new(3, 0)],
6848                    ),
6849                ],
6850                cx,
6851            );
6852            Editor::new(EditorMode::Full, buffer, None, true, cx)
6853        });
6854        let editor = window.root(cx).unwrap();
6855        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6856        let _state = window.update(cx, |editor, cx| {
6857            editor.cursor_shape = CursorShape::Block;
6858            editor.change_selections(None, cx, |s| {
6859                s.select_display_ranges([
6860                    DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6861                    DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6862                ]);
6863            });
6864        });
6865
6866        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6867            EditorElement::new(&editor, style)
6868        });
6869        assert_eq!(state.selections.len(), 1);
6870        let local_selections = &state.selections[0].1;
6871        assert_eq!(local_selections.len(), 2);
6872
6873        // moves cursor on excerpt boundary back a line
6874        // and doesn't allow selection to bleed through
6875        assert_eq!(
6876            local_selections[0].range,
6877            DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6878        );
6879        assert_eq!(
6880            local_selections[0].head,
6881            DisplayPoint::new(DisplayRow(6), 0)
6882        );
6883        // moves cursor on buffer boundary back two lines
6884        // and doesn't allow selection to bleed through
6885        assert_eq!(
6886            local_selections[1].range,
6887            DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6888        );
6889        assert_eq!(
6890            local_selections[1].head,
6891            DisplayPoint::new(DisplayRow(12), 0)
6892        );
6893    }
6894
6895    #[gpui::test]
6896    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6897        init_test(cx, |_| {});
6898
6899        let window = cx.add_window(|cx| {
6900            let buffer = MultiBuffer::build_simple("", cx);
6901            Editor::new(EditorMode::Full, buffer, None, true, cx)
6902        });
6903        let cx = &mut VisualTestContext::from_window(*window, cx);
6904        let editor = window.root(cx).unwrap();
6905        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6906        window
6907            .update(cx, |editor, cx| {
6908                editor.set_placeholder_text("hello", cx);
6909                editor.insert_blocks(
6910                    [BlockProperties {
6911                        style: BlockStyle::Fixed,
6912                        placement: BlockPlacement::Above(Anchor::min()),
6913                        height: 3,
6914                        render: Arc::new(|cx| div().h(3. * cx.line_height()).into_any()),
6915                        priority: 0,
6916                    }],
6917                    None,
6918                    cx,
6919                );
6920
6921                // Blur the editor so that it displays placeholder text.
6922                cx.blur();
6923            })
6924            .unwrap();
6925
6926        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6927            EditorElement::new(&editor, style)
6928        });
6929        assert_eq!(state.position_map.line_layouts.len(), 4);
6930        assert_eq!(
6931            state
6932                .line_numbers
6933                .iter()
6934                .map(Option::is_some)
6935                .collect::<Vec<_>>(),
6936            &[false, false, false, true]
6937        );
6938    }
6939
6940    #[gpui::test]
6941    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6942        const TAB_SIZE: u32 = 4;
6943
6944        let input_text = "\t \t|\t| a b";
6945        let expected_invisibles = vec![
6946            Invisible::Tab {
6947                line_start_offset: 0,
6948                line_end_offset: TAB_SIZE as usize,
6949            },
6950            Invisible::Whitespace {
6951                line_offset: TAB_SIZE as usize,
6952            },
6953            Invisible::Tab {
6954                line_start_offset: TAB_SIZE as usize + 1,
6955                line_end_offset: TAB_SIZE as usize * 2,
6956            },
6957            Invisible::Tab {
6958                line_start_offset: TAB_SIZE as usize * 2 + 1,
6959                line_end_offset: TAB_SIZE as usize * 3,
6960            },
6961            Invisible::Whitespace {
6962                line_offset: TAB_SIZE as usize * 3 + 1,
6963            },
6964            Invisible::Whitespace {
6965                line_offset: TAB_SIZE as usize * 3 + 3,
6966            },
6967        ];
6968        assert_eq!(
6969            expected_invisibles.len(),
6970            input_text
6971                .chars()
6972                .filter(|initial_char| initial_char.is_whitespace())
6973                .count(),
6974            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6975        );
6976
6977        for show_line_numbers in [true, false] {
6978            init_test(cx, |s| {
6979                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6980                s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6981            });
6982
6983            let actual_invisibles = collect_invisibles_from_new_editor(
6984                cx,
6985                EditorMode::Full,
6986                input_text,
6987                px(500.0),
6988                show_line_numbers,
6989            );
6990
6991            assert_eq!(expected_invisibles, actual_invisibles);
6992        }
6993    }
6994
6995    #[gpui::test]
6996    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6997        init_test(cx, |s| {
6998            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6999            s.defaults.tab_size = NonZeroU32::new(4);
7000        });
7001
7002        for editor_mode_without_invisibles in [
7003            EditorMode::SingleLine { auto_width: false },
7004            EditorMode::AutoHeight { max_lines: 100 },
7005        ] {
7006            for show_line_numbers in [true, false] {
7007                let invisibles = collect_invisibles_from_new_editor(
7008                    cx,
7009                    editor_mode_without_invisibles,
7010                    "\t\t\t| | a b",
7011                    px(500.0),
7012                    show_line_numbers,
7013                );
7014                assert!(invisibles.is_empty(),
7015                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
7016            }
7017        }
7018    }
7019
7020    #[gpui::test]
7021    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
7022        let tab_size = 4;
7023        let input_text = "a\tbcd     ".repeat(9);
7024        let repeated_invisibles = [
7025            Invisible::Tab {
7026                line_start_offset: 1,
7027                line_end_offset: tab_size as usize,
7028            },
7029            Invisible::Whitespace {
7030                line_offset: tab_size as usize + 3,
7031            },
7032            Invisible::Whitespace {
7033                line_offset: tab_size as usize + 4,
7034            },
7035            Invisible::Whitespace {
7036                line_offset: tab_size as usize + 5,
7037            },
7038            Invisible::Whitespace {
7039                line_offset: tab_size as usize + 6,
7040            },
7041            Invisible::Whitespace {
7042                line_offset: tab_size as usize + 7,
7043            },
7044        ];
7045        let expected_invisibles = std::iter::once(repeated_invisibles)
7046            .cycle()
7047            .take(9)
7048            .flatten()
7049            .collect::<Vec<_>>();
7050        assert_eq!(
7051            expected_invisibles.len(),
7052            input_text
7053                .chars()
7054                .filter(|initial_char| initial_char.is_whitespace())
7055                .count(),
7056            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
7057        );
7058        info!("Expected invisibles: {expected_invisibles:?}");
7059
7060        init_test(cx, |_| {});
7061
7062        // Put the same string with repeating whitespace pattern into editors of various size,
7063        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
7064        let resize_step = 10.0;
7065        let mut editor_width = 200.0;
7066        while editor_width <= 1000.0 {
7067            for show_line_numbers in [true, false] {
7068                update_test_language_settings(cx, |s| {
7069                    s.defaults.tab_size = NonZeroU32::new(tab_size);
7070                    s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
7071                    s.defaults.preferred_line_length = Some(editor_width as u32);
7072                    s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
7073                });
7074
7075                let actual_invisibles = collect_invisibles_from_new_editor(
7076                    cx,
7077                    EditorMode::Full,
7078                    &input_text,
7079                    px(editor_width),
7080                    show_line_numbers,
7081                );
7082
7083                // Whatever the editor size is, ensure it has the same invisible kinds in the same order
7084                // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
7085                let mut i = 0;
7086                for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
7087                    i = actual_index;
7088                    match expected_invisibles.get(i) {
7089                        Some(expected_invisible) => match (expected_invisible, actual_invisible) {
7090                            (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
7091                            | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
7092                            _ => {
7093                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
7094                            }
7095                        },
7096                        None => {
7097                            panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
7098                        }
7099                    }
7100                }
7101                let missing_expected_invisibles = &expected_invisibles[i + 1..];
7102                assert!(
7103                    missing_expected_invisibles.is_empty(),
7104                    "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
7105                );
7106
7107                editor_width += resize_step;
7108            }
7109        }
7110    }
7111
7112    #[gpui::test]
7113    fn test_inline_completion_popover_text(cx: &mut TestAppContext) {
7114        init_test(cx, |_| {});
7115
7116        // Test case 1: Simple insertion
7117        {
7118            let window = cx.add_window(|cx| {
7119                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7120                Editor::new(EditorMode::Full, buffer, None, true, cx)
7121            });
7122            let cx = &mut VisualTestContext::from_window(*window, cx);
7123
7124            window
7125                .update(cx, |editor, cx| {
7126                    let snapshot = editor.snapshot(cx);
7127                    let edit_range = snapshot.buffer_snapshot.anchor_after(Point::new(0, 6))
7128                        ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 6));
7129                    let edits = vec![(edit_range, " beautiful".to_string())];
7130
7131                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7132
7133                    assert_eq!(text, "Hello, beautiful world!");
7134                    assert_eq!(highlights.len(), 1);
7135                    assert_eq!(highlights[0].0, 6..16);
7136                    assert_eq!(
7137                        highlights[0].1.background_color,
7138                        Some(cx.theme().status().created_background)
7139                    );
7140                })
7141                .unwrap();
7142        }
7143
7144        // Test case 2: Replacement
7145        {
7146            let window = cx.add_window(|cx| {
7147                let buffer = MultiBuffer::build_simple("This is a test.", cx);
7148                Editor::new(EditorMode::Full, buffer, None, true, cx)
7149            });
7150            let cx = &mut VisualTestContext::from_window(*window, cx);
7151
7152            window
7153                .update(cx, |editor, cx| {
7154                    let snapshot = editor.snapshot(cx);
7155                    let edits = vec![(
7156                        snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7157                            ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 4)),
7158                        "That".to_string(),
7159                    )];
7160
7161                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7162
7163                    assert_eq!(text, "That is a test.");
7164                    assert_eq!(highlights.len(), 1);
7165                    assert_eq!(highlights[0].0, 0..4);
7166                    assert_eq!(
7167                        highlights[0].1.background_color,
7168                        Some(cx.theme().status().created_background)
7169                    );
7170                })
7171                .unwrap();
7172        }
7173
7174        // Test case 3: Multiple edits
7175        {
7176            let window = cx.add_window(|cx| {
7177                let buffer = MultiBuffer::build_simple("Hello, world!", cx);
7178                Editor::new(EditorMode::Full, buffer, None, true, cx)
7179            });
7180            let cx = &mut VisualTestContext::from_window(*window, cx);
7181
7182            window
7183                .update(cx, |editor, cx| {
7184                    let snapshot = editor.snapshot(cx);
7185                    let edits = vec![
7186                        (
7187                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 0))
7188                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 5)),
7189                            "Greetings".into(),
7190                        ),
7191                        (
7192                            snapshot.buffer_snapshot.anchor_after(Point::new(0, 12))
7193                                ..snapshot.buffer_snapshot.anchor_before(Point::new(0, 12)),
7194                            " and universe".into(),
7195                        ),
7196                    ];
7197
7198                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7199
7200                    assert_eq!(text, "Greetings, world and universe!");
7201                    assert_eq!(highlights.len(), 2);
7202                    assert_eq!(highlights[0].0, 0..9);
7203                    assert_eq!(highlights[1].0, 16..29);
7204                    assert_eq!(
7205                        highlights[0].1.background_color,
7206                        Some(cx.theme().status().created_background)
7207                    );
7208                    assert_eq!(
7209                        highlights[1].1.background_color,
7210                        Some(cx.theme().status().created_background)
7211                    );
7212                })
7213                .unwrap();
7214        }
7215
7216        // Test case 4: Multiple lines with edits
7217        {
7218            let window = cx.add_window(|cx| {
7219                let buffer = MultiBuffer::build_simple(
7220                    "First line\nSecond line\nThird line\nFourth line",
7221                    cx,
7222                );
7223                Editor::new(EditorMode::Full, buffer, None, true, cx)
7224            });
7225            let cx = &mut VisualTestContext::from_window(*window, cx);
7226
7227            window
7228                .update(cx, |editor, cx| {
7229                    let snapshot = editor.snapshot(cx);
7230                    let edits = vec![
7231                        (
7232                            snapshot.buffer_snapshot.anchor_before(Point::new(1, 7))
7233                                ..snapshot.buffer_snapshot.anchor_before(Point::new(1, 11)),
7234                            "modified".to_string(),
7235                        ),
7236                        (
7237                            snapshot.buffer_snapshot.anchor_before(Point::new(2, 0))
7238                                ..snapshot.buffer_snapshot.anchor_before(Point::new(2, 10)),
7239                            "New third line".to_string(),
7240                        ),
7241                        (
7242                            snapshot.buffer_snapshot.anchor_before(Point::new(3, 6))
7243                                ..snapshot.buffer_snapshot.anchor_before(Point::new(3, 6)),
7244                            " updated".to_string(),
7245                        ),
7246                    ];
7247
7248                    let (text, highlights) = inline_completion_popover_text(&snapshot, &edits, cx);
7249
7250                    assert_eq!(text, "Second modified\nNew third line\nFourth updated line");
7251                    assert_eq!(highlights.len(), 3);
7252                    assert_eq!(highlights[0].0, 7..15); // "modified"
7253                    assert_eq!(highlights[1].0, 16..30); // "New third line"
7254                    assert_eq!(highlights[2].0, 37..45); // " updated"
7255
7256                    for highlight in &highlights {
7257                        assert_eq!(
7258                            highlight.1.background_color,
7259                            Some(cx.theme().status().created_background)
7260                        );
7261                    }
7262                })
7263                .unwrap();
7264        }
7265    }
7266
7267    fn collect_invisibles_from_new_editor(
7268        cx: &mut TestAppContext,
7269        editor_mode: EditorMode,
7270        input_text: &str,
7271        editor_width: Pixels,
7272        show_line_numbers: bool,
7273    ) -> Vec<Invisible> {
7274        info!(
7275            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
7276            editor_width.0
7277        );
7278        let window = cx.add_window(|cx| {
7279            let buffer = MultiBuffer::build_simple(input_text, cx);
7280            Editor::new(editor_mode, buffer, None, true, cx)
7281        });
7282        let cx = &mut VisualTestContext::from_window(*window, cx);
7283        let editor = window.root(cx).unwrap();
7284
7285        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
7286        window
7287            .update(cx, |editor, cx| {
7288                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
7289                editor.set_wrap_width(Some(editor_width), cx);
7290                editor.set_show_line_numbers(show_line_numbers, cx);
7291            })
7292            .unwrap();
7293        let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
7294            EditorElement::new(&editor, style)
7295        });
7296        state
7297            .position_map
7298            .line_layouts
7299            .iter()
7300            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
7301            .cloned()
7302            .collect()
7303    }
7304}