element.rs

   1use crate::{
   2    display_map::{
   3        BlockContext, BlockStyle, DisplaySnapshot, FoldStatus, HighlightedChunk, ToDisplayPoint,
   4        TransformBlock,
   5    },
   6    editor_settings::ShowScrollbar,
   7    git::{diff_hunk_to_display, DisplayDiffHunk},
   8    hover_popover::{
   9        self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
  10    },
  11    items::BufferSearchHighlights,
  12    mouse_context_menu,
  13    scroll::scroll_amount::ScrollAmount,
  14    CursorShape, DisplayPoint, DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode,
  15    EditorSettings, EditorSnapshot, EditorStyle, GutterDimensions, HalfPageDown, HalfPageUp,
  16    HoveredCursor, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, SelectPhase, Selection,
  17    SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
  18};
  19use anyhow::Result;
  20use collections::{BTreeMap, HashMap};
  21use git::diff::DiffHunkStatus;
  22use gpui::{
  23    div, fill, outline, overlay, point, px, quad, relative, size, transparent_black, Action,
  24    AnchorCorner, AnyElement, AvailableSpace, Bounds, ContentMask, Corners, CursorStyle,
  25    DispatchPhase, Edges, Element, ElementContext, ElementInputHandler, Entity, Hitbox, Hsla,
  26    InteractiveElement, IntoElement, ModifiersChangedEvent, MouseButton, MouseDownEvent,
  27    MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine,
  28    SharedString, Size, Stateful, StatefulInteractiveElement, Style, Styled, TextRun, TextStyle,
  29    TextStyleRefinement, View, ViewContext, WindowContext,
  30};
  31use itertools::Itertools;
  32use language::language_settings::ShowWhitespaceSetting;
  33use lsp::DiagnosticSeverity;
  34use multi_buffer::Anchor;
  35use project::{
  36    project_settings::{GitGutterSetting, ProjectSettings},
  37    ProjectPath,
  38};
  39use settings::Settings;
  40use smallvec::SmallVec;
  41use std::{
  42    any::TypeId,
  43    borrow::Cow,
  44    cmp::{self, Ordering},
  45    fmt::Write,
  46    iter, mem,
  47    ops::Range,
  48    sync::Arc,
  49};
  50use sum_tree::Bias;
  51use theme::{ActiveTheme, PlayerColor};
  52use ui::prelude::*;
  53use ui::{h_flex, ButtonLike, ButtonStyle, Tooltip};
  54use util::ResultExt;
  55use workspace::item::Item;
  56
  57struct SelectionLayout {
  58    head: DisplayPoint,
  59    cursor_shape: CursorShape,
  60    is_newest: bool,
  61    is_local: bool,
  62    range: Range<DisplayPoint>,
  63    active_rows: Range<u32>,
  64    user_name: Option<SharedString>,
  65}
  66
  67impl SelectionLayout {
  68    fn new<T: ToPoint + ToDisplayPoint + Clone>(
  69        selection: Selection<T>,
  70        line_mode: bool,
  71        cursor_shape: CursorShape,
  72        map: &DisplaySnapshot,
  73        is_newest: bool,
  74        is_local: bool,
  75        user_name: Option<SharedString>,
  76    ) -> Self {
  77        let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
  78        let display_selection = point_selection.map(|p| p.to_display_point(map));
  79        let mut range = display_selection.range();
  80        let mut head = display_selection.head();
  81        let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
  82            ..map.next_line_boundary(point_selection.end).1.row();
  83
  84        // vim visual line mode
  85        if line_mode {
  86            let point_range = map.expand_to_line(point_selection.range());
  87            range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
  88        }
  89
  90        // any vim visual mode (including line mode)
  91        if cursor_shape == CursorShape::Block && !range.is_empty() && !selection.reversed {
  92            if head.column() > 0 {
  93                head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
  94            } else if head.row() > 0 && head != map.max_point() {
  95                head = map.clip_point(
  96                    DisplayPoint::new(head.row() - 1, map.line_len(head.row() - 1)),
  97                    Bias::Left,
  98                );
  99                // updating range.end is a no-op unless you're cursor is
 100                // on the newline containing a multi-buffer divider
 101                // in which case the clip_point may have moved the head up
 102                // an additional row.
 103                range.end = DisplayPoint::new(head.row() + 1, 0);
 104                active_rows.end = head.row();
 105            }
 106        }
 107
 108        Self {
 109            head,
 110            cursor_shape,
 111            is_newest,
 112            is_local,
 113            range,
 114            active_rows,
 115            user_name,
 116        }
 117    }
 118}
 119
 120pub struct EditorElement {
 121    editor: View<Editor>,
 122    style: EditorStyle,
 123}
 124
 125impl EditorElement {
 126    pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
 127        Self {
 128            editor: editor.clone(),
 129            style,
 130        }
 131    }
 132
 133    fn register_actions(&self, cx: &mut WindowContext) {
 134        let view = &self.editor;
 135        view.update(cx, |editor, cx| {
 136            for action in editor.editor_actions.iter() {
 137                (action)(cx)
 138            }
 139        });
 140
 141        crate::rust_analyzer_ext::apply_related_actions(view, cx);
 142        register_action(view, cx, Editor::move_left);
 143        register_action(view, cx, Editor::move_right);
 144        register_action(view, cx, Editor::move_down);
 145        register_action(view, cx, Editor::move_down_by_lines);
 146        register_action(view, cx, Editor::select_down_by_lines);
 147        register_action(view, cx, Editor::move_up);
 148        register_action(view, cx, Editor::move_up_by_lines);
 149        register_action(view, cx, Editor::select_up_by_lines);
 150        register_action(view, cx, Editor::cancel);
 151        register_action(view, cx, Editor::newline);
 152        register_action(view, cx, Editor::newline_above);
 153        register_action(view, cx, Editor::newline_below);
 154        register_action(view, cx, Editor::backspace);
 155        register_action(view, cx, Editor::delete);
 156        register_action(view, cx, Editor::tab);
 157        register_action(view, cx, Editor::tab_prev);
 158        register_action(view, cx, Editor::indent);
 159        register_action(view, cx, Editor::outdent);
 160        register_action(view, cx, Editor::delete_line);
 161        register_action(view, cx, Editor::join_lines);
 162        register_action(view, cx, Editor::sort_lines_case_sensitive);
 163        register_action(view, cx, Editor::sort_lines_case_insensitive);
 164        register_action(view, cx, Editor::reverse_lines);
 165        register_action(view, cx, Editor::shuffle_lines);
 166        register_action(view, cx, Editor::convert_to_upper_case);
 167        register_action(view, cx, Editor::convert_to_lower_case);
 168        register_action(view, cx, Editor::convert_to_title_case);
 169        register_action(view, cx, Editor::convert_to_snake_case);
 170        register_action(view, cx, Editor::convert_to_kebab_case);
 171        register_action(view, cx, Editor::convert_to_upper_camel_case);
 172        register_action(view, cx, Editor::convert_to_lower_camel_case);
 173        register_action(view, cx, Editor::delete_to_previous_word_start);
 174        register_action(view, cx, Editor::delete_to_previous_subword_start);
 175        register_action(view, cx, Editor::delete_to_next_word_end);
 176        register_action(view, cx, Editor::delete_to_next_subword_end);
 177        register_action(view, cx, Editor::delete_to_beginning_of_line);
 178        register_action(view, cx, Editor::delete_to_end_of_line);
 179        register_action(view, cx, Editor::cut_to_end_of_line);
 180        register_action(view, cx, Editor::duplicate_line);
 181        register_action(view, cx, Editor::move_line_up);
 182        register_action(view, cx, Editor::move_line_down);
 183        register_action(view, cx, Editor::transpose);
 184        register_action(view, cx, Editor::cut);
 185        register_action(view, cx, Editor::copy);
 186        register_action(view, cx, Editor::paste);
 187        register_action(view, cx, Editor::undo);
 188        register_action(view, cx, Editor::redo);
 189        register_action(view, cx, Editor::move_page_up);
 190        register_action(view, cx, Editor::move_page_down);
 191        register_action(view, cx, Editor::next_screen);
 192        register_action(view, cx, Editor::scroll_cursor_top);
 193        register_action(view, cx, Editor::scroll_cursor_center);
 194        register_action(view, cx, Editor::scroll_cursor_bottom);
 195        register_action(view, cx, |editor, _: &LineDown, cx| {
 196            editor.scroll_screen(&ScrollAmount::Line(1.), cx)
 197        });
 198        register_action(view, cx, |editor, _: &LineUp, cx| {
 199            editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
 200        });
 201        register_action(view, cx, |editor, _: &HalfPageDown, cx| {
 202            editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
 203        });
 204        register_action(view, cx, |editor, _: &HalfPageUp, cx| {
 205            editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
 206        });
 207        register_action(view, cx, |editor, _: &PageDown, cx| {
 208            editor.scroll_screen(&ScrollAmount::Page(1.), cx)
 209        });
 210        register_action(view, cx, |editor, _: &PageUp, cx| {
 211            editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
 212        });
 213        register_action(view, cx, Editor::move_to_previous_word_start);
 214        register_action(view, cx, Editor::move_to_previous_subword_start);
 215        register_action(view, cx, Editor::move_to_next_word_end);
 216        register_action(view, cx, Editor::move_to_next_subword_end);
 217        register_action(view, cx, Editor::move_to_beginning_of_line);
 218        register_action(view, cx, Editor::move_to_end_of_line);
 219        register_action(view, cx, Editor::move_to_start_of_paragraph);
 220        register_action(view, cx, Editor::move_to_end_of_paragraph);
 221        register_action(view, cx, Editor::move_to_beginning);
 222        register_action(view, cx, Editor::move_to_end);
 223        register_action(view, cx, Editor::select_up);
 224        register_action(view, cx, Editor::select_down);
 225        register_action(view, cx, Editor::select_left);
 226        register_action(view, cx, Editor::select_right);
 227        register_action(view, cx, Editor::select_to_previous_word_start);
 228        register_action(view, cx, Editor::select_to_previous_subword_start);
 229        register_action(view, cx, Editor::select_to_next_word_end);
 230        register_action(view, cx, Editor::select_to_next_subword_end);
 231        register_action(view, cx, Editor::select_to_beginning_of_line);
 232        register_action(view, cx, Editor::select_to_end_of_line);
 233        register_action(view, cx, Editor::select_to_start_of_paragraph);
 234        register_action(view, cx, Editor::select_to_end_of_paragraph);
 235        register_action(view, cx, Editor::select_to_beginning);
 236        register_action(view, cx, Editor::select_to_end);
 237        register_action(view, cx, Editor::select_all);
 238        register_action(view, cx, |editor, action, cx| {
 239            editor.select_all_matches(action, cx).log_err();
 240        });
 241        register_action(view, cx, Editor::select_line);
 242        register_action(view, cx, Editor::split_selection_into_lines);
 243        register_action(view, cx, Editor::add_selection_above);
 244        register_action(view, cx, Editor::add_selection_below);
 245        register_action(view, cx, |editor, action, cx| {
 246            editor.select_next(action, cx).log_err();
 247        });
 248        register_action(view, cx, |editor, action, cx| {
 249            editor.select_previous(action, cx).log_err();
 250        });
 251        register_action(view, cx, Editor::toggle_comments);
 252        register_action(view, cx, Editor::select_larger_syntax_node);
 253        register_action(view, cx, Editor::select_smaller_syntax_node);
 254        register_action(view, cx, Editor::move_to_enclosing_bracket);
 255        register_action(view, cx, Editor::undo_selection);
 256        register_action(view, cx, Editor::redo_selection);
 257        register_action(view, cx, Editor::go_to_diagnostic);
 258        register_action(view, cx, Editor::go_to_prev_diagnostic);
 259        register_action(view, cx, Editor::go_to_hunk);
 260        register_action(view, cx, Editor::go_to_prev_hunk);
 261        register_action(view, cx, Editor::go_to_definition);
 262        register_action(view, cx, Editor::go_to_definition_split);
 263        register_action(view, cx, Editor::go_to_implementation);
 264        register_action(view, cx, Editor::go_to_implementation_split);
 265        register_action(view, cx, Editor::go_to_type_definition);
 266        register_action(view, cx, Editor::go_to_type_definition_split);
 267        register_action(view, cx, Editor::open_url);
 268        register_action(view, cx, Editor::fold);
 269        register_action(view, cx, Editor::fold_at);
 270        register_action(view, cx, Editor::unfold_lines);
 271        register_action(view, cx, Editor::unfold_at);
 272        register_action(view, cx, Editor::fold_selected_ranges);
 273        register_action(view, cx, Editor::show_completions);
 274        register_action(view, cx, Editor::toggle_code_actions);
 275        register_action(view, cx, Editor::open_excerpts);
 276        register_action(view, cx, Editor::open_excerpts_in_split);
 277        register_action(view, cx, Editor::toggle_soft_wrap);
 278        register_action(view, cx, Editor::toggle_line_numbers);
 279        register_action(view, cx, Editor::toggle_inlay_hints);
 280        register_action(view, cx, hover_popover::hover);
 281        register_action(view, cx, Editor::reveal_in_finder);
 282        register_action(view, cx, Editor::copy_path);
 283        register_action(view, cx, Editor::copy_relative_path);
 284        register_action(view, cx, Editor::copy_highlight_json);
 285        register_action(view, cx, Editor::copy_permalink_to_line);
 286        register_action(view, cx, Editor::open_permalink_to_line);
 287        register_action(view, cx, |editor, action, cx| {
 288            if let Some(task) = editor.format(action, cx) {
 289                task.detach_and_log_err(cx);
 290            } else {
 291                cx.propagate();
 292            }
 293        });
 294        register_action(view, cx, Editor::restart_language_server);
 295        register_action(view, cx, Editor::show_character_palette);
 296        register_action(view, cx, |editor, action, cx| {
 297            if let Some(task) = editor.confirm_completion(action, cx) {
 298                task.detach_and_log_err(cx);
 299            } else {
 300                cx.propagate();
 301            }
 302        });
 303        register_action(view, cx, |editor, action, cx| {
 304            if let Some(task) = editor.confirm_code_action(action, cx) {
 305                task.detach_and_log_err(cx);
 306            } else {
 307                cx.propagate();
 308            }
 309        });
 310        register_action(view, cx, |editor, action, cx| {
 311            if let Some(task) = editor.rename(action, cx) {
 312                task.detach_and_log_err(cx);
 313            } else {
 314                cx.propagate();
 315            }
 316        });
 317        register_action(view, cx, |editor, action, cx| {
 318            if let Some(task) = editor.confirm_rename(action, cx) {
 319                task.detach_and_log_err(cx);
 320            } else {
 321                cx.propagate();
 322            }
 323        });
 324        register_action(view, cx, |editor, action, cx| {
 325            if let Some(task) = editor.find_all_references(action, cx) {
 326                task.detach_and_log_err(cx);
 327            } else {
 328                cx.propagate();
 329            }
 330        });
 331        register_action(view, cx, Editor::next_copilot_suggestion);
 332        register_action(view, cx, Editor::previous_copilot_suggestion);
 333        register_action(view, cx, Editor::copilot_suggest);
 334        register_action(view, cx, Editor::context_menu_first);
 335        register_action(view, cx, Editor::context_menu_prev);
 336        register_action(view, cx, Editor::context_menu_next);
 337        register_action(view, cx, Editor::context_menu_last);
 338        register_action(view, cx, Editor::display_cursor_names);
 339        register_action(view, cx, Editor::unique_lines_case_insensitive);
 340        register_action(view, cx, Editor::unique_lines_case_sensitive);
 341        register_action(view, cx, Editor::accept_partial_copilot_suggestion);
 342        register_action(view, cx, Editor::revert_selected_hunks);
 343    }
 344
 345    fn register_key_listeners(&self, cx: &mut ElementContext, layout: &EditorLayout) {
 346        let position_map = layout.position_map.clone();
 347        cx.on_key_event({
 348            let editor = self.editor.clone();
 349            let text_hitbox = layout.text_hitbox.clone();
 350            move |event: &ModifiersChangedEvent, phase, cx| {
 351                if phase != DispatchPhase::Bubble {
 352                    return;
 353                }
 354
 355                editor.update(cx, |editor, cx| {
 356                    Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
 357                })
 358            }
 359        });
 360    }
 361
 362    fn modifiers_changed(
 363        editor: &mut Editor,
 364        event: &ModifiersChangedEvent,
 365        position_map: &PositionMap,
 366        text_hitbox: &Hitbox,
 367        cx: &mut ViewContext<Editor>,
 368    ) {
 369        let mouse_position = cx.mouse_position();
 370        if !text_hitbox.is_hovered(cx) {
 371            return;
 372        }
 373
 374        editor.update_hovered_link(
 375            position_map.point_for_position(text_hitbox.bounds, mouse_position),
 376            &position_map.snapshot,
 377            event.modifiers,
 378            cx,
 379        )
 380    }
 381
 382    fn mouse_left_down(
 383        editor: &mut Editor,
 384        event: &MouseDownEvent,
 385        position_map: &PositionMap,
 386        text_hitbox: &Hitbox,
 387        gutter_hitbox: &Hitbox,
 388        cx: &mut ViewContext<Editor>,
 389    ) {
 390        if cx.default_prevented() {
 391            return;
 392        }
 393
 394        let mut click_count = event.click_count;
 395        let modifiers = event.modifiers;
 396
 397        if gutter_hitbox.is_hovered(cx) {
 398            click_count = 3; // Simulate triple-click when clicking the gutter to select lines
 399        } else if !text_hitbox.is_hovered(cx) {
 400            return;
 401        }
 402
 403        let point_for_position =
 404            position_map.point_for_position(text_hitbox.bounds, event.position);
 405        let position = point_for_position.previous_valid;
 406        if modifiers.shift && modifiers.alt {
 407            editor.select(
 408                SelectPhase::BeginColumnar {
 409                    position,
 410                    goal_column: point_for_position.exact_unclipped.column(),
 411                },
 412                cx,
 413            );
 414        } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.command {
 415            editor.select(
 416                SelectPhase::Extend {
 417                    position,
 418                    click_count,
 419                },
 420                cx,
 421            );
 422        } else {
 423            editor.select(
 424                SelectPhase::Begin {
 425                    position,
 426                    add: modifiers.alt,
 427                    click_count,
 428                },
 429                cx,
 430            );
 431        }
 432
 433        cx.stop_propagation();
 434    }
 435
 436    fn mouse_right_down(
 437        editor: &mut Editor,
 438        event: &MouseDownEvent,
 439        position_map: &PositionMap,
 440        text_hitbox: &Hitbox,
 441        cx: &mut ViewContext<Editor>,
 442    ) {
 443        if !text_hitbox.is_hovered(cx) {
 444            return;
 445        }
 446        let point_for_position =
 447            position_map.point_for_position(text_hitbox.bounds, event.position);
 448        mouse_context_menu::deploy_context_menu(
 449            editor,
 450            event.position,
 451            point_for_position.previous_valid,
 452            cx,
 453        );
 454        cx.stop_propagation();
 455    }
 456
 457    fn mouse_up(
 458        editor: &mut Editor,
 459        event: &MouseUpEvent,
 460        position_map: &PositionMap,
 461        text_hitbox: &Hitbox,
 462        cx: &mut ViewContext<Editor>,
 463    ) {
 464        let end_selection = editor.has_pending_selection();
 465        let pending_nonempty_selections = editor.has_pending_nonempty_selection();
 466
 467        if end_selection {
 468            editor.select(SelectPhase::End, cx);
 469        }
 470
 471        if !pending_nonempty_selections && event.modifiers.command && text_hitbox.is_hovered(cx) {
 472            let point = position_map.point_for_position(text_hitbox.bounds, event.position);
 473            editor.handle_click_hovered_link(point, event.modifiers, cx);
 474
 475            cx.stop_propagation();
 476        } else if end_selection {
 477            cx.stop_propagation();
 478        }
 479    }
 480
 481    fn mouse_dragged(
 482        editor: &mut Editor,
 483        event: &MouseMoveEvent,
 484        position_map: &PositionMap,
 485        text_bounds: Bounds<Pixels>,
 486        cx: &mut ViewContext<Editor>,
 487    ) {
 488        if !editor.has_pending_selection() {
 489            return;
 490        }
 491
 492        let point_for_position = position_map.point_for_position(text_bounds, event.position);
 493        let mut scroll_delta = gpui::Point::<f32>::default();
 494        let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
 495        let top = text_bounds.origin.y + vertical_margin;
 496        let bottom = text_bounds.lower_left().y - vertical_margin;
 497        if event.position.y < top {
 498            scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
 499        }
 500        if event.position.y > bottom {
 501            scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
 502        }
 503
 504        let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
 505        let left = text_bounds.origin.x + horizontal_margin;
 506        let right = text_bounds.upper_right().x - horizontal_margin;
 507        if event.position.x < left {
 508            scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
 509        }
 510        if event.position.x > right {
 511            scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
 512        }
 513
 514        editor.select(
 515            SelectPhase::Update {
 516                position: point_for_position.previous_valid,
 517                goal_column: point_for_position.exact_unclipped.column(),
 518                scroll_delta,
 519            },
 520            cx,
 521        );
 522    }
 523
 524    fn mouse_moved(
 525        editor: &mut Editor,
 526        event: &MouseMoveEvent,
 527        position_map: &PositionMap,
 528        text_hitbox: &Hitbox,
 529        gutter_hitbox: &Hitbox,
 530        cx: &mut ViewContext<Editor>,
 531    ) {
 532        let modifiers = event.modifiers;
 533        let gutter_hovered = gutter_hitbox.is_hovered(cx);
 534        editor.set_gutter_hovered(gutter_hovered, cx);
 535
 536        // Don't trigger hover popover if mouse is hovering over context menu
 537        if text_hitbox.is_hovered(cx) {
 538            let point_for_position =
 539                position_map.point_for_position(text_hitbox.bounds, event.position);
 540
 541            editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
 542
 543            if let Some(point) = point_for_position.as_valid() {
 544                hover_at(editor, Some(point), cx);
 545                Self::update_visible_cursor(editor, point, position_map, cx);
 546            } else {
 547                hover_at(editor, None, cx);
 548            }
 549        } else {
 550            editor.hide_hovered_link(cx);
 551            hover_at(editor, None, cx);
 552            if gutter_hovered {
 553                cx.stop_propagation();
 554            }
 555        }
 556    }
 557
 558    fn update_visible_cursor(
 559        editor: &mut Editor,
 560        point: DisplayPoint,
 561        position_map: &PositionMap,
 562        cx: &mut ViewContext<Editor>,
 563    ) {
 564        let snapshot = &position_map.snapshot;
 565        let Some(hub) = editor.collaboration_hub() else {
 566            return;
 567        };
 568        let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
 569            ..DisplayPoint::new(
 570                point.row(),
 571                (point.column() + 1).min(snapshot.line_len(point.row())),
 572            );
 573
 574        let range = snapshot
 575            .buffer_snapshot
 576            .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
 577            ..snapshot
 578                .buffer_snapshot
 579                .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
 580
 581        let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
 582            return;
 583        };
 584        let key = crate::HoveredCursor {
 585            replica_id: selection.replica_id,
 586            selection_id: selection.selection.id,
 587        };
 588        editor.hovered_cursors.insert(
 589            key.clone(),
 590            cx.spawn(|editor, mut cx| async move {
 591                cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 592                editor
 593                    .update(&mut cx, |editor, cx| {
 594                        editor.hovered_cursors.remove(&key);
 595                        cx.notify();
 596                    })
 597                    .ok();
 598            }),
 599        );
 600        cx.notify()
 601    }
 602
 603    fn layout_selections(
 604        &self,
 605        start_anchor: Anchor,
 606        end_anchor: Anchor,
 607        snapshot: &EditorSnapshot,
 608        start_row: u32,
 609        end_row: u32,
 610        cx: &mut ElementContext,
 611    ) -> (
 612        Vec<(PlayerColor, Vec<SelectionLayout>)>,
 613        BTreeMap<u32, bool>,
 614        Option<DisplayPoint>,
 615    ) {
 616        let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
 617        let mut active_rows = BTreeMap::new();
 618        let mut newest_selection_head = None;
 619        let editor = self.editor.read(cx);
 620
 621        if editor.show_local_selections {
 622            let mut local_selections: Vec<Selection<Point>> = editor
 623                .selections
 624                .disjoint_in_range(start_anchor..end_anchor, cx);
 625            local_selections.extend(editor.selections.pending(cx));
 626            let mut layouts = Vec::new();
 627            let newest = editor.selections.newest(cx);
 628            for selection in local_selections.drain(..) {
 629                let is_empty = selection.start == selection.end;
 630                let is_newest = selection == newest;
 631
 632                let layout = SelectionLayout::new(
 633                    selection,
 634                    editor.selections.line_mode,
 635                    editor.cursor_shape,
 636                    &snapshot.display_snapshot,
 637                    is_newest,
 638                    editor.leader_peer_id.is_none(),
 639                    None,
 640                );
 641                if is_newest {
 642                    newest_selection_head = Some(layout.head);
 643                }
 644
 645                for row in cmp::max(layout.active_rows.start, start_row)
 646                    ..=cmp::min(layout.active_rows.end, end_row)
 647                {
 648                    let contains_non_empty_selection = active_rows.entry(row).or_insert(!is_empty);
 649                    *contains_non_empty_selection |= !is_empty;
 650                }
 651                layouts.push(layout);
 652            }
 653
 654            let player = if editor.read_only(cx) {
 655                cx.theme().players().read_only()
 656            } else {
 657                self.style.local_player
 658            };
 659
 660            selections.push((player, layouts));
 661        }
 662
 663        if let Some(collaboration_hub) = &editor.collaboration_hub {
 664            // When following someone, render the local selections in their color.
 665            if let Some(leader_id) = editor.leader_peer_id {
 666                if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
 667                    if let Some(participant_index) = collaboration_hub
 668                        .user_participant_indices(cx)
 669                        .get(&collaborator.user_id)
 670                    {
 671                        if let Some((local_selection_style, _)) = selections.first_mut() {
 672                            *local_selection_style = cx
 673                                .theme()
 674                                .players()
 675                                .color_for_participant(participant_index.0);
 676                        }
 677                    }
 678                }
 679            }
 680
 681            let mut remote_selections = HashMap::default();
 682            for selection in snapshot.remote_selections_in_range(
 683                &(start_anchor..end_anchor),
 684                collaboration_hub.as_ref(),
 685                cx,
 686            ) {
 687                let selection_style = if let Some(participant_index) = selection.participant_index {
 688                    cx.theme()
 689                        .players()
 690                        .color_for_participant(participant_index.0)
 691                } else {
 692                    cx.theme().players().absent()
 693                };
 694
 695                // Don't re-render the leader's selections, since the local selections
 696                // match theirs.
 697                if Some(selection.peer_id) == editor.leader_peer_id {
 698                    continue;
 699                }
 700                let key = HoveredCursor {
 701                    replica_id: selection.replica_id,
 702                    selection_id: selection.selection.id,
 703                };
 704
 705                let is_shown =
 706                    editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
 707
 708                remote_selections
 709                    .entry(selection.replica_id)
 710                    .or_insert((selection_style, Vec::new()))
 711                    .1
 712                    .push(SelectionLayout::new(
 713                        selection.selection,
 714                        selection.line_mode,
 715                        selection.cursor_shape,
 716                        &snapshot.display_snapshot,
 717                        false,
 718                        false,
 719                        if is_shown { selection.user_name } else { None },
 720                    ));
 721            }
 722
 723            selections.extend(remote_selections.into_values());
 724        }
 725        (selections, active_rows, newest_selection_head)
 726    }
 727
 728    #[allow(clippy::too_many_arguments)]
 729    fn layout_folds(
 730        &self,
 731        snapshot: &EditorSnapshot,
 732        content_origin: gpui::Point<Pixels>,
 733        visible_anchor_range: Range<Anchor>,
 734        visible_display_row_range: Range<u32>,
 735        scroll_pixel_position: gpui::Point<Pixels>,
 736        line_height: Pixels,
 737        line_layouts: &[LineWithInvisibles],
 738        cx: &mut ElementContext,
 739    ) -> Vec<FoldLayout> {
 740        snapshot
 741            .folds_in_range(visible_anchor_range.clone())
 742            .filter_map(|fold| {
 743                let fold_range = fold.range.clone();
 744                let display_range = fold.range.start.to_display_point(&snapshot)
 745                    ..fold.range.end.to_display_point(&snapshot);
 746                debug_assert_eq!(display_range.start.row(), display_range.end.row());
 747                let row = display_range.start.row();
 748                debug_assert!(row < visible_display_row_range.end);
 749                let line_layout = line_layouts
 750                    .get((row - visible_display_row_range.start) as usize)
 751                    .map(|l| &l.line)?;
 752
 753                let start_x = content_origin.x
 754                    + line_layout.x_for_index(display_range.start.column() as usize)
 755                    - scroll_pixel_position.x;
 756                let start_y = content_origin.y + row as f32 * line_height - scroll_pixel_position.y;
 757                let end_x = content_origin.x
 758                    + line_layout.x_for_index(display_range.end.column() as usize)
 759                    - scroll_pixel_position.x;
 760
 761                let fold_bounds = Bounds {
 762                    origin: point(start_x, start_y),
 763                    size: size(end_x - start_x, line_height),
 764                };
 765
 766                let mut hover_element = div()
 767                    .id(fold.id)
 768                    .size_full()
 769                    .cursor_pointer()
 770                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 771                    .on_click(
 772                        cx.listener_for(&self.editor, move |editor: &mut Editor, _, cx| {
 773                            editor.unfold_ranges(
 774                                [fold_range.start..fold_range.end],
 775                                true,
 776                                false,
 777                                cx,
 778                            );
 779                            cx.stop_propagation();
 780                        }),
 781                    )
 782                    .into_any();
 783                hover_element.layout(fold_bounds.origin, fold_bounds.size.into(), cx);
 784                Some(FoldLayout {
 785                    display_range,
 786                    hover_element,
 787                })
 788            })
 789            .collect()
 790    }
 791
 792    #[allow(clippy::too_many_arguments)]
 793    fn layout_cursors(
 794        &self,
 795        snapshot: &EditorSnapshot,
 796        selections: &[(PlayerColor, Vec<SelectionLayout>)],
 797        visible_display_row_range: Range<u32>,
 798        line_layouts: &[LineWithInvisibles],
 799        text_hitbox: &Hitbox,
 800        content_origin: gpui::Point<Pixels>,
 801        scroll_pixel_position: gpui::Point<Pixels>,
 802        line_height: Pixels,
 803        em_width: Pixels,
 804        cx: &mut ElementContext,
 805    ) -> Vec<CursorLayout> {
 806        self.editor.update(cx, |editor, cx| {
 807            let mut cursors = Vec::new();
 808            for (player_color, selections) in selections {
 809                for selection in selections {
 810                    let cursor_position = selection.head;
 811                    if (selection.is_local && !editor.show_local_cursors(cx))
 812                        || !visible_display_row_range.contains(&cursor_position.row())
 813                    {
 814                        continue;
 815                    }
 816
 817                    let cursor_row_layout = &line_layouts
 818                        [(cursor_position.row() - visible_display_row_range.start) as usize]
 819                        .line;
 820                    let cursor_column = cursor_position.column() as usize;
 821
 822                    let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
 823                    let mut block_width =
 824                        cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
 825                    if block_width == Pixels::ZERO {
 826                        block_width = em_width;
 827                    }
 828                    let block_text = if let CursorShape::Block = selection.cursor_shape {
 829                        snapshot
 830                            .chars_at(cursor_position)
 831                            .next()
 832                            .and_then(|(character, _)| {
 833                                let text = if character == '\n' {
 834                                    SharedString::from(" ")
 835                                } else {
 836                                    SharedString::from(character.to_string())
 837                                };
 838                                let len = text.len();
 839                                cx.text_system()
 840                                    .shape_line(
 841                                        text,
 842                                        cursor_row_layout.font_size,
 843                                        &[TextRun {
 844                                            len,
 845                                            font: self.style.text.font(),
 846                                            color: self.style.background,
 847                                            background_color: None,
 848                                            strikethrough: None,
 849                                            underline: None,
 850                                        }],
 851                                    )
 852                                    .log_err()
 853                            })
 854                    } else {
 855                        None
 856                    };
 857
 858                    let x = cursor_character_x - scroll_pixel_position.x;
 859                    let y = cursor_position.row() as f32 * line_height - scroll_pixel_position.y;
 860                    if selection.is_newest {
 861                        editor.pixel_position_of_newest_cursor = Some(point(
 862                            text_hitbox.origin.x + x + block_width / 2.,
 863                            text_hitbox.origin.y + y + line_height / 2.,
 864                        ))
 865                    }
 866
 867                    let mut cursor = CursorLayout {
 868                        color: player_color.cursor,
 869                        block_width,
 870                        origin: point(x, y),
 871                        line_height,
 872                        shape: selection.cursor_shape,
 873                        block_text,
 874                        cursor_name: None,
 875                    };
 876                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 877                        string: name,
 878                        color: self.style.background,
 879                        is_top_row: cursor_position.row() == 0,
 880                    });
 881                    cx.with_element_context(|cx| cursor.layout(content_origin, cursor_name, cx));
 882                    cursors.push(cursor);
 883                }
 884            }
 885            cursors
 886        })
 887    }
 888
 889    fn layout_scrollbar(
 890        &self,
 891        snapshot: &EditorSnapshot,
 892        bounds: Bounds<Pixels>,
 893        scroll_position: gpui::Point<f32>,
 894        line_height: Pixels,
 895        height_in_lines: f32,
 896        cx: &mut ElementContext,
 897    ) -> Option<ScrollbarLayout> {
 898        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 899        let show_scrollbars = match scrollbar_settings.show {
 900            ShowScrollbar::Auto => {
 901                let editor = self.editor.read(cx);
 902                let is_singleton = editor.is_singleton(cx);
 903                // Git
 904                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
 905                    ||
 906                    // Selections
 907                    (is_singleton && scrollbar_settings.selections && editor.has_background_highlights::<BufferSearchHighlights>())
 908                    ||
 909                    // Symbols Selections
 910                    (is_singleton && scrollbar_settings.symbols_selections && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
 911                    ||
 912                    // Diagnostics
 913                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
 914                    ||
 915                    // Scrollmanager
 916                    editor.scroll_manager.scrollbars_visible()
 917            }
 918            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 919            ShowScrollbar::Always => true,
 920            ShowScrollbar::Never => false,
 921        };
 922        if snapshot.mode != EditorMode::Full {
 923            return None;
 924        }
 925
 926        let visible_row_range = scroll_position.y..scroll_position.y + height_in_lines;
 927
 928        // If a drag took place after we started dragging the scrollbar,
 929        // cancel the scrollbar drag.
 930        if cx.has_active_drag() {
 931            self.editor.update(cx, |editor, cx| {
 932                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
 933            });
 934        }
 935
 936        let track_bounds = Bounds::from_corners(
 937            point(self.scrollbar_left(&bounds), bounds.origin.y),
 938            point(bounds.lower_right().x, bounds.lower_left().y),
 939        );
 940
 941        let scroll_height = snapshot.max_point().row() as f32 + height_in_lines;
 942        let mut height = bounds.size.height;
 943        let mut first_row_y_offset = px(0.0);
 944
 945        // Impose a minimum height on the scrollbar thumb
 946        let row_height = height / scroll_height;
 947        let min_thumb_height = line_height;
 948        let thumb_height = height_in_lines * row_height;
 949        if thumb_height < min_thumb_height {
 950            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
 951            height -= min_thumb_height - thumb_height;
 952        }
 953
 954        Some(ScrollbarLayout {
 955            hitbox: cx.insert_hitbox(track_bounds, false),
 956            visible_row_range,
 957            height,
 958            scroll_height,
 959            first_row_y_offset,
 960            row_height,
 961            visible: show_scrollbars,
 962        })
 963    }
 964
 965    #[allow(clippy::too_many_arguments)]
 966    fn layout_gutter_fold_indicators(
 967        &self,
 968        fold_statuses: Vec<Option<(FoldStatus, u32, bool)>>,
 969        line_height: Pixels,
 970        gutter_dimensions: &GutterDimensions,
 971        gutter_settings: crate::editor_settings::Gutter,
 972        scroll_pixel_position: gpui::Point<Pixels>,
 973        gutter_hitbox: &Hitbox,
 974        cx: &mut ElementContext,
 975    ) -> Vec<Option<AnyElement>> {
 976        let mut indicators = self.editor.update(cx, |editor, cx| {
 977            editor.render_fold_indicators(
 978                fold_statuses,
 979                &self.style,
 980                editor.gutter_hovered,
 981                line_height,
 982                gutter_dimensions.margin,
 983                cx,
 984            )
 985        });
 986
 987        for (ix, fold_indicator) in indicators.iter_mut().enumerate() {
 988            if let Some(fold_indicator) = fold_indicator {
 989                debug_assert!(gutter_settings.folds);
 990                let available_space = size(
 991                    AvailableSpace::MinContent,
 992                    AvailableSpace::Definite(line_height * 0.55),
 993                );
 994                let fold_indicator_size = fold_indicator.measure(available_space, cx);
 995
 996                let position = point(
 997                    gutter_dimensions.width - gutter_dimensions.right_padding,
 998                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
 999                );
1000                let centering_offset = point(
1001                    (gutter_dimensions.right_padding + gutter_dimensions.margin
1002                        - fold_indicator_size.width)
1003                        / 2.,
1004                    (line_height - fold_indicator_size.height) / 2.,
1005                );
1006                let origin = gutter_hitbox.origin + position + centering_offset;
1007                fold_indicator.layout(origin, available_space, cx);
1008            }
1009        }
1010
1011        indicators
1012    }
1013
1014    //Folds contained in a hunk are ignored apart from shrinking visual size
1015    //If a fold contains any hunks then that fold line is marked as modified
1016    fn layout_git_gutters(
1017        &self,
1018        display_rows: Range<u32>,
1019        snapshot: &EditorSnapshot,
1020    ) -> Vec<DisplayDiffHunk> {
1021        let buffer_snapshot = &snapshot.buffer_snapshot;
1022
1023        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1024            .to_point(snapshot)
1025            .row;
1026        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1027            .to_point(snapshot)
1028            .row;
1029
1030        buffer_snapshot
1031            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1032            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1033            .dedup()
1034            .collect()
1035    }
1036
1037    fn layout_code_actions_indicator(
1038        &self,
1039        line_height: Pixels,
1040        newest_selection_head: DisplayPoint,
1041        scroll_pixel_position: gpui::Point<Pixels>,
1042        gutter_dimensions: &GutterDimensions,
1043        gutter_hitbox: &Hitbox,
1044        cx: &mut ElementContext,
1045    ) -> Option<AnyElement> {
1046        let mut active = false;
1047        let mut button = None;
1048        self.editor.update(cx, |editor, cx| {
1049            active = matches!(
1050                editor.context_menu.read().as_ref(),
1051                Some(crate::ContextMenu::CodeActions(_))
1052            );
1053            button = editor.render_code_actions_indicator(&self.style, active, cx);
1054        });
1055
1056        let mut button = button?.into_any_element();
1057        let available_space = size(
1058            AvailableSpace::MinContent,
1059            AvailableSpace::Definite(line_height),
1060        );
1061        let indicator_size = button.measure(available_space, cx);
1062
1063        let mut x = Pixels::ZERO;
1064        let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1065        // Center indicator.
1066        x +=
1067            (gutter_dimensions.margin + gutter_dimensions.left_padding - indicator_size.width) / 2.;
1068        y += (line_height - indicator_size.height) / 2.;
1069        button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1070        Some(button)
1071    }
1072
1073    fn calculate_relative_line_numbers(
1074        &self,
1075        snapshot: &EditorSnapshot,
1076        rows: &Range<u32>,
1077        relative_to: Option<u32>,
1078    ) -> HashMap<u32, u32> {
1079        let mut relative_rows: HashMap<u32, u32> = Default::default();
1080        let Some(relative_to) = relative_to else {
1081            return relative_rows;
1082        };
1083
1084        let start = rows.start.min(relative_to);
1085        let end = rows.end.max(relative_to);
1086
1087        let buffer_rows = snapshot
1088            .buffer_rows(start)
1089            .take(1 + (end - start) as usize)
1090            .collect::<Vec<_>>();
1091
1092        let head_idx = relative_to - start;
1093        let mut delta = 1;
1094        let mut i = head_idx + 1;
1095        while i < buffer_rows.len() as u32 {
1096            if buffer_rows[i as usize].is_some() {
1097                if rows.contains(&(i + start)) {
1098                    relative_rows.insert(i + start, delta);
1099                }
1100                delta += 1;
1101            }
1102            i += 1;
1103        }
1104        delta = 1;
1105        i = head_idx.min(buffer_rows.len() as u32 - 1);
1106        while i > 0 && buffer_rows[i as usize].is_none() {
1107            i -= 1;
1108        }
1109
1110        while i > 0 {
1111            i -= 1;
1112            if buffer_rows[i as usize].is_some() {
1113                if rows.contains(&(i + start)) {
1114                    relative_rows.insert(i + start, delta);
1115                }
1116                delta += 1;
1117            }
1118        }
1119
1120        relative_rows
1121    }
1122
1123    fn layout_line_numbers(
1124        &self,
1125        rows: Range<u32>,
1126        active_rows: &BTreeMap<u32, bool>,
1127        newest_selection_head: Option<DisplayPoint>,
1128        snapshot: &EditorSnapshot,
1129        cx: &ElementContext,
1130    ) -> (
1131        Vec<Option<ShapedLine>>,
1132        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1133    ) {
1134        let editor = self.editor.read(cx);
1135        let is_singleton = editor.is_singleton(cx);
1136        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1137            let newest = editor.selections.newest::<Point>(cx);
1138            SelectionLayout::new(
1139                newest,
1140                editor.selections.line_mode,
1141                editor.cursor_shape,
1142                &snapshot.display_snapshot,
1143                true,
1144                true,
1145                None,
1146            )
1147            .head
1148        });
1149        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1150        let include_line_numbers =
1151            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1152        let include_fold_statuses =
1153            EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1154        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1155        let mut fold_statuses = Vec::with_capacity(rows.len());
1156        let mut line_number = String::new();
1157        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1158        let relative_to = if is_relative {
1159            Some(newest_selection_head.row())
1160        } else {
1161            None
1162        };
1163
1164        let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1165
1166        for (ix, row) in snapshot
1167            .buffer_rows(rows.start)
1168            .take((rows.end - rows.start) as usize)
1169            .enumerate()
1170        {
1171            let display_row = rows.start + ix as u32;
1172            let (active, color) = if active_rows.contains_key(&display_row) {
1173                (true, cx.theme().colors().editor_active_line_number)
1174            } else {
1175                (false, cx.theme().colors().editor_line_number)
1176            };
1177            if let Some(buffer_row) = row {
1178                if include_line_numbers {
1179                    line_number.clear();
1180                    let default_number = buffer_row + 1;
1181                    let number = relative_rows
1182                        .get(&(ix as u32 + rows.start))
1183                        .unwrap_or(&default_number);
1184                    write!(&mut line_number, "{}", number).unwrap();
1185                    let run = TextRun {
1186                        len: line_number.len(),
1187                        font: self.style.text.font(),
1188                        color,
1189                        background_color: None,
1190                        underline: None,
1191                        strikethrough: None,
1192                    };
1193                    let shaped_line = cx
1194                        .text_system()
1195                        .shape_line(line_number.clone().into(), font_size, &[run])
1196                        .unwrap();
1197                    shaped_line_numbers.push(Some(shaped_line));
1198                }
1199                if include_fold_statuses {
1200                    fold_statuses.push(
1201                        is_singleton
1202                            .then(|| {
1203                                snapshot
1204                                    .fold_for_line(buffer_row)
1205                                    .map(|fold_status| (fold_status, buffer_row, active))
1206                            })
1207                            .flatten(),
1208                    )
1209                }
1210            } else {
1211                fold_statuses.push(None);
1212                shaped_line_numbers.push(None);
1213            }
1214        }
1215
1216        (shaped_line_numbers, fold_statuses)
1217    }
1218
1219    fn layout_lines(
1220        &self,
1221        rows: Range<u32>,
1222        line_number_layouts: &[Option<ShapedLine>],
1223        snapshot: &EditorSnapshot,
1224        cx: &ElementContext,
1225    ) -> Vec<LineWithInvisibles> {
1226        if rows.start >= rows.end {
1227            return Vec::new();
1228        }
1229
1230        // Show the placeholder when the editor is empty
1231        if snapshot.is_empty() {
1232            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1233            let placeholder_color = cx.theme().colors().text_placeholder;
1234            let placeholder_text = snapshot.placeholder_text();
1235
1236            let placeholder_lines = placeholder_text
1237                .as_ref()
1238                .map_or("", AsRef::as_ref)
1239                .split('\n')
1240                .skip(rows.start as usize)
1241                .chain(iter::repeat(""))
1242                .take(rows.len());
1243            placeholder_lines
1244                .filter_map(move |line| {
1245                    let run = TextRun {
1246                        len: line.len(),
1247                        font: self.style.text.font(),
1248                        color: placeholder_color,
1249                        background_color: None,
1250                        underline: Default::default(),
1251                        strikethrough: None,
1252                    };
1253                    cx.text_system()
1254                        .shape_line(line.to_string().into(), font_size, &[run])
1255                        .log_err()
1256                })
1257                .map(|line| LineWithInvisibles {
1258                    line,
1259                    invisibles: Vec::new(),
1260                })
1261                .collect()
1262        } else {
1263            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1264            LineWithInvisibles::from_chunks(
1265                chunks,
1266                &self.style.text,
1267                MAX_LINE_LEN,
1268                rows.len(),
1269                line_number_layouts,
1270                snapshot.mode,
1271                cx,
1272            )
1273        }
1274    }
1275
1276    #[allow(clippy::too_many_arguments)]
1277    fn build_blocks(
1278        &self,
1279        rows: Range<u32>,
1280        snapshot: &EditorSnapshot,
1281        hitbox: &Hitbox,
1282        text_hitbox: &Hitbox,
1283        scroll_width: &mut Pixels,
1284        gutter_dimensions: &GutterDimensions,
1285        em_width: Pixels,
1286        text_x: Pixels,
1287        line_height: Pixels,
1288        line_layouts: &[LineWithInvisibles],
1289        cx: &mut ElementContext,
1290    ) -> Vec<BlockLayout> {
1291        let mut block_id = 0;
1292        let (fixed_blocks, non_fixed_blocks) = snapshot
1293            .blocks_in_range(rows.clone())
1294            .partition::<Vec<_>, _>(|(_, block)| match block {
1295                TransformBlock::ExcerptHeader { .. } => false,
1296                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1297            });
1298
1299        let render_block = |block: &TransformBlock,
1300                            available_space: Size<AvailableSpace>,
1301                            block_id: usize,
1302                            cx: &mut ElementContext| {
1303            let mut element = match block {
1304                TransformBlock::Custom(block) => {
1305                    let align_to = block
1306                        .position()
1307                        .to_point(&snapshot.buffer_snapshot)
1308                        .to_display_point(snapshot);
1309                    let anchor_x = text_x
1310                        + if rows.contains(&align_to.row()) {
1311                            line_layouts[(align_to.row() - rows.start) as usize]
1312                                .line
1313                                .x_for_index(align_to.column() as usize)
1314                        } else {
1315                            layout_line(align_to.row(), snapshot, &self.style, cx)
1316                                .unwrap()
1317                                .x_for_index(align_to.column() as usize)
1318                        };
1319
1320                    block.render(&mut BlockContext {
1321                        context: cx,
1322                        anchor_x,
1323                        gutter_dimensions,
1324                        line_height,
1325                        em_width,
1326                        block_id,
1327                        max_width: text_hitbox.size.width.max(*scroll_width),
1328                        editor_style: &self.style,
1329                    })
1330                }
1331
1332                TransformBlock::ExcerptHeader {
1333                    buffer,
1334                    range,
1335                    starts_new_buffer,
1336                    ..
1337                } => {
1338                    let include_root = self
1339                        .editor
1340                        .read(cx)
1341                        .project
1342                        .as_ref()
1343                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1344                        .unwrap_or_default();
1345
1346                    let jump_handler = project::File::from_dyn(buffer.file()).map(|file| {
1347                        let jump_path = ProjectPath {
1348                            worktree_id: file.worktree_id(cx),
1349                            path: file.path.clone(),
1350                        };
1351                        let jump_anchor = range
1352                            .primary
1353                            .as_ref()
1354                            .map_or(range.context.start, |primary| primary.start);
1355                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1356
1357                        cx.listener_for(&self.editor, move |editor, _, cx| {
1358                            editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
1359                        })
1360                    });
1361
1362                    let element = if *starts_new_buffer {
1363                        let path = buffer.resolve_file_path(cx, include_root);
1364                        let mut filename = None;
1365                        let mut parent_path = None;
1366                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1367                        if let Some(path) = path {
1368                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1369                            parent_path = path
1370                                .parent()
1371                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1372                        }
1373
1374                        v_flex()
1375                            .id(("path header container", block_id))
1376                            .size_full()
1377                            .justify_center()
1378                            .p(gpui::px(6.))
1379                            .child(
1380                                h_flex()
1381                                    .id("path header block")
1382                                    .size_full()
1383                                    .pl(gpui::px(12.))
1384                                    .pr(gpui::px(8.))
1385                                    .rounded_md()
1386                                    .shadow_md()
1387                                    .border()
1388                                    .border_color(cx.theme().colors().border)
1389                                    .bg(cx.theme().colors().editor_subheader_background)
1390                                    .justify_between()
1391                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
1392                                    .child(
1393                                        h_flex().gap_3().child(
1394                                            h_flex()
1395                                                .gap_2()
1396                                                .child(
1397                                                    filename
1398                                                        .map(SharedString::from)
1399                                                        .unwrap_or_else(|| "untitled".into()),
1400                                                )
1401                                                .when_some(parent_path, |then, path| {
1402                                                    then.child(
1403                                                        div().child(path).text_color(
1404                                                            cx.theme().colors().text_muted,
1405                                                        ),
1406                                                    )
1407                                                }),
1408                                        ),
1409                                    )
1410                                    .when_some(jump_handler, |this, jump_handler| {
1411                                        this.cursor_pointer()
1412                                            .tooltip(|cx| {
1413                                                Tooltip::for_action(
1414                                                    "Jump to Buffer",
1415                                                    &OpenExcerpts,
1416                                                    cx,
1417                                                )
1418                                            })
1419                                            .on_mouse_down(MouseButton::Left, |_, cx| {
1420                                                cx.stop_propagation()
1421                                            })
1422                                            .on_click(jump_handler)
1423                                    }),
1424                            )
1425                    } else {
1426                        h_flex()
1427                            .id(("collapsed context", block_id))
1428                            .size_full()
1429                            .gap(gutter_dimensions.left_padding + gutter_dimensions.right_padding)
1430                            .child(
1431                                h_flex()
1432                                    .justify_end()
1433                                    .flex_none()
1434                                    .w(gutter_dimensions.width
1435                                        - (gutter_dimensions.left_padding
1436                                            + gutter_dimensions.right_padding))
1437                                    .h_full()
1438                                    .text_buffer(cx)
1439                                    .text_color(cx.theme().colors().editor_line_number)
1440                                    .child("..."),
1441                            )
1442                            .child(
1443                                ButtonLike::new("jump to collapsed context")
1444                                    .style(ButtonStyle::Transparent)
1445                                    .full_width()
1446                                    .child(
1447                                        div()
1448                                            .h_px()
1449                                            .w_full()
1450                                            .bg(cx.theme().colors().border_variant)
1451                                            .group_hover("", |style| {
1452                                                style.bg(cx.theme().colors().border)
1453                                            }),
1454                                    )
1455                                    .when_some(jump_handler, |this, jump_handler| {
1456                                        this.on_click(jump_handler).tooltip(|cx| {
1457                                            Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx)
1458                                        })
1459                                    }),
1460                            )
1461                    };
1462                    element.into_any()
1463                }
1464            };
1465
1466            let size = element.measure(available_space, cx);
1467            (element, size)
1468        };
1469
1470        let mut fixed_block_max_width = Pixels::ZERO;
1471        let mut blocks = Vec::new();
1472        for (row, block) in fixed_blocks {
1473            let available_space = size(
1474                AvailableSpace::MinContent,
1475                AvailableSpace::Definite(block.height() as f32 * line_height),
1476            );
1477            let (element, element_size) = render_block(block, available_space, block_id, cx);
1478            block_id += 1;
1479            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1480            blocks.push(BlockLayout {
1481                row,
1482                element,
1483                available_space,
1484                style: BlockStyle::Fixed,
1485            });
1486        }
1487        for (row, block) in non_fixed_blocks {
1488            let style = match block {
1489                TransformBlock::Custom(block) => block.style(),
1490                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1491            };
1492            let width = match style {
1493                BlockStyle::Sticky => hitbox.size.width,
1494                BlockStyle::Flex => hitbox
1495                    .size
1496                    .width
1497                    .max(fixed_block_max_width)
1498                    .max(gutter_dimensions.width + *scroll_width),
1499                BlockStyle::Fixed => unreachable!(),
1500            };
1501            let available_space = size(
1502                AvailableSpace::Definite(width),
1503                AvailableSpace::Definite(block.height() as f32 * line_height),
1504            );
1505            let (element, _) = render_block(block, available_space, block_id, cx);
1506            block_id += 1;
1507            blocks.push(BlockLayout {
1508                row,
1509                element,
1510                available_space,
1511                style,
1512            });
1513        }
1514
1515        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1516        blocks
1517    }
1518
1519    fn layout_blocks(
1520        &self,
1521        blocks: &mut Vec<BlockLayout>,
1522        hitbox: &Hitbox,
1523        line_height: Pixels,
1524        scroll_pixel_position: gpui::Point<Pixels>,
1525        cx: &mut ElementContext,
1526    ) {
1527        for block in blocks {
1528            let mut origin = hitbox.origin
1529                + point(
1530                    Pixels::ZERO,
1531                    block.row as f32 * line_height - scroll_pixel_position.y,
1532                );
1533            if !matches!(block.style, BlockStyle::Sticky) {
1534                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1535            }
1536            block.element.layout(origin, block.available_space, cx);
1537        }
1538    }
1539
1540    #[allow(clippy::too_many_arguments)]
1541    fn layout_context_menu(
1542        &self,
1543        line_height: Pixels,
1544        hitbox: &Hitbox,
1545        text_hitbox: &Hitbox,
1546        content_origin: gpui::Point<Pixels>,
1547        start_row: u32,
1548        scroll_pixel_position: gpui::Point<Pixels>,
1549        line_layouts: &[LineWithInvisibles],
1550        newest_selection_head: DisplayPoint,
1551        cx: &mut ElementContext,
1552    ) -> bool {
1553        let max_height = cmp::min(
1554            12. * line_height,
1555            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1556        );
1557        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1558            if editor.context_menu_visible() {
1559                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1560            } else {
1561                None
1562            }
1563        }) else {
1564            return false;
1565        };
1566
1567        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1568        let context_menu_size = context_menu.measure(available_space, cx);
1569
1570        let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1571        let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1572        let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1573        let mut list_origin = content_origin + point(x, y);
1574        let list_width = context_menu_size.width;
1575        let list_height = context_menu_size.height;
1576
1577        // Snap the right edge of the list to the right edge of the window if
1578        // its horizontal bounds overflow.
1579        if list_origin.x + list_width > cx.viewport_size().width {
1580            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1581        }
1582
1583        if list_origin.y + list_height > text_hitbox.lower_right().y {
1584            list_origin.y -= line_height + list_height;
1585        }
1586
1587        cx.defer_draw(context_menu, list_origin, 1);
1588        true
1589    }
1590
1591    fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1592        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1593        let mut element = overlay()
1594            .position(mouse_context_menu.position)
1595            .child(mouse_context_menu.context_menu.clone())
1596            .anchor(AnchorCorner::TopLeft)
1597            .snap_to_window()
1598            .into_any();
1599        element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1600        Some(element)
1601    }
1602
1603    #[allow(clippy::too_many_arguments)]
1604    fn layout_hover_popovers(
1605        &self,
1606        snapshot: &EditorSnapshot,
1607        hitbox: &Hitbox,
1608        text_hitbox: &Hitbox,
1609        visible_display_row_range: Range<u32>,
1610        content_origin: gpui::Point<Pixels>,
1611        scroll_pixel_position: gpui::Point<Pixels>,
1612        line_layouts: &[LineWithInvisibles],
1613        line_height: Pixels,
1614        em_width: Pixels,
1615        cx: &mut ElementContext,
1616    ) {
1617        let max_size = size(
1618            (120. * em_width) // Default size
1619                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1620                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1621            (16. * line_height) // Default size
1622                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1623                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1624        );
1625
1626        let hover_popovers = self.editor.update(cx, |editor, cx| {
1627            editor.hover_state.render(
1628                &snapshot,
1629                &self.style,
1630                visible_display_row_range.clone(),
1631                max_size,
1632                editor.workspace.as_ref().map(|(w, _)| w.clone()),
1633                cx,
1634            )
1635        });
1636        let Some((position, mut hover_popovers)) = hover_popovers else {
1637            return;
1638        };
1639
1640        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1641
1642        // This is safe because we check on layout whether the required row is available
1643        let hovered_row_layout =
1644            &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1645
1646        // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1647        // height. This is the size we will use to decide whether to render popovers above or below
1648        // the hovered line.
1649        let first_size = hover_popovers[0].measure(available_space, cx);
1650        let height_to_reserve = first_size.height + 1.5 * MIN_POPOVER_LINE_HEIGHT * line_height;
1651
1652        // Compute Hovered Point
1653        let x =
1654            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1655        let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1656        let hovered_point = content_origin + point(x, y);
1657
1658        if hovered_point.y - height_to_reserve > Pixels::ZERO {
1659            // There is enough space above. Render popovers above the hovered point
1660            let mut current_y = hovered_point.y;
1661            for mut hover_popover in hover_popovers {
1662                let size = hover_popover.measure(available_space, cx);
1663                let mut popover_origin = point(hovered_point.x, current_y - size.height);
1664
1665                let x_out_of_bounds = text_hitbox.upper_right().x - (popover_origin.x + size.width);
1666                if x_out_of_bounds < Pixels::ZERO {
1667                    popover_origin.x = popover_origin.x + x_out_of_bounds;
1668                }
1669
1670                cx.defer_draw(hover_popover, popover_origin, 2);
1671
1672                current_y = popover_origin.y - HOVER_POPOVER_GAP;
1673            }
1674        } else {
1675            // There is not enough space above. Render popovers below the hovered point
1676            let mut current_y = hovered_point.y + line_height;
1677            for mut hover_popover in hover_popovers {
1678                let size = hover_popover.measure(available_space, cx);
1679                let mut popover_origin = point(hovered_point.x, current_y);
1680
1681                let x_out_of_bounds = text_hitbox.upper_right().x - (popover_origin.x + size.width);
1682                if x_out_of_bounds < Pixels::ZERO {
1683                    popover_origin.x = popover_origin.x + x_out_of_bounds;
1684                }
1685
1686                cx.defer_draw(hover_popover, popover_origin, 2);
1687
1688                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1689            }
1690        }
1691    }
1692
1693    fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
1694        cx.paint_layer(layout.hitbox.bounds, |cx| {
1695            let scroll_top =
1696                layout.position_map.snapshot.scroll_position().y * layout.position_map.line_height;
1697            let gutter_bg = cx.theme().colors().editor_gutter_background;
1698            cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
1699            cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
1700
1701            if let EditorMode::Full = layout.mode {
1702                let mut active_rows = layout.active_rows.iter().peekable();
1703                while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
1704                    let mut end_row = *start_row;
1705                    while active_rows.peek().map_or(false, |r| {
1706                        *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
1707                    }) {
1708                        active_rows.next().unwrap();
1709                        end_row += 1;
1710                    }
1711
1712                    if !contains_non_empty_selection {
1713                        let origin = point(
1714                            layout.hitbox.origin.x,
1715                            layout.hitbox.origin.y
1716                                + (layout.position_map.line_height * *start_row as f32)
1717                                - scroll_top,
1718                        );
1719                        let size = size(
1720                            layout.hitbox.size.width,
1721                            layout.position_map.line_height * (end_row - start_row + 1) as f32,
1722                        );
1723                        let active_line_bg = cx.theme().colors().editor_active_line_background;
1724                        cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
1725                    }
1726                }
1727
1728                let mut paint_highlight =
1729                    |highlight_row_start: u32, highlight_row_end: u32, color| {
1730                        let origin = point(
1731                            layout.hitbox.origin.x,
1732                            layout.hitbox.origin.y
1733                                + (layout.position_map.line_height * highlight_row_start as f32)
1734                                - scroll_top,
1735                        );
1736                        let size = size(
1737                            layout.hitbox.size.width,
1738                            layout.position_map.line_height
1739                                * (highlight_row_end + 1 - highlight_row_start) as f32,
1740                        );
1741                        cx.paint_quad(fill(Bounds { origin, size }, color));
1742                    };
1743
1744                let mut last_row = None;
1745                let mut highlight_row_start = 0u32;
1746                let mut highlight_row_end = 0u32;
1747                for (&row, &color) in &layout.highlighted_rows {
1748                    let paint = last_row.map_or(false, |(last_row, last_color)| {
1749                        last_color != color || last_row + 1 < row
1750                    });
1751
1752                    if paint {
1753                        let paint_range_is_unfinished = highlight_row_end == 0;
1754                        if paint_range_is_unfinished {
1755                            highlight_row_end = row;
1756                            last_row = None;
1757                        }
1758                        paint_highlight(highlight_row_start, highlight_row_end, color);
1759                        highlight_row_start = 0;
1760                        highlight_row_end = 0;
1761                        if !paint_range_is_unfinished {
1762                            highlight_row_start = row;
1763                            last_row = Some((row, color));
1764                        }
1765                    } else {
1766                        if last_row.is_none() {
1767                            highlight_row_start = row;
1768                        } else {
1769                            highlight_row_end = row;
1770                        }
1771                        last_row = Some((row, color));
1772                    }
1773                }
1774                if let Some((row, hsla)) = last_row {
1775                    highlight_row_end = row;
1776                    paint_highlight(highlight_row_start, highlight_row_end, hsla);
1777                }
1778
1779                let scroll_left =
1780                    layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
1781
1782                for (wrap_position, active) in layout.wrap_guides.iter() {
1783                    let x = (layout.text_hitbox.origin.x
1784                        + *wrap_position
1785                        + layout.position_map.em_width / 2.)
1786                        - scroll_left;
1787
1788                    let show_scrollbars = layout
1789                        .scrollbar_layout
1790                        .as_ref()
1791                        .map_or(false, |scrollbar| scrollbar.visible);
1792                    if x < layout.text_hitbox.origin.x
1793                        || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
1794                    {
1795                        continue;
1796                    }
1797
1798                    let color = if *active {
1799                        cx.theme().colors().editor_active_wrap_guide
1800                    } else {
1801                        cx.theme().colors().editor_wrap_guide
1802                    };
1803                    cx.paint_quad(fill(
1804                        Bounds {
1805                            origin: point(x, layout.text_hitbox.origin.y),
1806                            size: size(px(1.), layout.text_hitbox.size.height),
1807                        },
1808                        color,
1809                    ));
1810                }
1811            }
1812        })
1813    }
1814
1815    fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
1816        let line_height = layout.position_map.line_height;
1817
1818        let scroll_position = layout.position_map.snapshot.scroll_position();
1819        let scroll_top = scroll_position.y * line_height;
1820
1821        cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
1822
1823        let show_git_gutter = matches!(
1824            ProjectSettings::get_global(cx).git.git_gutter,
1825            Some(GitGutterSetting::TrackedFiles)
1826        );
1827
1828        if show_git_gutter {
1829            Self::paint_diff_hunks(layout, cx);
1830        }
1831
1832        for (ix, line) in layout.line_numbers.iter().enumerate() {
1833            if let Some(line) = line {
1834                let line_origin = layout.gutter_hitbox.origin
1835                    + point(
1836                        layout.gutter_hitbox.size.width
1837                            - line.width
1838                            - layout.gutter_dimensions.right_padding,
1839                        ix as f32 * line_height - (scroll_top % line_height),
1840                    );
1841
1842                line.paint(line_origin, line_height, cx).log_err();
1843            }
1844        }
1845
1846        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
1847            cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
1848                for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
1849                    fold_indicator.paint(cx);
1850                }
1851            });
1852
1853            if let Some(indicator) = layout.code_actions_indicator.as_mut() {
1854                indicator.paint(cx);
1855            }
1856        })
1857    }
1858
1859    fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
1860        if layout.display_hunks.is_empty() {
1861            return;
1862        }
1863
1864        let line_height = layout.position_map.line_height;
1865
1866        let scroll_position = layout.position_map.snapshot.scroll_position();
1867        let scroll_top = scroll_position.y * line_height;
1868
1869        cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
1870            for hunk in &layout.display_hunks {
1871                let (display_row_range, status) = match hunk {
1872                    //TODO: This rendering is entirely a horrible hack
1873                    &DisplayDiffHunk::Folded { display_row: row } => {
1874                        let start_y = row as f32 * line_height - scroll_top;
1875                        let end_y = start_y + line_height;
1876
1877                        let width = 0.275 * line_height;
1878                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
1879                        let highlight_size = size(width * 2., end_y - start_y);
1880                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
1881                        cx.paint_quad(quad(
1882                            highlight_bounds,
1883                            Corners::all(1. * line_height),
1884                            cx.theme().status().modified,
1885                            Edges::default(),
1886                            transparent_black(),
1887                        ));
1888
1889                        continue;
1890                    }
1891
1892                    DisplayDiffHunk::Unfolded {
1893                        display_row_range,
1894                        status,
1895                    } => (display_row_range, status),
1896                };
1897
1898                let color = match status {
1899                    DiffHunkStatus::Added => cx.theme().status().created,
1900                    DiffHunkStatus::Modified => cx.theme().status().modified,
1901
1902                    //TODO: This rendering is entirely a horrible hack
1903                    DiffHunkStatus::Removed => {
1904                        let row = display_row_range.start;
1905
1906                        let offset = line_height / 2.;
1907                        let start_y = row as f32 * line_height - offset - scroll_top;
1908                        let end_y = start_y + line_height;
1909
1910                        let width = 0.275 * line_height;
1911                        let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
1912                        let highlight_size = size(width * 2., end_y - start_y);
1913                        let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
1914                        cx.paint_quad(quad(
1915                            highlight_bounds,
1916                            Corners::all(1. * line_height),
1917                            cx.theme().status().deleted,
1918                            Edges::default(),
1919                            transparent_black(),
1920                        ));
1921
1922                        continue;
1923                    }
1924                };
1925
1926                let start_row = display_row_range.start;
1927                let end_row = display_row_range.end;
1928                // If we're in a multibuffer, row range span might include an
1929                // excerpt header, so if we were to draw the marker straight away,
1930                // the hunk might include the rows of that header.
1931                // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
1932                // Instead, we simply check whether the range we're dealing with includes
1933                // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
1934                let end_row_in_current_excerpt = layout
1935                    .position_map
1936                    .snapshot
1937                    .blocks_in_range(start_row..end_row)
1938                    .find_map(|(start_row, block)| {
1939                        if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1940                            Some(start_row)
1941                        } else {
1942                            None
1943                        }
1944                    })
1945                    .unwrap_or(end_row);
1946
1947                let start_y = start_row as f32 * line_height - scroll_top;
1948                let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
1949
1950                let width = 0.275 * line_height;
1951                let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
1952                let highlight_size = size(width * 2., end_y - start_y);
1953                let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
1954                cx.paint_quad(quad(
1955                    highlight_bounds,
1956                    Corners::all(0.05 * line_height),
1957                    color,
1958                    Edges::default(),
1959                    transparent_black(),
1960                ));
1961            }
1962        })
1963    }
1964
1965    fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
1966        cx.with_content_mask(
1967            Some(ContentMask {
1968                bounds: layout.text_hitbox.bounds,
1969            }),
1970            |cx| {
1971                let cursor_style = if self
1972                    .editor
1973                    .read(cx)
1974                    .hovered_link_state
1975                    .as_ref()
1976                    .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
1977                {
1978                    CursorStyle::PointingHand
1979                } else {
1980                    CursorStyle::IBeam
1981                };
1982                cx.set_cursor_style(cursor_style, &layout.text_hitbox);
1983
1984                cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
1985                let invisible_display_ranges = self.paint_highlights(layout, cx);
1986                self.paint_lines(&invisible_display_ranges, layout, cx);
1987                self.paint_redactions(layout, cx);
1988                self.paint_cursors(layout, cx);
1989            },
1990        )
1991    }
1992
1993    fn paint_highlights(
1994        &mut self,
1995        layout: &mut EditorLayout,
1996        cx: &mut ElementContext,
1997    ) -> SmallVec<[Range<DisplayPoint>; 32]> {
1998        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
1999            let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2000            let line_end_overshoot = 0.15 * layout.position_map.line_height;
2001            for (range, color) in &layout.highlighted_ranges {
2002                self.paint_highlighted_range(
2003                    range.clone(),
2004                    *color,
2005                    Pixels::ZERO,
2006                    line_end_overshoot,
2007                    layout,
2008                    cx,
2009                );
2010            }
2011
2012            let corner_radius = 0.15 * layout.position_map.line_height;
2013
2014            for (player_color, selections) in &layout.selections {
2015                for selection in selections.into_iter() {
2016                    self.paint_highlighted_range(
2017                        selection.range.clone(),
2018                        player_color.selection,
2019                        corner_radius,
2020                        corner_radius * 2.,
2021                        layout,
2022                        cx,
2023                    );
2024
2025                    if selection.is_local && !selection.range.is_empty() {
2026                        invisible_display_ranges.push(selection.range.clone());
2027                    }
2028                }
2029            }
2030            invisible_display_ranges
2031        })
2032    }
2033
2034    fn paint_lines(
2035        &mut self,
2036        invisible_display_ranges: &[Range<DisplayPoint>],
2037        layout: &EditorLayout,
2038        cx: &mut ElementContext,
2039    ) {
2040        let whitespace_setting = self
2041            .editor
2042            .read(cx)
2043            .buffer
2044            .read(cx)
2045            .settings_at(0, cx)
2046            .show_whitespaces;
2047
2048        for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2049            let row = layout.visible_display_row_range.start + ix as u32;
2050            line_with_invisibles.draw(
2051                layout,
2052                row,
2053                layout.content_origin,
2054                whitespace_setting,
2055                invisible_display_ranges,
2056                cx,
2057            )
2058        }
2059    }
2060
2061    fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2062        if layout.redacted_ranges.is_empty() {
2063            return;
2064        }
2065
2066        let line_end_overshoot = layout.line_end_overshoot();
2067
2068        // A softer than perfect black
2069        let redaction_color = gpui::rgb(0x0e1111);
2070
2071        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2072            for range in layout.redacted_ranges.iter() {
2073                self.paint_highlighted_range(
2074                    range.clone(),
2075                    redaction_color.into(),
2076                    Pixels::ZERO,
2077                    line_end_overshoot,
2078                    layout,
2079                    cx,
2080                );
2081            }
2082        });
2083    }
2084
2085    fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2086        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2087            for cursor in &mut layout.cursors {
2088                cursor.paint(layout.content_origin, cx);
2089            }
2090        });
2091    }
2092
2093    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2094        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2095            return;
2096        };
2097
2098        let thumb_bounds = scrollbar_layout.thumb_bounds();
2099        if scrollbar_layout.visible {
2100            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2101                cx.paint_quad(quad(
2102                    scrollbar_layout.hitbox.bounds,
2103                    Corners::default(),
2104                    cx.theme().colors().scrollbar_track_background,
2105                    Edges {
2106                        top: Pixels::ZERO,
2107                        right: Pixels::ZERO,
2108                        bottom: Pixels::ZERO,
2109                        left: px(1.),
2110                    },
2111                    cx.theme().colors().scrollbar_track_border,
2112                ));
2113                let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2114                let is_singleton = self.editor.read(cx).is_singleton(cx);
2115                if is_singleton && scrollbar_settings.selections {
2116                    let start_anchor = Anchor::min();
2117                    let end_anchor = Anchor::max();
2118                    let background_ranges = self
2119                        .editor
2120                        .read(cx)
2121                        .background_highlight_row_ranges::<BufferSearchHighlights>(
2122                            start_anchor..end_anchor,
2123                            &layout.position_map.snapshot,
2124                            50000,
2125                        );
2126                    for range in background_ranges {
2127                        let start_y = scrollbar_layout.y_for_row(range.start().row() as f32);
2128                        let mut end_y = scrollbar_layout.y_for_row(range.end().row() as f32);
2129                        if end_y - start_y < px(1.) {
2130                            end_y = start_y + px(1.);
2131                        }
2132                        let bounds = Bounds::from_corners(
2133                            point(scrollbar_layout.hitbox.left(), start_y),
2134                            point(scrollbar_layout.hitbox.right(), end_y),
2135                        );
2136                        cx.paint_quad(quad(
2137                            bounds,
2138                            Corners::default(),
2139                            cx.theme().status().info,
2140                            Edges {
2141                                top: Pixels::ZERO,
2142                                right: px(1.),
2143                                bottom: Pixels::ZERO,
2144                                left: px(1.),
2145                            },
2146                            cx.theme().colors().scrollbar_thumb_border,
2147                        ));
2148                    }
2149                }
2150
2151                if is_singleton && scrollbar_settings.symbols_selections {
2152                    let selection_ranges = self.editor.read(cx).background_highlights_in_range(
2153                        Anchor::min()..Anchor::max(),
2154                        &layout.position_map.snapshot,
2155                        cx.theme().colors(),
2156                    );
2157                    for hunk in selection_ranges {
2158                        let start_display = Point::new(hunk.0.start.row(), 0)
2159                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2160                        let end_display = Point::new(hunk.0.end.row(), 0)
2161                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2162                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2163                        let mut end_y = if hunk.0.start == hunk.0.end {
2164                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2165                        } else {
2166                            scrollbar_layout.y_for_row(end_display.row() as f32)
2167                        };
2168
2169                        if end_y - start_y < px(1.) {
2170                            end_y = start_y + px(1.);
2171                        }
2172                        let bounds = Bounds::from_corners(
2173                            point(scrollbar_layout.hitbox.left(), start_y),
2174                            point(scrollbar_layout.hitbox.right(), end_y),
2175                        );
2176
2177                        cx.paint_quad(quad(
2178                            bounds,
2179                            Corners::default(),
2180                            cx.theme().status().info,
2181                            Edges {
2182                                top: Pixels::ZERO,
2183                                right: px(1.),
2184                                bottom: Pixels::ZERO,
2185                                left: px(1.),
2186                            },
2187                            cx.theme().colors().scrollbar_thumb_border,
2188                        ));
2189                    }
2190                }
2191
2192                if is_singleton && scrollbar_settings.git_diff {
2193                    for hunk in layout
2194                        .position_map
2195                        .snapshot
2196                        .buffer_snapshot
2197                        .git_diff_hunks_in_range(0..layout.max_row)
2198                    {
2199                        let start_display = Point::new(hunk.associated_range.start, 0)
2200                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2201                        let end_display = Point::new(hunk.associated_range.end, 0)
2202                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2203                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2204                        let mut end_y = if hunk.associated_range.start == hunk.associated_range.end
2205                        {
2206                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2207                        } else {
2208                            scrollbar_layout.y_for_row(end_display.row() as f32)
2209                        };
2210
2211                        if end_y - start_y < px(1.) {
2212                            end_y = start_y + px(1.);
2213                        }
2214                        let bounds = Bounds::from_corners(
2215                            point(scrollbar_layout.hitbox.left(), start_y),
2216                            point(scrollbar_layout.hitbox.right(), end_y),
2217                        );
2218
2219                        let color = match hunk.status() {
2220                            DiffHunkStatus::Added => cx.theme().status().created,
2221                            DiffHunkStatus::Modified => cx.theme().status().modified,
2222                            DiffHunkStatus::Removed => cx.theme().status().deleted,
2223                        };
2224                        cx.paint_quad(quad(
2225                            bounds,
2226                            Corners::default(),
2227                            color,
2228                            Edges {
2229                                top: Pixels::ZERO,
2230                                right: px(1.),
2231                                bottom: Pixels::ZERO,
2232                                left: px(1.),
2233                            },
2234                            cx.theme().colors().scrollbar_thumb_border,
2235                        ));
2236                    }
2237                }
2238
2239                if is_singleton && scrollbar_settings.diagnostics {
2240                    let max_point = layout
2241                        .position_map
2242                        .snapshot
2243                        .display_snapshot
2244                        .buffer_snapshot
2245                        .max_point();
2246
2247                    let diagnostics = layout
2248                        .position_map
2249                        .snapshot
2250                        .buffer_snapshot
2251                        .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
2252                        // We want to sort by severity, in order to paint the most severe diagnostics last.
2253                        .sorted_by_key(|diagnostic| {
2254                            std::cmp::Reverse(diagnostic.diagnostic.severity)
2255                        });
2256
2257                    for diagnostic in diagnostics {
2258                        let start_display = diagnostic
2259                            .range
2260                            .start
2261                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2262                        let end_display = diagnostic
2263                            .range
2264                            .end
2265                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2266                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2267                        let mut end_y = if diagnostic.range.start == diagnostic.range.end {
2268                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2269                        } else {
2270                            scrollbar_layout.y_for_row(end_display.row() as f32)
2271                        };
2272
2273                        if end_y - start_y < px(1.) {
2274                            end_y = start_y + px(1.);
2275                        }
2276                        let bounds = Bounds::from_corners(
2277                            point(scrollbar_layout.hitbox.left(), start_y),
2278                            point(scrollbar_layout.hitbox.right(), end_y),
2279                        );
2280
2281                        let color = match diagnostic.diagnostic.severity {
2282                            DiagnosticSeverity::ERROR => cx.theme().status().error,
2283                            DiagnosticSeverity::WARNING => cx.theme().status().warning,
2284                            DiagnosticSeverity::INFORMATION => cx.theme().status().info,
2285                            _ => cx.theme().status().hint,
2286                        };
2287                        cx.paint_quad(quad(
2288                            bounds,
2289                            Corners::default(),
2290                            color,
2291                            Edges {
2292                                top: Pixels::ZERO,
2293                                right: px(1.),
2294                                bottom: Pixels::ZERO,
2295                                left: px(1.),
2296                            },
2297                            cx.theme().colors().scrollbar_thumb_border,
2298                        ));
2299                    }
2300                }
2301
2302                cx.paint_quad(quad(
2303                    thumb_bounds,
2304                    Corners::default(),
2305                    cx.theme().colors().scrollbar_thumb_background,
2306                    Edges {
2307                        top: Pixels::ZERO,
2308                        right: px(1.),
2309                        bottom: Pixels::ZERO,
2310                        left: px(1.),
2311                    },
2312                    cx.theme().colors().scrollbar_thumb_border,
2313                ));
2314            });
2315        }
2316
2317        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2318
2319        let scroll_height = scrollbar_layout.scroll_height;
2320        let height = scrollbar_layout.height;
2321        let row_range = scrollbar_layout.visible_row_range.clone();
2322
2323        cx.on_mouse_event({
2324            let editor = self.editor.clone();
2325            let hitbox = scrollbar_layout.hitbox.clone();
2326            let mut mouse_position = cx.mouse_position();
2327            move |event: &MouseMoveEvent, phase, cx| {
2328                if phase == DispatchPhase::Capture {
2329                    return;
2330                }
2331
2332                editor.update(cx, |editor, cx| {
2333                    if event.pressed_button == Some(MouseButton::Left)
2334                        && editor.scroll_manager.is_dragging_scrollbar()
2335                    {
2336                        let y = mouse_position.y;
2337                        let new_y = event.position.y;
2338                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2339                            let mut position = editor.scroll_position(cx);
2340                            position.y += (new_y - y) * scroll_height / height;
2341                            if position.y < 0.0 {
2342                                position.y = 0.0;
2343                            }
2344                            editor.set_scroll_position(position, cx);
2345                        }
2346
2347                        mouse_position = event.position;
2348                        cx.stop_propagation();
2349                    } else {
2350                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2351                        if hitbox.is_hovered(cx) {
2352                            editor.scroll_manager.show_scrollbar(cx);
2353                        }
2354                    }
2355                })
2356            }
2357        });
2358
2359        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2360            cx.on_mouse_event({
2361                let editor = self.editor.clone();
2362                move |_: &MouseUpEvent, phase, cx| {
2363                    if phase == DispatchPhase::Capture {
2364                        return;
2365                    }
2366
2367                    editor.update(cx, |editor, cx| {
2368                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2369                        cx.stop_propagation();
2370                    });
2371                }
2372            });
2373        } else {
2374            cx.on_mouse_event({
2375                let editor = self.editor.clone();
2376                let hitbox = scrollbar_layout.hitbox.clone();
2377                move |event: &MouseDownEvent, phase, cx| {
2378                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2379                        return;
2380                    }
2381
2382                    editor.update(cx, |editor, cx| {
2383                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2384
2385                        let y = event.position.y;
2386                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2387                            let center_row =
2388                                ((y - hitbox.top()) * scroll_height / height).round() as u32;
2389                            let top_row = center_row
2390                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2391                            let mut position = editor.scroll_position(cx);
2392                            position.y = top_row as f32;
2393                            editor.set_scroll_position(position, cx);
2394                        } else {
2395                            editor.scroll_manager.show_scrollbar(cx);
2396                        }
2397
2398                        cx.stop_propagation();
2399                    });
2400                }
2401            });
2402        }
2403    }
2404
2405    #[allow(clippy::too_many_arguments)]
2406    fn paint_highlighted_range(
2407        &self,
2408        range: Range<DisplayPoint>,
2409        color: Hsla,
2410        corner_radius: Pixels,
2411        line_end_overshoot: Pixels,
2412        layout: &EditorLayout,
2413        cx: &mut ElementContext,
2414    ) {
2415        let start_row = layout.visible_display_row_range.start;
2416        let end_row = layout.visible_display_row_range.end;
2417        if range.start != range.end {
2418            let row_range = if range.end.column() == 0 {
2419                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2420            } else {
2421                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2422            };
2423
2424            let highlighted_range = HighlightedRange {
2425                color,
2426                line_height: layout.position_map.line_height,
2427                corner_radius,
2428                start_y: layout.content_origin.y
2429                    + row_range.start as f32 * layout.position_map.line_height
2430                    - layout.position_map.scroll_pixel_position.y,
2431                lines: row_range
2432                    .into_iter()
2433                    .map(|row| {
2434                        let line_layout =
2435                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2436                        HighlightedRangeLine {
2437                            start_x: if row == range.start.row() {
2438                                layout.content_origin.x
2439                                    + line_layout.x_for_index(range.start.column() as usize)
2440                                    - layout.position_map.scroll_pixel_position.x
2441                            } else {
2442                                layout.content_origin.x
2443                                    - layout.position_map.scroll_pixel_position.x
2444                            },
2445                            end_x: if row == range.end.row() {
2446                                layout.content_origin.x
2447                                    + line_layout.x_for_index(range.end.column() as usize)
2448                                    - layout.position_map.scroll_pixel_position.x
2449                            } else {
2450                                layout.content_origin.x + line_layout.width + line_end_overshoot
2451                                    - layout.position_map.scroll_pixel_position.x
2452                            },
2453                        }
2454                    })
2455                    .collect(),
2456            };
2457
2458            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2459        }
2460    }
2461
2462    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2463        if layout.folds.is_empty() {
2464            return;
2465        }
2466
2467        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2468            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2469            for mut fold in mem::take(&mut layout.folds) {
2470                fold.hover_element.paint(cx);
2471
2472                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2473                let fold_background = if hover_element.interactivity().active.unwrap() {
2474                    cx.theme().colors().ghost_element_active
2475                } else if hover_element.interactivity().hovered.unwrap() {
2476                    cx.theme().colors().ghost_element_hover
2477                } else {
2478                    cx.theme().colors().ghost_element_background
2479                };
2480
2481                self.paint_highlighted_range(
2482                    fold.display_range.clone(),
2483                    fold_background,
2484                    fold_corner_radius,
2485                    fold_corner_radius * 2.,
2486                    layout,
2487                    cx,
2488                );
2489            }
2490        })
2491    }
2492
2493    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2494        for mut block in layout.blocks.drain(..) {
2495            block.element.paint(cx);
2496        }
2497    }
2498
2499    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2500        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2501            mouse_context_menu.paint(cx);
2502        }
2503    }
2504
2505    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2506        cx.on_mouse_event({
2507            let position_map = layout.position_map.clone();
2508            let editor = self.editor.clone();
2509            let hitbox = layout.hitbox.clone();
2510            let mut delta = ScrollDelta::default();
2511
2512            move |event: &ScrollWheelEvent, phase, cx| {
2513                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2514                    delta = delta.coalesce(event.delta);
2515                    editor.update(cx, |editor, cx| {
2516                        let position_map: &PositionMap = &position_map;
2517
2518                        let line_height = position_map.line_height;
2519                        let max_glyph_width = position_map.em_width;
2520                        let (delta, axis) = match delta {
2521                            gpui::ScrollDelta::Pixels(mut pixels) => {
2522                                //Trackpad
2523                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2524                                (pixels, axis)
2525                            }
2526
2527                            gpui::ScrollDelta::Lines(lines) => {
2528                                //Not trackpad
2529                                let pixels =
2530                                    point(lines.x * max_glyph_width, lines.y * line_height);
2531                                (pixels, None)
2532                            }
2533                        };
2534
2535                        let scroll_position = position_map.snapshot.scroll_position();
2536                        let x = (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width;
2537                        let y = (scroll_position.y * line_height - delta.y) / line_height;
2538                        let scroll_position =
2539                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2540                        editor.scroll(scroll_position, axis, cx);
2541                        cx.stop_propagation();
2542                    });
2543                }
2544            }
2545        });
2546    }
2547
2548    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2549        self.paint_scroll_wheel_listener(layout, cx);
2550
2551        cx.on_mouse_event({
2552            let position_map = layout.position_map.clone();
2553            let editor = self.editor.clone();
2554            let text_hitbox = layout.text_hitbox.clone();
2555            let gutter_hitbox = layout.gutter_hitbox.clone();
2556
2557            move |event: &MouseDownEvent, phase, cx| {
2558                if phase == DispatchPhase::Bubble {
2559                    match event.button {
2560                        MouseButton::Left => editor.update(cx, |editor, cx| {
2561                            Self::mouse_left_down(
2562                                editor,
2563                                event,
2564                                &position_map,
2565                                &text_hitbox,
2566                                &gutter_hitbox,
2567                                cx,
2568                            );
2569                        }),
2570                        MouseButton::Right => editor.update(cx, |editor, cx| {
2571                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2572                        }),
2573                        _ => {}
2574                    };
2575                }
2576            }
2577        });
2578
2579        cx.on_mouse_event({
2580            let editor = self.editor.clone();
2581            let position_map = layout.position_map.clone();
2582            let text_hitbox = layout.text_hitbox.clone();
2583
2584            move |event: &MouseUpEvent, phase, cx| {
2585                if phase == DispatchPhase::Bubble {
2586                    editor.update(cx, |editor, cx| {
2587                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2588                    });
2589                }
2590            }
2591        });
2592        cx.on_mouse_event({
2593            let position_map = layout.position_map.clone();
2594            let editor = self.editor.clone();
2595            let text_hitbox = layout.text_hitbox.clone();
2596            let gutter_hitbox = layout.gutter_hitbox.clone();
2597
2598            move |event: &MouseMoveEvent, phase, cx| {
2599                if phase == DispatchPhase::Bubble {
2600                    editor.update(cx, |editor, cx| {
2601                        if event.pressed_button == Some(MouseButton::Left) {
2602                            Self::mouse_dragged(
2603                                editor,
2604                                event,
2605                                &position_map,
2606                                text_hitbox.bounds,
2607                                cx,
2608                            )
2609                        }
2610
2611                        Self::mouse_moved(
2612                            editor,
2613                            event,
2614                            &position_map,
2615                            &text_hitbox,
2616                            &gutter_hitbox,
2617                            cx,
2618                        )
2619                    });
2620                }
2621            }
2622        });
2623    }
2624
2625    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2626        bounds.upper_right().x - self.style.scrollbar_width
2627    }
2628
2629    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2630        let style = &self.style;
2631        let font_size = style.text.font_size.to_pixels(cx.rem_size());
2632        let layout = cx
2633            .text_system()
2634            .shape_line(
2635                SharedString::from(" ".repeat(column)),
2636                font_size,
2637                &[TextRun {
2638                    len: column,
2639                    font: style.text.font(),
2640                    color: Hsla::default(),
2641                    background_color: None,
2642                    underline: None,
2643                    strikethrough: None,
2644                }],
2645            )
2646            .unwrap();
2647
2648        layout.width
2649    }
2650
2651    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2652        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2653        self.column_pixels(digit_count, cx)
2654    }
2655}
2656
2657#[derive(Debug)]
2658pub(crate) struct LineWithInvisibles {
2659    pub line: ShapedLine,
2660    invisibles: Vec<Invisible>,
2661}
2662
2663impl LineWithInvisibles {
2664    fn from_chunks<'a>(
2665        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2666        text_style: &TextStyle,
2667        max_line_len: usize,
2668        max_line_count: usize,
2669        line_number_layouts: &[Option<ShapedLine>],
2670        editor_mode: EditorMode,
2671        cx: &WindowContext,
2672    ) -> Vec<Self> {
2673        let mut layouts = Vec::with_capacity(max_line_count);
2674        let mut line = String::new();
2675        let mut invisibles = Vec::new();
2676        let mut styles = Vec::new();
2677        let mut non_whitespace_added = false;
2678        let mut row = 0;
2679        let mut line_exceeded_max_len = false;
2680        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2681
2682        for highlighted_chunk in chunks.chain([HighlightedChunk {
2683            chunk: "\n",
2684            style: None,
2685            is_tab: false,
2686        }]) {
2687            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2688                if ix > 0 {
2689                    let shaped_line = cx
2690                        .text_system()
2691                        .shape_line(line.clone().into(), font_size, &styles)
2692                        .unwrap();
2693                    layouts.push(Self {
2694                        line: shaped_line,
2695                        invisibles: std::mem::take(&mut invisibles),
2696                    });
2697
2698                    line.clear();
2699                    styles.clear();
2700                    row += 1;
2701                    line_exceeded_max_len = false;
2702                    non_whitespace_added = false;
2703                    if row == max_line_count {
2704                        return layouts;
2705                    }
2706                }
2707
2708                if !line_chunk.is_empty() && !line_exceeded_max_len {
2709                    let text_style = if let Some(style) = highlighted_chunk.style {
2710                        Cow::Owned(text_style.clone().highlight(style))
2711                    } else {
2712                        Cow::Borrowed(text_style)
2713                    };
2714
2715                    if line.len() + line_chunk.len() > max_line_len {
2716                        let mut chunk_len = max_line_len - line.len();
2717                        while !line_chunk.is_char_boundary(chunk_len) {
2718                            chunk_len -= 1;
2719                        }
2720                        line_chunk = &line_chunk[..chunk_len];
2721                        line_exceeded_max_len = true;
2722                    }
2723
2724                    styles.push(TextRun {
2725                        len: line_chunk.len(),
2726                        font: text_style.font(),
2727                        color: text_style.color,
2728                        background_color: text_style.background_color,
2729                        underline: text_style.underline,
2730                        strikethrough: text_style.strikethrough,
2731                    });
2732
2733                    if editor_mode == EditorMode::Full {
2734                        // Line wrap pads its contents with fake whitespaces,
2735                        // avoid printing them
2736                        let inside_wrapped_string = line_number_layouts
2737                            .get(row)
2738                            .and_then(|layout| layout.as_ref())
2739                            .is_none();
2740                        if highlighted_chunk.is_tab {
2741                            if non_whitespace_added || !inside_wrapped_string {
2742                                invisibles.push(Invisible::Tab {
2743                                    line_start_offset: line.len(),
2744                                });
2745                            }
2746                        } else {
2747                            invisibles.extend(
2748                                line_chunk
2749                                    .chars()
2750                                    .enumerate()
2751                                    .filter(|(_, line_char)| {
2752                                        let is_whitespace = line_char.is_whitespace();
2753                                        non_whitespace_added |= !is_whitespace;
2754                                        is_whitespace
2755                                            && (non_whitespace_added || !inside_wrapped_string)
2756                                    })
2757                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2758                                        line_offset: line.len() + whitespace_index,
2759                                    }),
2760                            )
2761                        }
2762                    }
2763
2764                    line.push_str(line_chunk);
2765                }
2766            }
2767        }
2768
2769        layouts
2770    }
2771
2772    fn draw(
2773        &self,
2774        layout: &EditorLayout,
2775        row: u32,
2776        content_origin: gpui::Point<Pixels>,
2777        whitespace_setting: ShowWhitespaceSetting,
2778        selection_ranges: &[Range<DisplayPoint>],
2779        cx: &mut ElementContext,
2780    ) {
2781        let line_height = layout.position_map.line_height;
2782        let line_y = line_height * row as f32 - layout.position_map.scroll_pixel_position.y;
2783
2784        self.line
2785            .paint(
2786                content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y),
2787                line_height,
2788                cx,
2789            )
2790            .log_err();
2791
2792        self.draw_invisibles(
2793            &selection_ranges,
2794            layout,
2795            content_origin,
2796            line_y,
2797            row,
2798            line_height,
2799            whitespace_setting,
2800            cx,
2801        );
2802    }
2803
2804    #[allow(clippy::too_many_arguments)]
2805    fn draw_invisibles(
2806        &self,
2807        selection_ranges: &[Range<DisplayPoint>],
2808        layout: &EditorLayout,
2809        content_origin: gpui::Point<Pixels>,
2810        line_y: Pixels,
2811        row: u32,
2812        line_height: Pixels,
2813        whitespace_setting: ShowWhitespaceSetting,
2814        cx: &mut ElementContext,
2815    ) {
2816        let allowed_invisibles_regions = match whitespace_setting {
2817            ShowWhitespaceSetting::None => return,
2818            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2819            ShowWhitespaceSetting::All => None,
2820        };
2821
2822        for invisible in &self.invisibles {
2823            let (&token_offset, invisible_symbol) = match invisible {
2824                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2825                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2826            };
2827
2828            let x_offset = self.line.x_for_index(token_offset);
2829            let invisible_offset =
2830                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2831            let origin = content_origin
2832                + gpui::point(
2833                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
2834                    line_y,
2835                );
2836
2837            if let Some(allowed_regions) = allowed_invisibles_regions {
2838                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2839                if !allowed_regions
2840                    .iter()
2841                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2842                {
2843                    continue;
2844                }
2845            }
2846            invisible_symbol.paint(origin, line_height, cx).log_err();
2847        }
2848    }
2849}
2850
2851#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2852enum Invisible {
2853    Tab { line_start_offset: usize },
2854    Whitespace { line_offset: usize },
2855}
2856
2857impl Element for EditorElement {
2858    type BeforeLayout = ();
2859    type AfterLayout = EditorLayout;
2860
2861    fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
2862        self.editor.update(cx, |editor, cx| {
2863            editor.set_style(self.style.clone(), cx);
2864
2865            let layout_id = match editor.mode {
2866                EditorMode::SingleLine => {
2867                    let rem_size = cx.rem_size();
2868                    let mut style = Style::default();
2869                    style.size.width = relative(1.).into();
2870                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2871                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2872                }
2873                EditorMode::AutoHeight { max_lines } => {
2874                    let editor_handle = cx.view().clone();
2875                    let max_line_number_width =
2876                        self.max_line_number_width(&editor.snapshot(cx), cx);
2877                    cx.with_element_context(|cx| {
2878                        cx.request_measured_layout(
2879                            Style::default(),
2880                            move |known_dimensions, _, cx| {
2881                                editor_handle
2882                                    .update(cx, |editor, cx| {
2883                                        compute_auto_height_layout(
2884                                            editor,
2885                                            max_lines,
2886                                            max_line_number_width,
2887                                            known_dimensions,
2888                                            cx,
2889                                        )
2890                                    })
2891                                    .unwrap_or_default()
2892                            },
2893                        )
2894                    })
2895                }
2896                EditorMode::Full => {
2897                    let mut style = Style::default();
2898                    style.size.width = relative(1.).into();
2899                    style.size.height = relative(1.).into();
2900                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2901                }
2902            };
2903
2904            (layout_id, ())
2905        })
2906    }
2907
2908    fn after_layout(
2909        &mut self,
2910        bounds: Bounds<Pixels>,
2911        _: &mut Self::BeforeLayout,
2912        cx: &mut ElementContext,
2913    ) -> Self::AfterLayout {
2914        let text_style = TextStyleRefinement {
2915            font_size: Some(self.style.text.font_size),
2916            line_height: Some(self.style.text.line_height),
2917            ..Default::default()
2918        };
2919        cx.with_text_style(Some(text_style), |cx| {
2920            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2921                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
2922                let style = self.style.clone();
2923
2924                let font_id = cx.text_system().resolve_font(&style.text.font());
2925                let font_size = style.text.font_size.to_pixels(cx.rem_size());
2926                let line_height = style.text.line_height_in_pixels(cx.rem_size());
2927                let em_width = cx
2928                    .text_system()
2929                    .typographic_bounds(font_id, font_size, 'm')
2930                    .unwrap()
2931                    .size
2932                    .width;
2933                let em_advance = cx
2934                    .text_system()
2935                    .advance(font_id, font_size, 'm')
2936                    .unwrap()
2937                    .width;
2938
2939                let gutter_dimensions = snapshot.gutter_dimensions(
2940                    font_id,
2941                    font_size,
2942                    em_width,
2943                    self.max_line_number_width(&snapshot, cx),
2944                    cx,
2945                );
2946                let text_width = bounds.size.width - gutter_dimensions.width;
2947                let overscroll = size(em_width, px(0.));
2948
2949                snapshot = self.editor.update(cx, |editor, cx| {
2950                    editor.gutter_width = gutter_dimensions.width;
2951                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
2952
2953                    let editor_width =
2954                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
2955                    let wrap_width = match editor.soft_wrap_mode(cx) {
2956                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2957                        SoftWrap::EditorWidth => editor_width,
2958                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2959                    };
2960
2961                    if editor.set_wrap_width(Some(wrap_width), cx) {
2962                        editor.snapshot(cx)
2963                    } else {
2964                        snapshot
2965                    }
2966                });
2967
2968                let wrap_guides = self
2969                    .editor
2970                    .read(cx)
2971                    .wrap_guides(cx)
2972                    .iter()
2973                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2974                    .collect::<SmallVec<[_; 2]>>();
2975
2976                let hitbox = cx.insert_hitbox(bounds, false);
2977                let gutter_hitbox = cx.insert_hitbox(
2978                    Bounds {
2979                        origin: bounds.origin,
2980                        size: size(gutter_dimensions.width, bounds.size.height),
2981                    },
2982                    false,
2983                );
2984                let text_hitbox = cx.insert_hitbox(
2985                    Bounds {
2986                        origin: gutter_hitbox.upper_right(),
2987                        size: size(text_width, bounds.size.height),
2988                    },
2989                    false,
2990                );
2991                // Offset the content_bounds from the text_bounds by the gutter margin (which
2992                // is roughly half a character wide) to make hit testing work more like how we want.
2993                let content_origin =
2994                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
2995
2996                let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
2997                    let autoscroll_horizontally =
2998                        editor.autoscroll_vertically(bounds.size.height, line_height, cx);
2999                    snapshot = editor.snapshot(cx);
3000                    autoscroll_horizontally
3001                });
3002
3003                let mut scroll_position = snapshot.scroll_position();
3004                // The scroll position is a fractional point, the whole number of which represents
3005                // the top of the window in terms of display rows.
3006                let start_row = scroll_position.y as u32;
3007                let height_in_lines = bounds.size.height / line_height;
3008                let max_row = snapshot.max_point().row();
3009
3010                // Add 1 to ensure selections bleed off screen
3011                let end_row =
3012                    1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3013
3014                let start_anchor = if start_row == 0 {
3015                    Anchor::min()
3016                } else {
3017                    snapshot.buffer_snapshot.anchor_before(
3018                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3019                    )
3020                };
3021                let end_anchor = if end_row > max_row {
3022                    Anchor::max()
3023                } else {
3024                    snapshot.buffer_snapshot.anchor_before(
3025                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3026                    )
3027                };
3028
3029                let highlighted_rows = self
3030                    .editor
3031                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3032                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3033                    start_anchor..end_anchor,
3034                    &snapshot.display_snapshot,
3035                    cx.theme().colors(),
3036                );
3037
3038                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3039                    start_anchor..end_anchor,
3040                    &snapshot.display_snapshot,
3041                    cx,
3042                );
3043
3044                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3045                    start_anchor,
3046                    end_anchor,
3047                    &snapshot,
3048                    start_row,
3049                    end_row,
3050                    cx,
3051                );
3052
3053                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3054                    start_row..end_row,
3055                    &active_rows,
3056                    newest_selection_head,
3057                    &snapshot,
3058                    cx,
3059                );
3060
3061                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3062
3063                let mut max_visible_line_width = Pixels::ZERO;
3064                let line_layouts =
3065                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3066                for line_with_invisibles in &line_layouts {
3067                    if line_with_invisibles.line.width > max_visible_line_width {
3068                        max_visible_line_width = line_with_invisibles.line.width;
3069                    }
3070                }
3071
3072                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3073                    .unwrap()
3074                    .width;
3075                let mut scroll_width =
3076                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3077                let mut blocks = self.build_blocks(
3078                    start_row..end_row,
3079                    &snapshot,
3080                    &hitbox,
3081                    &text_hitbox,
3082                    &mut scroll_width,
3083                    &gutter_dimensions,
3084                    em_width,
3085                    gutter_dimensions.width + gutter_dimensions.margin,
3086                    line_height,
3087                    &line_layouts,
3088                    cx,
3089                );
3090
3091                let scroll_max = point(
3092                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3093                    max_row as f32,
3094                );
3095
3096                self.editor.update(cx, |editor, cx| {
3097                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3098
3099                    let autoscrolled = if autoscroll_horizontally {
3100                        editor.autoscroll_horizontally(
3101                            start_row,
3102                            text_hitbox.size.width,
3103                            scroll_width,
3104                            em_width,
3105                            &line_layouts,
3106                            cx,
3107                        )
3108                    } else {
3109                        false
3110                    };
3111
3112                    if clamped || autoscrolled {
3113                        snapshot = editor.snapshot(cx);
3114                        scroll_position = snapshot.scroll_position();
3115                    }
3116                });
3117
3118                let scroll_pixel_position = point(
3119                    scroll_position.x * em_width,
3120                    scroll_position.y * line_height,
3121                );
3122
3123                cx.with_element_id(Some("blocks"), |cx| {
3124                    self.layout_blocks(
3125                        &mut blocks,
3126                        &hitbox,
3127                        line_height,
3128                        scroll_pixel_position,
3129                        cx,
3130                    );
3131                });
3132
3133                let cursors = self.layout_cursors(
3134                    &snapshot,
3135                    &selections,
3136                    start_row..end_row,
3137                    &line_layouts,
3138                    &text_hitbox,
3139                    content_origin,
3140                    scroll_pixel_position,
3141                    line_height,
3142                    em_width,
3143                    cx,
3144                );
3145
3146                let scrollbar_layout = self.layout_scrollbar(
3147                    &snapshot,
3148                    bounds,
3149                    scroll_position,
3150                    line_height,
3151                    height_in_lines,
3152                    cx,
3153                );
3154
3155                let folds = cx.with_element_id(Some("folds"), |cx| {
3156                    self.layout_folds(
3157                        &snapshot,
3158                        content_origin,
3159                        start_anchor..end_anchor,
3160                        start_row..end_row,
3161                        scroll_pixel_position,
3162                        line_height,
3163                        &line_layouts,
3164                        cx,
3165                    )
3166                });
3167
3168                let gutter_settings = EditorSettings::get_global(cx).gutter;
3169
3170                let mut context_menu_visible = false;
3171                let mut code_actions_indicator = None;
3172                if let Some(newest_selection_head) = newest_selection_head {
3173                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3174                        context_menu_visible = self.layout_context_menu(
3175                            line_height,
3176                            &hitbox,
3177                            &text_hitbox,
3178                            content_origin,
3179                            start_row,
3180                            scroll_pixel_position,
3181                            &line_layouts,
3182                            newest_selection_head,
3183                            cx,
3184                        );
3185                        if gutter_settings.code_actions {
3186                            code_actions_indicator = self.layout_code_actions_indicator(
3187                                line_height,
3188                                newest_selection_head,
3189                                scroll_pixel_position,
3190                                &gutter_dimensions,
3191                                &gutter_hitbox,
3192                                cx,
3193                            );
3194                        }
3195                    }
3196                }
3197
3198                if !context_menu_visible && !cx.has_active_drag() {
3199                    self.layout_hover_popovers(
3200                        &snapshot,
3201                        &hitbox,
3202                        &text_hitbox,
3203                        start_row..end_row,
3204                        content_origin,
3205                        scroll_pixel_position,
3206                        &line_layouts,
3207                        line_height,
3208                        em_width,
3209                        cx,
3210                    );
3211                }
3212
3213                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3214
3215                let fold_indicators = if gutter_settings.folds {
3216                    cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3217                        self.layout_gutter_fold_indicators(
3218                            fold_statuses,
3219                            line_height,
3220                            &gutter_dimensions,
3221                            gutter_settings,
3222                            scroll_pixel_position,
3223                            &gutter_hitbox,
3224                            cx,
3225                        )
3226                    })
3227                } else {
3228                    Vec::new()
3229                };
3230
3231                let invisible_symbol_font_size = font_size / 2.;
3232                let tab_invisible = cx
3233                    .text_system()
3234                    .shape_line(
3235                        "".into(),
3236                        invisible_symbol_font_size,
3237                        &[TextRun {
3238                            len: "".len(),
3239                            font: self.style.text.font(),
3240                            color: cx.theme().colors().editor_invisible,
3241                            background_color: None,
3242                            underline: None,
3243                            strikethrough: None,
3244                        }],
3245                    )
3246                    .unwrap();
3247                let space_invisible = cx
3248                    .text_system()
3249                    .shape_line(
3250                        "".into(),
3251                        invisible_symbol_font_size,
3252                        &[TextRun {
3253                            len: "".len(),
3254                            font: self.style.text.font(),
3255                            color: cx.theme().colors().editor_invisible,
3256                            background_color: None,
3257                            underline: None,
3258                            strikethrough: None,
3259                        }],
3260                    )
3261                    .unwrap();
3262
3263                EditorLayout {
3264                    mode: snapshot.mode,
3265                    position_map: Arc::new(PositionMap {
3266                        size: bounds.size,
3267                        scroll_pixel_position,
3268                        scroll_max,
3269                        line_layouts,
3270                        line_height,
3271                        em_width,
3272                        em_advance,
3273                        snapshot,
3274                    }),
3275                    visible_display_row_range: start_row..end_row,
3276                    wrap_guides,
3277                    hitbox,
3278                    text_hitbox,
3279                    gutter_hitbox,
3280                    gutter_dimensions,
3281                    content_origin,
3282                    scrollbar_layout,
3283                    max_row,
3284                    active_rows,
3285                    highlighted_rows,
3286                    highlighted_ranges,
3287                    redacted_ranges,
3288                    line_numbers,
3289                    display_hunks,
3290                    folds,
3291                    blocks,
3292                    cursors,
3293                    selections,
3294                    mouse_context_menu,
3295                    code_actions_indicator,
3296                    fold_indicators,
3297                    tab_invisible,
3298                    space_invisible,
3299                }
3300            })
3301        })
3302    }
3303
3304    fn paint(
3305        &mut self,
3306        bounds: Bounds<gpui::Pixels>,
3307        _: &mut Self::BeforeLayout,
3308        layout: &mut Self::AfterLayout,
3309        cx: &mut ElementContext,
3310    ) {
3311        let focus_handle = self.editor.focus_handle(cx);
3312        let key_context = self.editor.read(cx).key_context(cx);
3313        cx.set_focus_handle(&focus_handle);
3314        cx.set_key_context(key_context);
3315        cx.set_view_id(self.editor.entity_id());
3316        cx.handle_input(
3317            &focus_handle,
3318            ElementInputHandler::new(bounds, self.editor.clone()),
3319        );
3320        self.register_actions(cx);
3321        self.register_key_listeners(cx, layout);
3322
3323        let text_style = TextStyleRefinement {
3324            font_size: Some(self.style.text.font_size),
3325            line_height: Some(self.style.text.line_height),
3326            ..Default::default()
3327        };
3328        cx.with_text_style(Some(text_style), |cx| {
3329            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3330                self.paint_mouse_listeners(layout, cx);
3331
3332                self.paint_background(layout, cx);
3333                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3334                    self.paint_gutter(layout, cx);
3335                }
3336                self.paint_text(layout, cx);
3337
3338                if !layout.blocks.is_empty() {
3339                    cx.with_element_id(Some("blocks"), |cx| {
3340                        self.paint_blocks(layout, cx);
3341                    });
3342                }
3343
3344                self.paint_scrollbar(layout, cx);
3345                self.paint_mouse_context_menu(layout, cx);
3346            });
3347        })
3348    }
3349}
3350
3351impl IntoElement for EditorElement {
3352    type Element = Self;
3353
3354    fn into_element(self) -> Self::Element {
3355        self
3356    }
3357}
3358
3359type BufferRow = u32;
3360
3361pub struct EditorLayout {
3362    position_map: Arc<PositionMap>,
3363    hitbox: Hitbox,
3364    text_hitbox: Hitbox,
3365    gutter_hitbox: Hitbox,
3366    gutter_dimensions: GutterDimensions,
3367    content_origin: gpui::Point<Pixels>,
3368    scrollbar_layout: Option<ScrollbarLayout>,
3369    mode: EditorMode,
3370    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3371    visible_display_row_range: Range<u32>,
3372    active_rows: BTreeMap<u32, bool>,
3373    highlighted_rows: BTreeMap<u32, Hsla>,
3374    line_numbers: Vec<Option<ShapedLine>>,
3375    display_hunks: Vec<DisplayDiffHunk>,
3376    folds: Vec<FoldLayout>,
3377    blocks: Vec<BlockLayout>,
3378    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3379    redacted_ranges: Vec<Range<DisplayPoint>>,
3380    cursors: Vec<CursorLayout>,
3381    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3382    max_row: u32,
3383    code_actions_indicator: Option<AnyElement>,
3384    fold_indicators: Vec<Option<AnyElement>>,
3385    mouse_context_menu: Option<AnyElement>,
3386    tab_invisible: ShapedLine,
3387    space_invisible: ShapedLine,
3388}
3389
3390impl EditorLayout {
3391    fn line_end_overshoot(&self) -> Pixels {
3392        0.15 * self.position_map.line_height
3393    }
3394}
3395
3396struct ScrollbarLayout {
3397    hitbox: Hitbox,
3398    visible_row_range: Range<f32>,
3399    visible: bool,
3400    height: Pixels,
3401    scroll_height: f32,
3402    first_row_y_offset: Pixels,
3403    row_height: Pixels,
3404}
3405
3406impl ScrollbarLayout {
3407    fn thumb_bounds(&self) -> Bounds<Pixels> {
3408        let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
3409        let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
3410        Bounds::from_corners(
3411            point(self.hitbox.left(), thumb_top),
3412            point(self.hitbox.right(), thumb_bottom),
3413        )
3414    }
3415
3416    fn y_for_row(&self, row: f32) -> Pixels {
3417        self.hitbox.top() + self.first_row_y_offset + row * self.row_height
3418    }
3419}
3420
3421struct FoldLayout {
3422    display_range: Range<DisplayPoint>,
3423    hover_element: AnyElement,
3424}
3425
3426struct PositionMap {
3427    size: Size<Pixels>,
3428    line_height: Pixels,
3429    scroll_pixel_position: gpui::Point<Pixels>,
3430    scroll_max: gpui::Point<f32>,
3431    em_width: Pixels,
3432    em_advance: Pixels,
3433    line_layouts: Vec<LineWithInvisibles>,
3434    snapshot: EditorSnapshot,
3435}
3436
3437#[derive(Debug, Copy, Clone)]
3438pub struct PointForPosition {
3439    pub previous_valid: DisplayPoint,
3440    pub next_valid: DisplayPoint,
3441    pub exact_unclipped: DisplayPoint,
3442    pub column_overshoot_after_line_end: u32,
3443}
3444
3445impl PointForPosition {
3446    pub fn as_valid(&self) -> Option<DisplayPoint> {
3447        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3448            Some(self.previous_valid)
3449        } else {
3450            None
3451        }
3452    }
3453}
3454
3455impl PositionMap {
3456    fn point_for_position(
3457        &self,
3458        text_bounds: Bounds<Pixels>,
3459        position: gpui::Point<Pixels>,
3460    ) -> PointForPosition {
3461        let scroll_position = self.snapshot.scroll_position();
3462        let position = position - text_bounds.origin;
3463        let y = position.y.max(px(0.)).min(self.size.height);
3464        let x = position.x + (scroll_position.x * self.em_width);
3465        let row = ((y / self.line_height) + scroll_position.y) as u32;
3466
3467        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3468            .line_layouts
3469            .get(row as usize - scroll_position.y as usize)
3470            .map(|LineWithInvisibles { line, .. }| line)
3471        {
3472            if let Some(ix) = line.index_for_x(x) {
3473                (ix as u32, px(0.))
3474            } else {
3475                (line.len as u32, px(0.).max(x - line.width))
3476            }
3477        } else {
3478            (0, x)
3479        };
3480
3481        let mut exact_unclipped = DisplayPoint::new(row, column);
3482        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3483        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3484
3485        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3486        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3487        PointForPosition {
3488            previous_valid,
3489            next_valid,
3490            exact_unclipped,
3491            column_overshoot_after_line_end,
3492        }
3493    }
3494}
3495
3496struct BlockLayout {
3497    row: u32,
3498    element: AnyElement,
3499    available_space: Size<AvailableSpace>,
3500    style: BlockStyle,
3501}
3502
3503fn layout_line(
3504    row: u32,
3505    snapshot: &EditorSnapshot,
3506    style: &EditorStyle,
3507    cx: &WindowContext,
3508) -> Result<ShapedLine> {
3509    let mut line = snapshot.line(row);
3510
3511    if line.len() > MAX_LINE_LEN {
3512        let mut len = MAX_LINE_LEN;
3513        while !line.is_char_boundary(len) {
3514            len -= 1;
3515        }
3516
3517        line.truncate(len);
3518    }
3519
3520    cx.text_system().shape_line(
3521        line.into(),
3522        style.text.font_size.to_pixels(cx.rem_size()),
3523        &[TextRun {
3524            len: snapshot.line_len(row) as usize,
3525            font: style.text.font(),
3526            color: Hsla::default(),
3527            background_color: None,
3528            underline: None,
3529            strikethrough: None,
3530        }],
3531    )
3532}
3533
3534pub struct CursorLayout {
3535    origin: gpui::Point<Pixels>,
3536    block_width: Pixels,
3537    line_height: Pixels,
3538    color: Hsla,
3539    shape: CursorShape,
3540    block_text: Option<ShapedLine>,
3541    cursor_name: Option<AnyElement>,
3542}
3543
3544#[derive(Debug)]
3545pub struct CursorName {
3546    string: SharedString,
3547    color: Hsla,
3548    is_top_row: bool,
3549}
3550
3551impl CursorLayout {
3552    pub fn new(
3553        origin: gpui::Point<Pixels>,
3554        block_width: Pixels,
3555        line_height: Pixels,
3556        color: Hsla,
3557        shape: CursorShape,
3558        block_text: Option<ShapedLine>,
3559    ) -> CursorLayout {
3560        CursorLayout {
3561            origin,
3562            block_width,
3563            line_height,
3564            color,
3565            shape,
3566            block_text,
3567            cursor_name: None,
3568        }
3569    }
3570
3571    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3572        Bounds {
3573            origin: self.origin + origin,
3574            size: size(self.block_width, self.line_height),
3575        }
3576    }
3577
3578    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3579        match self.shape {
3580            CursorShape::Bar => Bounds {
3581                origin: self.origin + origin,
3582                size: size(px(2.0), self.line_height),
3583            },
3584            CursorShape::Block | CursorShape::Hollow => Bounds {
3585                origin: self.origin + origin,
3586                size: size(self.block_width, self.line_height),
3587            },
3588            CursorShape::Underscore => Bounds {
3589                origin: self.origin
3590                    + origin
3591                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3592                size: size(self.block_width, px(2.0)),
3593            },
3594        }
3595    }
3596
3597    pub fn layout(
3598        &mut self,
3599        origin: gpui::Point<Pixels>,
3600        cursor_name: Option<CursorName>,
3601        cx: &mut ElementContext,
3602    ) {
3603        if let Some(cursor_name) = cursor_name {
3604            let bounds = self.bounds(origin);
3605            let text_size = self.line_height / 1.5;
3606
3607            let name_origin = if cursor_name.is_top_row {
3608                point(bounds.right() - px(1.), bounds.top())
3609            } else {
3610                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
3611            };
3612            let mut name_element = div()
3613                .bg(self.color)
3614                .text_size(text_size)
3615                .px_0p5()
3616                .line_height(text_size + px(2.))
3617                .text_color(cursor_name.color)
3618                .child(cursor_name.string.clone())
3619                .into_any_element();
3620
3621            name_element.layout(
3622                name_origin,
3623                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
3624                cx,
3625            );
3626
3627            self.cursor_name = Some(name_element);
3628        }
3629    }
3630
3631    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
3632        let bounds = self.bounds(origin);
3633
3634        //Draw background or border quad
3635        let cursor = if matches!(self.shape, CursorShape::Hollow) {
3636            outline(bounds, self.color)
3637        } else {
3638            fill(bounds, self.color)
3639        };
3640
3641        if let Some(name) = &mut self.cursor_name {
3642            name.paint(cx);
3643        }
3644
3645        cx.paint_quad(cursor);
3646
3647        if let Some(block_text) = &self.block_text {
3648            block_text
3649                .paint(self.origin + origin, self.line_height, cx)
3650                .log_err();
3651        }
3652    }
3653
3654    pub fn shape(&self) -> CursorShape {
3655        self.shape
3656    }
3657}
3658
3659#[derive(Debug)]
3660pub struct HighlightedRange {
3661    pub start_y: Pixels,
3662    pub line_height: Pixels,
3663    pub lines: Vec<HighlightedRangeLine>,
3664    pub color: Hsla,
3665    pub corner_radius: Pixels,
3666}
3667
3668#[derive(Debug)]
3669pub struct HighlightedRangeLine {
3670    pub start_x: Pixels,
3671    pub end_x: Pixels,
3672}
3673
3674impl HighlightedRange {
3675    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
3676        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3677            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3678            self.paint_lines(
3679                self.start_y + self.line_height,
3680                &self.lines[1..],
3681                bounds,
3682                cx,
3683            );
3684        } else {
3685            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3686        }
3687    }
3688
3689    fn paint_lines(
3690        &self,
3691        start_y: Pixels,
3692        lines: &[HighlightedRangeLine],
3693        _bounds: Bounds<Pixels>,
3694        cx: &mut ElementContext,
3695    ) {
3696        if lines.is_empty() {
3697            return;
3698        }
3699
3700        let first_line = lines.first().unwrap();
3701        let last_line = lines.last().unwrap();
3702
3703        let first_top_left = point(first_line.start_x, start_y);
3704        let first_top_right = point(first_line.end_x, start_y);
3705
3706        let curve_height = point(Pixels::ZERO, self.corner_radius);
3707        let curve_width = |start_x: Pixels, end_x: Pixels| {
3708            let max = (end_x - start_x) / 2.;
3709            let width = if max < self.corner_radius {
3710                max
3711            } else {
3712                self.corner_radius
3713            };
3714
3715            point(width, Pixels::ZERO)
3716        };
3717
3718        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3719        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3720        path.curve_to(first_top_right + curve_height, first_top_right);
3721
3722        let mut iter = lines.iter().enumerate().peekable();
3723        while let Some((ix, line)) = iter.next() {
3724            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3725
3726            if let Some((_, next_line)) = iter.peek() {
3727                let next_top_right = point(next_line.end_x, bottom_right.y);
3728
3729                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3730                    Ordering::Equal => {
3731                        path.line_to(bottom_right);
3732                    }
3733                    Ordering::Less => {
3734                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3735                        path.line_to(bottom_right - curve_height);
3736                        if self.corner_radius > Pixels::ZERO {
3737                            path.curve_to(bottom_right - curve_width, bottom_right);
3738                        }
3739                        path.line_to(next_top_right + curve_width);
3740                        if self.corner_radius > Pixels::ZERO {
3741                            path.curve_to(next_top_right + curve_height, next_top_right);
3742                        }
3743                    }
3744                    Ordering::Greater => {
3745                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3746                        path.line_to(bottom_right - curve_height);
3747                        if self.corner_radius > Pixels::ZERO {
3748                            path.curve_to(bottom_right + curve_width, bottom_right);
3749                        }
3750                        path.line_to(next_top_right - curve_width);
3751                        if self.corner_radius > Pixels::ZERO {
3752                            path.curve_to(next_top_right + curve_height, next_top_right);
3753                        }
3754                    }
3755                }
3756            } else {
3757                let curve_width = curve_width(line.start_x, line.end_x);
3758                path.line_to(bottom_right - curve_height);
3759                if self.corner_radius > Pixels::ZERO {
3760                    path.curve_to(bottom_right - curve_width, bottom_right);
3761                }
3762
3763                let bottom_left = point(line.start_x, bottom_right.y);
3764                path.line_to(bottom_left + curve_width);
3765                if self.corner_radius > Pixels::ZERO {
3766                    path.curve_to(bottom_left - curve_height, bottom_left);
3767                }
3768            }
3769        }
3770
3771        if first_line.start_x > last_line.start_x {
3772            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3773            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3774            path.line_to(second_top_left + curve_height);
3775            if self.corner_radius > Pixels::ZERO {
3776                path.curve_to(second_top_left + curve_width, second_top_left);
3777            }
3778            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3779            path.line_to(first_bottom_left - curve_width);
3780            if self.corner_radius > Pixels::ZERO {
3781                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3782            }
3783        }
3784
3785        path.line_to(first_top_left + curve_height);
3786        if self.corner_radius > Pixels::ZERO {
3787            path.curve_to(first_top_left + top_curve_width, first_top_left);
3788        }
3789        path.line_to(first_top_right - top_curve_width);
3790
3791        cx.paint_path(path, self.color);
3792    }
3793}
3794
3795pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3796    (delta.pow(1.5) / 100.0).into()
3797}
3798
3799fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3800    (delta.pow(1.2) / 300.0).into()
3801}
3802
3803#[cfg(test)]
3804mod tests {
3805    use super::*;
3806    use crate::{
3807        display_map::{BlockDisposition, BlockProperties},
3808        editor_tests::{init_test, update_test_language_settings},
3809        Editor, MultiBuffer,
3810    };
3811    use gpui::TestAppContext;
3812    use language::language_settings;
3813    use log::info;
3814    use std::{num::NonZeroU32, sync::Arc};
3815    use util::test::sample_text;
3816
3817    #[gpui::test]
3818    fn test_shape_line_numbers(cx: &mut TestAppContext) {
3819        init_test(cx, |_| {});
3820        let window = cx.add_window(|cx| {
3821            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3822            Editor::new(EditorMode::Full, buffer, None, cx)
3823        });
3824
3825        let editor = window.root(cx).unwrap();
3826        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3827        let element = EditorElement::new(&editor, style);
3828        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
3829
3830        let layouts = cx
3831            .update_window(*window, |_, cx| {
3832                cx.with_element_context(|cx| {
3833                    element
3834                        .layout_line_numbers(
3835                            0..6,
3836                            &Default::default(),
3837                            Some(DisplayPoint::new(0, 0)),
3838                            &snapshot,
3839                            cx,
3840                        )
3841                        .0
3842                })
3843            })
3844            .unwrap();
3845        assert_eq!(layouts.len(), 6);
3846
3847        let relative_rows = window
3848            .update(cx, |editor, cx| {
3849                let snapshot = editor.snapshot(cx);
3850                element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3851            })
3852            .unwrap();
3853        assert_eq!(relative_rows[&0], 3);
3854        assert_eq!(relative_rows[&1], 2);
3855        assert_eq!(relative_rows[&2], 1);
3856        // current line has no relative number
3857        assert_eq!(relative_rows[&4], 1);
3858        assert_eq!(relative_rows[&5], 2);
3859
3860        // works if cursor is before screen
3861        let relative_rows = window
3862            .update(cx, |editor, cx| {
3863                let snapshot = editor.snapshot(cx);
3864
3865                element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3866            })
3867            .unwrap();
3868        assert_eq!(relative_rows.len(), 3);
3869        assert_eq!(relative_rows[&3], 2);
3870        assert_eq!(relative_rows[&4], 3);
3871        assert_eq!(relative_rows[&5], 4);
3872
3873        // works if cursor is after screen
3874        let relative_rows = window
3875            .update(cx, |editor, cx| {
3876                let snapshot = editor.snapshot(cx);
3877
3878                element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3879            })
3880            .unwrap();
3881        assert_eq!(relative_rows.len(), 3);
3882        assert_eq!(relative_rows[&0], 5);
3883        assert_eq!(relative_rows[&1], 4);
3884        assert_eq!(relative_rows[&2], 3);
3885    }
3886
3887    #[gpui::test]
3888    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3889        init_test(cx, |_| {});
3890
3891        let window = cx.add_window(|cx| {
3892            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3893            Editor::new(EditorMode::Full, buffer, None, cx)
3894        });
3895        let editor = window.root(cx).unwrap();
3896        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3897        let mut element = EditorElement::new(&editor, style);
3898
3899        window
3900            .update(cx, |editor, cx| {
3901                editor.cursor_shape = CursorShape::Block;
3902                editor.change_selections(None, cx, |s| {
3903                    s.select_ranges([
3904                        Point::new(0, 0)..Point::new(1, 0),
3905                        Point::new(3, 2)..Point::new(3, 3),
3906                        Point::new(5, 6)..Point::new(6, 0),
3907                    ]);
3908                });
3909            })
3910            .unwrap();
3911        let state = cx
3912            .update_window(window.into(), |_view, cx| {
3913                cx.with_element_context(|cx| {
3914                    element.after_layout(
3915                        Bounds {
3916                            origin: point(px(500.), px(500.)),
3917                            size: size(px(500.), px(500.)),
3918                        },
3919                        &mut (),
3920                        cx,
3921                    )
3922                })
3923            })
3924            .unwrap();
3925
3926        assert_eq!(state.selections.len(), 1);
3927        let local_selections = &state.selections[0].1;
3928        assert_eq!(local_selections.len(), 3);
3929        // moves cursor back one line
3930        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3931        assert_eq!(
3932            local_selections[0].range,
3933            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3934        );
3935
3936        // moves cursor back one column
3937        assert_eq!(
3938            local_selections[1].range,
3939            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3940        );
3941        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3942
3943        // leaves cursor on the max point
3944        assert_eq!(
3945            local_selections[2].range,
3946            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3947        );
3948        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3949
3950        // active lines does not include 1 (even though the range of the selection does)
3951        assert_eq!(
3952            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3953            vec![0, 3, 5, 6]
3954        );
3955
3956        // multi-buffer support
3957        // in DisplayPoint coordinates, this is what we're dealing with:
3958        //  0: [[file
3959        //  1:   header]]
3960        //  2: aaaaaa
3961        //  3: bbbbbb
3962        //  4: cccccc
3963        //  5:
3964        //  6: ...
3965        //  7: ffffff
3966        //  8: gggggg
3967        //  9: hhhhhh
3968        // 10:
3969        // 11: [[file
3970        // 12:   header]]
3971        // 13: bbbbbb
3972        // 14: cccccc
3973        // 15: dddddd
3974        let window = cx.add_window(|cx| {
3975            let buffer = MultiBuffer::build_multi(
3976                [
3977                    (
3978                        &(sample_text(8, 6, 'a') + "\n"),
3979                        vec![
3980                            Point::new(0, 0)..Point::new(3, 0),
3981                            Point::new(4, 0)..Point::new(7, 0),
3982                        ],
3983                    ),
3984                    (
3985                        &(sample_text(8, 6, 'a') + "\n"),
3986                        vec![Point::new(1, 0)..Point::new(3, 0)],
3987                    ),
3988                ],
3989                cx,
3990            );
3991            Editor::new(EditorMode::Full, buffer, None, cx)
3992        });
3993        let editor = window.root(cx).unwrap();
3994        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3995        let mut element = EditorElement::new(&editor, style);
3996        let _state = window.update(cx, |editor, cx| {
3997            editor.cursor_shape = CursorShape::Block;
3998            editor.change_selections(None, cx, |s| {
3999                s.select_display_ranges([
4000                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4001                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4002                ]);
4003            });
4004        });
4005
4006        let state = cx
4007            .update_window(window.into(), |_view, cx| {
4008                cx.with_element_context(|cx| {
4009                    element.after_layout(
4010                        Bounds {
4011                            origin: point(px(500.), px(500.)),
4012                            size: size(px(500.), px(500.)),
4013                        },
4014                        &mut (),
4015                        cx,
4016                    )
4017                })
4018            })
4019            .unwrap();
4020        assert_eq!(state.selections.len(), 1);
4021        let local_selections = &state.selections[0].1;
4022        assert_eq!(local_selections.len(), 2);
4023
4024        // moves cursor on excerpt boundary back a line
4025        // and doesn't allow selection to bleed through
4026        assert_eq!(
4027            local_selections[0].range,
4028            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4029        );
4030        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4031        // moves cursor on buffer boundary back two lines
4032        // and doesn't allow selection to bleed through
4033        assert_eq!(
4034            local_selections[1].range,
4035            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4036        );
4037        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4038    }
4039
4040    #[gpui::test]
4041    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4042        init_test(cx, |_| {});
4043
4044        let window = cx.add_window(|cx| {
4045            let buffer = MultiBuffer::build_simple("", cx);
4046            Editor::new(EditorMode::Full, buffer, None, cx)
4047        });
4048        let editor = window.root(cx).unwrap();
4049        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4050        window
4051            .update(cx, |editor, cx| {
4052                editor.set_placeholder_text("hello", cx);
4053                editor.insert_blocks(
4054                    [BlockProperties {
4055                        style: BlockStyle::Fixed,
4056                        disposition: BlockDisposition::Above,
4057                        height: 3,
4058                        position: Anchor::min(),
4059                        render: Arc::new(|_| div().into_any()),
4060                    }],
4061                    None,
4062                    cx,
4063                );
4064
4065                // Blur the editor so that it displays placeholder text.
4066                cx.blur();
4067            })
4068            .unwrap();
4069
4070        let mut element = EditorElement::new(&editor, style);
4071        let state = cx
4072            .update_window(window.into(), |_view, cx| {
4073                cx.with_element_context(|cx| {
4074                    element.after_layout(
4075                        Bounds {
4076                            origin: point(px(500.), px(500.)),
4077                            size: size(px(500.), px(500.)),
4078                        },
4079                        &mut (),
4080                        cx,
4081                    )
4082                })
4083            })
4084            .unwrap();
4085
4086        assert_eq!(state.position_map.line_layouts.len(), 4);
4087        assert_eq!(
4088            state
4089                .line_numbers
4090                .iter()
4091                .map(Option::is_some)
4092                .collect::<Vec<_>>(),
4093            &[false, false, false, true]
4094        );
4095    }
4096
4097    #[gpui::test]
4098    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4099        const TAB_SIZE: u32 = 4;
4100
4101        let input_text = "\t \t|\t| a b";
4102        let expected_invisibles = vec![
4103            Invisible::Tab {
4104                line_start_offset: 0,
4105            },
4106            Invisible::Whitespace {
4107                line_offset: TAB_SIZE as usize,
4108            },
4109            Invisible::Tab {
4110                line_start_offset: TAB_SIZE as usize + 1,
4111            },
4112            Invisible::Tab {
4113                line_start_offset: TAB_SIZE as usize * 2 + 1,
4114            },
4115            Invisible::Whitespace {
4116                line_offset: TAB_SIZE as usize * 3 + 1,
4117            },
4118            Invisible::Whitespace {
4119                line_offset: TAB_SIZE as usize * 3 + 3,
4120            },
4121        ];
4122        assert_eq!(
4123            expected_invisibles.len(),
4124            input_text
4125                .chars()
4126                .filter(|initial_char| initial_char.is_whitespace())
4127                .count(),
4128            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4129        );
4130
4131        init_test(cx, |s| {
4132            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4133            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4134        });
4135
4136        let actual_invisibles =
4137            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4138
4139        assert_eq!(expected_invisibles, actual_invisibles);
4140    }
4141
4142    #[gpui::test]
4143    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4144        init_test(cx, |s| {
4145            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4146            s.defaults.tab_size = NonZeroU32::new(4);
4147        });
4148
4149        for editor_mode_without_invisibles in [
4150            EditorMode::SingleLine,
4151            EditorMode::AutoHeight { max_lines: 100 },
4152        ] {
4153            let invisibles = collect_invisibles_from_new_editor(
4154                cx,
4155                editor_mode_without_invisibles,
4156                "\t\t\t| | a b",
4157                px(500.0),
4158            );
4159            assert!(invisibles.is_empty(),
4160                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4161        }
4162    }
4163
4164    #[gpui::test]
4165    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4166        let tab_size = 4;
4167        let input_text = "a\tbcd   ".repeat(9);
4168        let repeated_invisibles = [
4169            Invisible::Tab {
4170                line_start_offset: 1,
4171            },
4172            Invisible::Whitespace {
4173                line_offset: tab_size as usize + 3,
4174            },
4175            Invisible::Whitespace {
4176                line_offset: tab_size as usize + 4,
4177            },
4178            Invisible::Whitespace {
4179                line_offset: tab_size as usize + 5,
4180            },
4181        ];
4182        let expected_invisibles = std::iter::once(repeated_invisibles)
4183            .cycle()
4184            .take(9)
4185            .flatten()
4186            .collect::<Vec<_>>();
4187        assert_eq!(
4188            expected_invisibles.len(),
4189            input_text
4190                .chars()
4191                .filter(|initial_char| initial_char.is_whitespace())
4192                .count(),
4193            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4194        );
4195        info!("Expected invisibles: {expected_invisibles:?}");
4196
4197        init_test(cx, |_| {});
4198
4199        // Put the same string with repeating whitespace pattern into editors of various size,
4200        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4201        let resize_step = 10.0;
4202        let mut editor_width = 200.0;
4203        while editor_width <= 1000.0 {
4204            update_test_language_settings(cx, |s| {
4205                s.defaults.tab_size = NonZeroU32::new(tab_size);
4206                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4207                s.defaults.preferred_line_length = Some(editor_width as u32);
4208                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4209            });
4210
4211            let actual_invisibles = collect_invisibles_from_new_editor(
4212                cx,
4213                EditorMode::Full,
4214                &input_text,
4215                px(editor_width),
4216            );
4217
4218            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4219            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4220            let mut i = 0;
4221            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4222                i = actual_index;
4223                match expected_invisibles.get(i) {
4224                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4225                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4226                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4227                        _ => {
4228                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4229                        }
4230                    },
4231                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4232                }
4233            }
4234            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4235            assert!(
4236                missing_expected_invisibles.is_empty(),
4237                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4238            );
4239
4240            editor_width += resize_step;
4241        }
4242    }
4243
4244    fn collect_invisibles_from_new_editor(
4245        cx: &mut TestAppContext,
4246        editor_mode: EditorMode,
4247        input_text: &str,
4248        editor_width: Pixels,
4249    ) -> Vec<Invisible> {
4250        info!(
4251            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4252            editor_width.0
4253        );
4254        let window = cx.add_window(|cx| {
4255            let buffer = MultiBuffer::build_simple(&input_text, cx);
4256            Editor::new(editor_mode, buffer, None, cx)
4257        });
4258        let editor = window.root(cx).unwrap();
4259        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4260        let mut element = EditorElement::new(&editor, style);
4261        window
4262            .update(cx, |editor, cx| {
4263                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4264                editor.set_wrap_width(Some(editor_width), cx);
4265            })
4266            .unwrap();
4267        let layout_state = cx
4268            .update_window(window.into(), |_, cx| {
4269                cx.with_element_context(|cx| {
4270                    element.after_layout(
4271                        Bounds {
4272                            origin: point(px(500.), px(500.)),
4273                            size: size(px(500.), px(500.)),
4274                        },
4275                        &mut (),
4276                        cx,
4277                    )
4278                })
4279            })
4280            .unwrap();
4281
4282        layout_state
4283            .position_map
4284            .line_layouts
4285            .iter()
4286            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4287            .cloned()
4288            .collect()
4289    }
4290}
4291
4292pub fn register_action<T: Action>(
4293    view: &View<Editor>,
4294    cx: &mut WindowContext,
4295    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4296) {
4297    let view = view.clone();
4298    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4299        let action = action.downcast_ref().unwrap();
4300        if phase == DispatchPhase::Bubble {
4301            view.update(cx, |editor, cx| {
4302                listener(editor, action, cx);
4303            })
4304        }
4305    })
4306}
4307
4308fn compute_auto_height_layout(
4309    editor: &mut Editor,
4310    max_lines: usize,
4311    max_line_number_width: Pixels,
4312    known_dimensions: Size<Option<Pixels>>,
4313    cx: &mut ViewContext<Editor>,
4314) -> Option<Size<Pixels>> {
4315    let width = known_dimensions.width?;
4316    if let Some(height) = known_dimensions.height {
4317        return Some(size(width, height));
4318    }
4319
4320    let style = editor.style.as_ref().unwrap();
4321    let font_id = cx.text_system().resolve_font(&style.text.font());
4322    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4323    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4324    let em_width = cx
4325        .text_system()
4326        .typographic_bounds(font_id, font_size, 'm')
4327        .unwrap()
4328        .size
4329        .width;
4330
4331    let mut snapshot = editor.snapshot(cx);
4332    let gutter_dimensions =
4333        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4334
4335    editor.gutter_width = gutter_dimensions.width;
4336    let text_width = width - gutter_dimensions.width;
4337    let overscroll = size(em_width, px(0.));
4338
4339    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4340    if editor.set_wrap_width(Some(editor_width), cx) {
4341        snapshot = editor.snapshot(cx);
4342    }
4343
4344    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4345    let height = scroll_height
4346        .max(line_height)
4347        .min(line_height * max_lines as f32);
4348
4349    Some(size(width, height))
4350}