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