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 - scroll_pixel_position.y / line_height)
 860                        * line_height;
 861                    if selection.is_newest {
 862                        editor.pixel_position_of_newest_cursor = Some(point(
 863                            text_hitbox.origin.x + x + block_width / 2.,
 864                            text_hitbox.origin.y + y + line_height / 2.,
 865                        ))
 866                    }
 867
 868                    let mut cursor = CursorLayout {
 869                        color: player_color.cursor,
 870                        block_width,
 871                        origin: point(x, y),
 872                        line_height,
 873                        shape: selection.cursor_shape,
 874                        block_text,
 875                        cursor_name: None,
 876                    };
 877                    let cursor_name = selection.user_name.clone().map(|name| CursorName {
 878                        string: name,
 879                        color: self.style.background,
 880                        is_top_row: cursor_position.row() == 0,
 881                    });
 882                    cx.with_element_context(|cx| cursor.layout(content_origin, cursor_name, cx));
 883                    cursors.push(cursor);
 884                }
 885            }
 886            cursors
 887        })
 888    }
 889
 890    fn layout_scrollbar(
 891        &self,
 892        snapshot: &EditorSnapshot,
 893        bounds: Bounds<Pixels>,
 894        scroll_position: gpui::Point<f32>,
 895        line_height: Pixels,
 896        height_in_lines: f32,
 897        cx: &mut ElementContext,
 898    ) -> Option<ScrollbarLayout> {
 899        let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
 900        let show_scrollbars = match scrollbar_settings.show {
 901            ShowScrollbar::Auto => {
 902                let editor = self.editor.read(cx);
 903                let is_singleton = editor.is_singleton(cx);
 904                // Git
 905                (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
 906                    ||
 907                    // Selections
 908                    (is_singleton && scrollbar_settings.selections && editor.has_background_highlights::<BufferSearchHighlights>())
 909                    ||
 910                    // Symbols Selections
 911                    (is_singleton && scrollbar_settings.symbols_selections && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
 912                    ||
 913                    // Diagnostics
 914                    (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
 915                    ||
 916                    // Scrollmanager
 917                    editor.scroll_manager.scrollbars_visible()
 918            }
 919            ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
 920            ShowScrollbar::Always => true,
 921            ShowScrollbar::Never => false,
 922        };
 923        if snapshot.mode != EditorMode::Full {
 924            return None;
 925        }
 926
 927        let visible_row_range = scroll_position.y..scroll_position.y + height_in_lines;
 928
 929        // If a drag took place after we started dragging the scrollbar,
 930        // cancel the scrollbar drag.
 931        if cx.has_active_drag() {
 932            self.editor.update(cx, |editor, cx| {
 933                editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
 934            });
 935        }
 936
 937        let track_bounds = Bounds::from_corners(
 938            point(self.scrollbar_left(&bounds), bounds.origin.y),
 939            point(bounds.lower_right().x, bounds.lower_left().y),
 940        );
 941
 942        let scroll_height = snapshot.max_point().row() as f32 + height_in_lines;
 943        let mut height = bounds.size.height;
 944        let mut first_row_y_offset = px(0.0);
 945
 946        // Impose a minimum height on the scrollbar thumb
 947        let row_height = height / scroll_height;
 948        let min_thumb_height = line_height;
 949        let thumb_height = height_in_lines * row_height;
 950        if thumb_height < min_thumb_height {
 951            first_row_y_offset = (min_thumb_height - thumb_height) / 2.0;
 952            height -= min_thumb_height - thumb_height;
 953        }
 954
 955        Some(ScrollbarLayout {
 956            hitbox: cx.insert_hitbox(track_bounds, false),
 957            visible_row_range,
 958            height,
 959            scroll_height,
 960            first_row_y_offset,
 961            row_height,
 962            visible: show_scrollbars,
 963        })
 964    }
 965
 966    #[allow(clippy::too_many_arguments)]
 967    fn layout_gutter_fold_indicators(
 968        &self,
 969        fold_statuses: Vec<Option<(FoldStatus, u32, bool)>>,
 970        line_height: Pixels,
 971        gutter_dimensions: &GutterDimensions,
 972        gutter_settings: crate::editor_settings::Gutter,
 973        scroll_pixel_position: gpui::Point<Pixels>,
 974        gutter_hitbox: &Hitbox,
 975        cx: &mut ElementContext,
 976    ) -> Vec<Option<AnyElement>> {
 977        let mut indicators = self.editor.update(cx, |editor, cx| {
 978            editor.render_fold_indicators(
 979                fold_statuses,
 980                &self.style,
 981                editor.gutter_hovered,
 982                line_height,
 983                gutter_dimensions.margin,
 984                cx,
 985            )
 986        });
 987
 988        for (ix, fold_indicator) in indicators.iter_mut().enumerate() {
 989            if let Some(fold_indicator) = fold_indicator {
 990                debug_assert!(gutter_settings.folds);
 991                let available_space = size(
 992                    AvailableSpace::MinContent,
 993                    AvailableSpace::Definite(line_height * 0.55),
 994                );
 995                let fold_indicator_size = fold_indicator.measure(available_space, cx);
 996
 997                let position = point(
 998                    gutter_dimensions.width - gutter_dimensions.right_padding,
 999                    ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1000                );
1001                let centering_offset = point(
1002                    (gutter_dimensions.right_padding + gutter_dimensions.margin
1003                        - fold_indicator_size.width)
1004                        / 2.,
1005                    (line_height - fold_indicator_size.height) / 2.,
1006                );
1007                let origin = gutter_hitbox.origin + position + centering_offset;
1008                fold_indicator.layout(origin, available_space, cx);
1009            }
1010        }
1011
1012        indicators
1013    }
1014
1015    //Folds contained in a hunk are ignored apart from shrinking visual size
1016    //If a fold contains any hunks then that fold line is marked as modified
1017    fn layout_git_gutters(
1018        &self,
1019        display_rows: Range<u32>,
1020        snapshot: &EditorSnapshot,
1021    ) -> Vec<DisplayDiffHunk> {
1022        let buffer_snapshot = &snapshot.buffer_snapshot;
1023
1024        let buffer_start_row = DisplayPoint::new(display_rows.start, 0)
1025            .to_point(snapshot)
1026            .row;
1027        let buffer_end_row = DisplayPoint::new(display_rows.end, 0)
1028            .to_point(snapshot)
1029            .row;
1030
1031        buffer_snapshot
1032            .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1033            .map(|hunk| diff_hunk_to_display(hunk, snapshot))
1034            .dedup()
1035            .collect()
1036    }
1037
1038    fn layout_code_actions_indicator(
1039        &self,
1040        line_height: Pixels,
1041        newest_selection_head: DisplayPoint,
1042        scroll_pixel_position: gpui::Point<Pixels>,
1043        gutter_dimensions: &GutterDimensions,
1044        gutter_hitbox: &Hitbox,
1045        cx: &mut ElementContext,
1046    ) -> Option<AnyElement> {
1047        let mut active = false;
1048        let mut button = None;
1049        self.editor.update(cx, |editor, cx| {
1050            active = matches!(
1051                editor.context_menu.read().as_ref(),
1052                Some(crate::ContextMenu::CodeActions(_))
1053            );
1054            button = editor.render_code_actions_indicator(&self.style, active, cx);
1055        });
1056
1057        let mut button = button?.into_any_element();
1058        let available_space = size(
1059            AvailableSpace::MinContent,
1060            AvailableSpace::Definite(line_height),
1061        );
1062        let indicator_size = button.measure(available_space, cx);
1063
1064        let mut x = Pixels::ZERO;
1065        let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1066        // Center indicator.
1067        x +=
1068            (gutter_dimensions.margin + gutter_dimensions.left_padding - indicator_size.width) / 2.;
1069        y += (line_height - indicator_size.height) / 2.;
1070        button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1071        Some(button)
1072    }
1073
1074    fn calculate_relative_line_numbers(
1075        &self,
1076        snapshot: &EditorSnapshot,
1077        rows: &Range<u32>,
1078        relative_to: Option<u32>,
1079    ) -> HashMap<u32, u32> {
1080        let mut relative_rows: HashMap<u32, u32> = Default::default();
1081        let Some(relative_to) = relative_to else {
1082            return relative_rows;
1083        };
1084
1085        let start = rows.start.min(relative_to);
1086        let end = rows.end.max(relative_to);
1087
1088        let buffer_rows = snapshot
1089            .buffer_rows(start)
1090            .take(1 + (end - start) as usize)
1091            .collect::<Vec<_>>();
1092
1093        let head_idx = relative_to - start;
1094        let mut delta = 1;
1095        let mut i = head_idx + 1;
1096        while i < buffer_rows.len() as u32 {
1097            if buffer_rows[i as usize].is_some() {
1098                if rows.contains(&(i + start)) {
1099                    relative_rows.insert(i + start, delta);
1100                }
1101                delta += 1;
1102            }
1103            i += 1;
1104        }
1105        delta = 1;
1106        i = head_idx.min(buffer_rows.len() as u32 - 1);
1107        while i > 0 && buffer_rows[i as usize].is_none() {
1108            i -= 1;
1109        }
1110
1111        while i > 0 {
1112            i -= 1;
1113            if buffer_rows[i as usize].is_some() {
1114                if rows.contains(&(i + start)) {
1115                    relative_rows.insert(i + start, delta);
1116                }
1117                delta += 1;
1118            }
1119        }
1120
1121        relative_rows
1122    }
1123
1124    fn layout_line_numbers(
1125        &self,
1126        rows: Range<u32>,
1127        active_rows: &BTreeMap<u32, bool>,
1128        newest_selection_head: Option<DisplayPoint>,
1129        snapshot: &EditorSnapshot,
1130        cx: &ElementContext,
1131    ) -> (
1132        Vec<Option<ShapedLine>>,
1133        Vec<Option<(FoldStatus, BufferRow, bool)>>,
1134    ) {
1135        let editor = self.editor.read(cx);
1136        let is_singleton = editor.is_singleton(cx);
1137        let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1138            let newest = editor.selections.newest::<Point>(cx);
1139            SelectionLayout::new(
1140                newest,
1141                editor.selections.line_mode,
1142                editor.cursor_shape,
1143                &snapshot.display_snapshot,
1144                true,
1145                true,
1146                None,
1147            )
1148            .head
1149        });
1150        let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1151        let include_line_numbers =
1152            EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1153        let include_fold_statuses =
1154            EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1155        let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1156        let mut fold_statuses = Vec::with_capacity(rows.len());
1157        let mut line_number = String::new();
1158        let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1159        let relative_to = if is_relative {
1160            Some(newest_selection_head.row())
1161        } else {
1162            None
1163        };
1164
1165        let relative_rows = self.calculate_relative_line_numbers(&snapshot, &rows, relative_to);
1166
1167        for (ix, row) in snapshot
1168            .buffer_rows(rows.start)
1169            .take((rows.end - rows.start) as usize)
1170            .enumerate()
1171        {
1172            let display_row = rows.start + ix as u32;
1173            let (active, color) = if active_rows.contains_key(&display_row) {
1174                (true, cx.theme().colors().editor_active_line_number)
1175            } else {
1176                (false, cx.theme().colors().editor_line_number)
1177            };
1178            if let Some(buffer_row) = row {
1179                if include_line_numbers {
1180                    line_number.clear();
1181                    let default_number = buffer_row + 1;
1182                    let number = relative_rows
1183                        .get(&(ix as u32 + rows.start))
1184                        .unwrap_or(&default_number);
1185                    write!(&mut line_number, "{}", number).unwrap();
1186                    let run = TextRun {
1187                        len: line_number.len(),
1188                        font: self.style.text.font(),
1189                        color,
1190                        background_color: None,
1191                        underline: None,
1192                        strikethrough: None,
1193                    };
1194                    let shaped_line = cx
1195                        .text_system()
1196                        .shape_line(line_number.clone().into(), font_size, &[run])
1197                        .unwrap();
1198                    shaped_line_numbers.push(Some(shaped_line));
1199                }
1200                if include_fold_statuses {
1201                    fold_statuses.push(
1202                        is_singleton
1203                            .then(|| {
1204                                snapshot
1205                                    .fold_for_line(buffer_row)
1206                                    .map(|fold_status| (fold_status, buffer_row, active))
1207                            })
1208                            .flatten(),
1209                    )
1210                }
1211            } else {
1212                fold_statuses.push(None);
1213                shaped_line_numbers.push(None);
1214            }
1215        }
1216
1217        (shaped_line_numbers, fold_statuses)
1218    }
1219
1220    fn layout_lines(
1221        &self,
1222        rows: Range<u32>,
1223        line_number_layouts: &[Option<ShapedLine>],
1224        snapshot: &EditorSnapshot,
1225        cx: &ElementContext,
1226    ) -> Vec<LineWithInvisibles> {
1227        if rows.start >= rows.end {
1228            return Vec::new();
1229        }
1230
1231        // Show the placeholder when the editor is empty
1232        if snapshot.is_empty() {
1233            let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1234            let placeholder_color = cx.theme().colors().text_placeholder;
1235            let placeholder_text = snapshot.placeholder_text();
1236
1237            let placeholder_lines = placeholder_text
1238                .as_ref()
1239                .map_or("", AsRef::as_ref)
1240                .split('\n')
1241                .skip(rows.start as usize)
1242                .chain(iter::repeat(""))
1243                .take(rows.len());
1244            placeholder_lines
1245                .filter_map(move |line| {
1246                    let run = TextRun {
1247                        len: line.len(),
1248                        font: self.style.text.font(),
1249                        color: placeholder_color,
1250                        background_color: None,
1251                        underline: Default::default(),
1252                        strikethrough: None,
1253                    };
1254                    cx.text_system()
1255                        .shape_line(line.to_string().into(), font_size, &[run])
1256                        .log_err()
1257                })
1258                .map(|line| LineWithInvisibles {
1259                    line,
1260                    invisibles: Vec::new(),
1261                })
1262                .collect()
1263        } else {
1264            let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1265            LineWithInvisibles::from_chunks(
1266                chunks,
1267                &self.style.text,
1268                MAX_LINE_LEN,
1269                rows.len(),
1270                line_number_layouts,
1271                snapshot.mode,
1272                cx,
1273            )
1274        }
1275    }
1276
1277    #[allow(clippy::too_many_arguments)]
1278    fn build_blocks(
1279        &self,
1280        rows: Range<u32>,
1281        snapshot: &EditorSnapshot,
1282        hitbox: &Hitbox,
1283        text_hitbox: &Hitbox,
1284        scroll_width: &mut Pixels,
1285        gutter_dimensions: &GutterDimensions,
1286        em_width: Pixels,
1287        text_x: Pixels,
1288        line_height: Pixels,
1289        line_layouts: &[LineWithInvisibles],
1290        cx: &mut ElementContext,
1291    ) -> Vec<BlockLayout> {
1292        let mut block_id = 0;
1293        let (fixed_blocks, non_fixed_blocks) = snapshot
1294            .blocks_in_range(rows.clone())
1295            .partition::<Vec<_>, _>(|(_, block)| match block {
1296                TransformBlock::ExcerptHeader { .. } => false,
1297                TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1298            });
1299
1300        let render_block = |block: &TransformBlock,
1301                            available_space: Size<AvailableSpace>,
1302                            block_id: usize,
1303                            cx: &mut ElementContext| {
1304            let mut element = match block {
1305                TransformBlock::Custom(block) => {
1306                    let align_to = block
1307                        .position()
1308                        .to_point(&snapshot.buffer_snapshot)
1309                        .to_display_point(snapshot);
1310                    let anchor_x = text_x
1311                        + if rows.contains(&align_to.row()) {
1312                            line_layouts[(align_to.row() - rows.start) as usize]
1313                                .line
1314                                .x_for_index(align_to.column() as usize)
1315                        } else {
1316                            layout_line(align_to.row(), snapshot, &self.style, cx)
1317                                .unwrap()
1318                                .x_for_index(align_to.column() as usize)
1319                        };
1320
1321                    block.render(&mut BlockContext {
1322                        context: cx,
1323                        anchor_x,
1324                        gutter_dimensions,
1325                        line_height,
1326                        em_width,
1327                        block_id,
1328                        max_width: text_hitbox.size.width.max(*scroll_width),
1329                        editor_style: &self.style,
1330                    })
1331                }
1332
1333                TransformBlock::ExcerptHeader {
1334                    buffer,
1335                    range,
1336                    starts_new_buffer,
1337                    ..
1338                } => {
1339                    let include_root = self
1340                        .editor
1341                        .read(cx)
1342                        .project
1343                        .as_ref()
1344                        .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1345                        .unwrap_or_default();
1346
1347                    let jump_handler = project::File::from_dyn(buffer.file()).map(|file| {
1348                        let jump_path = ProjectPath {
1349                            worktree_id: file.worktree_id(cx),
1350                            path: file.path.clone(),
1351                        };
1352                        let jump_anchor = range
1353                            .primary
1354                            .as_ref()
1355                            .map_or(range.context.start, |primary| primary.start);
1356                        let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1357
1358                        cx.listener_for(&self.editor, move |editor, _, cx| {
1359                            editor.jump(jump_path.clone(), jump_position, jump_anchor, cx);
1360                        })
1361                    });
1362
1363                    let element = if *starts_new_buffer {
1364                        let path = buffer.resolve_file_path(cx, include_root);
1365                        let mut filename = None;
1366                        let mut parent_path = None;
1367                        // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1368                        if let Some(path) = path {
1369                            filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1370                            parent_path = path
1371                                .parent()
1372                                .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1373                        }
1374
1375                        v_flex()
1376                            .id(("path header container", block_id))
1377                            .size_full()
1378                            .justify_center()
1379                            .p(gpui::px(6.))
1380                            .child(
1381                                h_flex()
1382                                    .id("path header block")
1383                                    .size_full()
1384                                    .pl(gpui::px(12.))
1385                                    .pr(gpui::px(8.))
1386                                    .rounded_md()
1387                                    .shadow_md()
1388                                    .border()
1389                                    .border_color(cx.theme().colors().border)
1390                                    .bg(cx.theme().colors().editor_subheader_background)
1391                                    .justify_between()
1392                                    .hover(|style| style.bg(cx.theme().colors().element_hover))
1393                                    .child(
1394                                        h_flex().gap_3().child(
1395                                            h_flex()
1396                                                .gap_2()
1397                                                .child(
1398                                                    filename
1399                                                        .map(SharedString::from)
1400                                                        .unwrap_or_else(|| "untitled".into()),
1401                                                )
1402                                                .when_some(parent_path, |then, path| {
1403                                                    then.child(
1404                                                        div().child(path).text_color(
1405                                                            cx.theme().colors().text_muted,
1406                                                        ),
1407                                                    )
1408                                                }),
1409                                        ),
1410                                    )
1411                                    .when_some(jump_handler, |this, jump_handler| {
1412                                        this.cursor_pointer()
1413                                            .tooltip(|cx| {
1414                                                Tooltip::for_action(
1415                                                    "Jump to Buffer",
1416                                                    &OpenExcerpts,
1417                                                    cx,
1418                                                )
1419                                            })
1420                                            .on_mouse_down(MouseButton::Left, |_, cx| {
1421                                                cx.stop_propagation()
1422                                            })
1423                                            .on_click(jump_handler)
1424                                    }),
1425                            )
1426                    } else {
1427                        h_flex()
1428                            .id(("collapsed context", block_id))
1429                            .size_full()
1430                            .gap(gutter_dimensions.left_padding + gutter_dimensions.right_padding)
1431                            .child(
1432                                h_flex()
1433                                    .justify_end()
1434                                    .flex_none()
1435                                    .w(gutter_dimensions.width
1436                                        - (gutter_dimensions.left_padding
1437                                            + gutter_dimensions.right_padding))
1438                                    .h_full()
1439                                    .text_buffer(cx)
1440                                    .text_color(cx.theme().colors().editor_line_number)
1441                                    .child("..."),
1442                            )
1443                            .child(
1444                                ButtonLike::new("jump to collapsed context")
1445                                    .style(ButtonStyle::Transparent)
1446                                    .full_width()
1447                                    .child(
1448                                        div()
1449                                            .h_px()
1450                                            .w_full()
1451                                            .bg(cx.theme().colors().border_variant)
1452                                            .group_hover("", |style| {
1453                                                style.bg(cx.theme().colors().border)
1454                                            }),
1455                                    )
1456                                    .when_some(jump_handler, |this, jump_handler| {
1457                                        this.on_click(jump_handler).tooltip(|cx| {
1458                                            Tooltip::for_action("Jump to Buffer", &OpenExcerpts, cx)
1459                                        })
1460                                    }),
1461                            )
1462                    };
1463                    element.into_any()
1464                }
1465            };
1466
1467            let size = element.measure(available_space, cx);
1468            (element, size)
1469        };
1470
1471        let mut fixed_block_max_width = Pixels::ZERO;
1472        let mut blocks = Vec::new();
1473        for (row, block) in fixed_blocks {
1474            let available_space = size(
1475                AvailableSpace::MinContent,
1476                AvailableSpace::Definite(block.height() as f32 * line_height),
1477            );
1478            let (element, element_size) = render_block(block, available_space, block_id, cx);
1479            block_id += 1;
1480            fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1481            blocks.push(BlockLayout {
1482                row,
1483                element,
1484                available_space,
1485                style: BlockStyle::Fixed,
1486            });
1487        }
1488        for (row, block) in non_fixed_blocks {
1489            let style = match block {
1490                TransformBlock::Custom(block) => block.style(),
1491                TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1492            };
1493            let width = match style {
1494                BlockStyle::Sticky => hitbox.size.width,
1495                BlockStyle::Flex => hitbox
1496                    .size
1497                    .width
1498                    .max(fixed_block_max_width)
1499                    .max(gutter_dimensions.width + *scroll_width),
1500                BlockStyle::Fixed => unreachable!(),
1501            };
1502            let available_space = size(
1503                AvailableSpace::Definite(width),
1504                AvailableSpace::Definite(block.height() as f32 * line_height),
1505            );
1506            let (element, _) = render_block(block, available_space, block_id, cx);
1507            block_id += 1;
1508            blocks.push(BlockLayout {
1509                row,
1510                element,
1511                available_space,
1512                style,
1513            });
1514        }
1515
1516        *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1517        blocks
1518    }
1519
1520    fn layout_blocks(
1521        &self,
1522        blocks: &mut Vec<BlockLayout>,
1523        hitbox: &Hitbox,
1524        line_height: Pixels,
1525        scroll_pixel_position: gpui::Point<Pixels>,
1526        cx: &mut ElementContext,
1527    ) {
1528        for block in blocks {
1529            let mut origin = hitbox.origin
1530                + point(
1531                    Pixels::ZERO,
1532                    block.row as f32 * line_height - scroll_pixel_position.y,
1533                );
1534            if !matches!(block.style, BlockStyle::Sticky) {
1535                origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1536            }
1537            block.element.layout(origin, block.available_space, cx);
1538        }
1539    }
1540
1541    #[allow(clippy::too_many_arguments)]
1542    fn layout_context_menu(
1543        &self,
1544        line_height: Pixels,
1545        hitbox: &Hitbox,
1546        text_hitbox: &Hitbox,
1547        content_origin: gpui::Point<Pixels>,
1548        start_row: u32,
1549        scroll_pixel_position: gpui::Point<Pixels>,
1550        line_layouts: &[LineWithInvisibles],
1551        newest_selection_head: DisplayPoint,
1552        cx: &mut ElementContext,
1553    ) -> bool {
1554        let max_height = cmp::min(
1555            12. * line_height,
1556            cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1557        );
1558        let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1559            if editor.context_menu_visible() {
1560                editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1561            } else {
1562                None
1563            }
1564        }) else {
1565            return false;
1566        };
1567
1568        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1569        let context_menu_size = context_menu.measure(available_space, cx);
1570
1571        let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1572        let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1573        let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1574        let mut list_origin = content_origin + point(x, y);
1575        let list_width = context_menu_size.width;
1576        let list_height = context_menu_size.height;
1577
1578        // Snap the right edge of the list to the right edge of the window if
1579        // its horizontal bounds overflow.
1580        if list_origin.x + list_width > cx.viewport_size().width {
1581            list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1582        }
1583
1584        if list_origin.y + list_height > text_hitbox.lower_right().y {
1585            list_origin.y -= line_height + list_height;
1586        }
1587
1588        cx.defer_draw(context_menu, list_origin, 1);
1589        true
1590    }
1591
1592    fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1593        let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1594        let mut element = overlay()
1595            .position(mouse_context_menu.position)
1596            .child(mouse_context_menu.context_menu.clone())
1597            .anchor(AnchorCorner::TopLeft)
1598            .snap_to_window()
1599            .into_any();
1600        element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1601        Some(element)
1602    }
1603
1604    #[allow(clippy::too_many_arguments)]
1605    fn layout_hover_popovers(
1606        &self,
1607        snapshot: &EditorSnapshot,
1608        hitbox: &Hitbox,
1609        text_hitbox: &Hitbox,
1610        visible_display_row_range: Range<u32>,
1611        content_origin: gpui::Point<Pixels>,
1612        scroll_pixel_position: gpui::Point<Pixels>,
1613        line_layouts: &[LineWithInvisibles],
1614        line_height: Pixels,
1615        em_width: Pixels,
1616        cx: &mut ElementContext,
1617    ) {
1618        let max_size = size(
1619            (120. * em_width) // Default size
1620                .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1621                .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1622            (16. * line_height) // Default size
1623                .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1624                .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1625        );
1626
1627        let hover_popovers = self.editor.update(cx, |editor, cx| {
1628            editor.hover_state.render(
1629                &snapshot,
1630                &self.style,
1631                visible_display_row_range.clone(),
1632                max_size,
1633                editor.workspace.as_ref().map(|(w, _)| w.clone()),
1634                cx,
1635            )
1636        });
1637        let Some((position, mut hover_popovers)) = hover_popovers else {
1638            return;
1639        };
1640
1641        let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1642
1643        // This is safe because we check on layout whether the required row is available
1644        let hovered_row_layout =
1645            &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1646
1647        // Minimum required size: Take the first popover, and add 1.5 times the minimum popover
1648        // height. This is the size we will use to decide whether to render popovers above or below
1649        // the hovered line.
1650        let first_size = hover_popovers[0].measure(available_space, cx);
1651        let height_to_reserve = first_size.height + 1.5 * MIN_POPOVER_LINE_HEIGHT * line_height;
1652
1653        // Compute Hovered Point
1654        let x =
1655            hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1656        let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1657        let hovered_point = content_origin + point(x, y);
1658
1659        if hovered_point.y - height_to_reserve > Pixels::ZERO {
1660            // There is enough space above. Render popovers above the hovered point
1661            let mut current_y = hovered_point.y;
1662            for mut hover_popover in hover_popovers {
1663                let size = hover_popover.measure(available_space, cx);
1664                let mut popover_origin = point(hovered_point.x, current_y - size.height);
1665
1666                let x_out_of_bounds = text_hitbox.upper_right().x - (popover_origin.x + size.width);
1667                if x_out_of_bounds < Pixels::ZERO {
1668                    popover_origin.x = popover_origin.x + x_out_of_bounds;
1669                }
1670
1671                cx.defer_draw(hover_popover, popover_origin, 2);
1672
1673                current_y = popover_origin.y - HOVER_POPOVER_GAP;
1674            }
1675        } else {
1676            // There is not enough space above. Render popovers below the hovered point
1677            let mut current_y = hovered_point.y + line_height;
1678            for mut hover_popover in hover_popovers {
1679                let size = hover_popover.measure(available_space, cx);
1680                let mut popover_origin = point(hovered_point.x, current_y);
1681
1682                let x_out_of_bounds = text_hitbox.upper_right().x - (popover_origin.x + size.width);
1683                if x_out_of_bounds < Pixels::ZERO {
1684                    popover_origin.x = popover_origin.x + x_out_of_bounds;
1685                }
1686
1687                cx.defer_draw(hover_popover, popover_origin, 2);
1688
1689                current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1690            }
1691        }
1692    }
1693
1694    fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
1695        cx.paint_layer(layout.hitbox.bounds, |cx| {
1696            let scroll_top = layout.position_map.snapshot.scroll_position().y;
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                                + (*start_row as f32 - scroll_top)
1717                                    * layout.position_map.line_height,
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                                + (highlight_row_start as f32 - scroll_top)
1734                                    * layout.position_map.line_height,
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        for cursor in &mut layout.cursors {
2087            cursor.paint(layout.content_origin, cx);
2088        }
2089    }
2090
2091    fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2092        let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2093            return;
2094        };
2095
2096        let thumb_bounds = scrollbar_layout.thumb_bounds();
2097        if scrollbar_layout.visible {
2098            cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2099                cx.paint_quad(quad(
2100                    scrollbar_layout.hitbox.bounds,
2101                    Corners::default(),
2102                    cx.theme().colors().scrollbar_track_background,
2103                    Edges {
2104                        top: Pixels::ZERO,
2105                        right: Pixels::ZERO,
2106                        bottom: Pixels::ZERO,
2107                        left: px(1.),
2108                    },
2109                    cx.theme().colors().scrollbar_track_border,
2110                ));
2111                let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2112                let is_singleton = self.editor.read(cx).is_singleton(cx);
2113                if is_singleton && scrollbar_settings.selections {
2114                    let start_anchor = Anchor::min();
2115                    let end_anchor = Anchor::max();
2116                    let background_ranges = self
2117                        .editor
2118                        .read(cx)
2119                        .background_highlight_row_ranges::<BufferSearchHighlights>(
2120                            start_anchor..end_anchor,
2121                            &layout.position_map.snapshot,
2122                            50000,
2123                        );
2124                    for range in background_ranges {
2125                        let start_y = scrollbar_layout.y_for_row(range.start().row() as f32);
2126                        let mut end_y = scrollbar_layout.y_for_row(range.end().row() as f32);
2127                        if end_y - start_y < px(1.) {
2128                            end_y = start_y + px(1.);
2129                        }
2130                        let bounds = Bounds::from_corners(
2131                            point(scrollbar_layout.hitbox.left(), start_y),
2132                            point(scrollbar_layout.hitbox.right(), end_y),
2133                        );
2134                        cx.paint_quad(quad(
2135                            bounds,
2136                            Corners::default(),
2137                            cx.theme().status().info,
2138                            Edges {
2139                                top: Pixels::ZERO,
2140                                right: px(1.),
2141                                bottom: Pixels::ZERO,
2142                                left: px(1.),
2143                            },
2144                            cx.theme().colors().scrollbar_thumb_border,
2145                        ));
2146                    }
2147                }
2148
2149                if is_singleton && scrollbar_settings.symbols_selections {
2150                    let selection_ranges = self.editor.read(cx).background_highlights_in_range(
2151                        Anchor::min()..Anchor::max(),
2152                        &layout.position_map.snapshot,
2153                        cx.theme().colors(),
2154                    );
2155                    for hunk in selection_ranges {
2156                        let start_display = Point::new(hunk.0.start.row(), 0)
2157                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2158                        let end_display = Point::new(hunk.0.end.row(), 0)
2159                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2160                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2161                        let mut end_y = if hunk.0.start == hunk.0.end {
2162                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2163                        } else {
2164                            scrollbar_layout.y_for_row(end_display.row() as f32)
2165                        };
2166
2167                        if end_y - start_y < px(1.) {
2168                            end_y = start_y + px(1.);
2169                        }
2170                        let bounds = Bounds::from_corners(
2171                            point(scrollbar_layout.hitbox.left(), start_y),
2172                            point(scrollbar_layout.hitbox.right(), end_y),
2173                        );
2174
2175                        cx.paint_quad(quad(
2176                            bounds,
2177                            Corners::default(),
2178                            cx.theme().status().info,
2179                            Edges {
2180                                top: Pixels::ZERO,
2181                                right: px(1.),
2182                                bottom: Pixels::ZERO,
2183                                left: px(1.),
2184                            },
2185                            cx.theme().colors().scrollbar_thumb_border,
2186                        ));
2187                    }
2188                }
2189
2190                if is_singleton && scrollbar_settings.git_diff {
2191                    for hunk in layout
2192                        .position_map
2193                        .snapshot
2194                        .buffer_snapshot
2195                        .git_diff_hunks_in_range(0..layout.max_row)
2196                    {
2197                        let start_display = Point::new(hunk.associated_range.start, 0)
2198                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2199                        let end_display = Point::new(hunk.associated_range.end, 0)
2200                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2201                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2202                        let mut end_y = if hunk.associated_range.start == hunk.associated_range.end
2203                        {
2204                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2205                        } else {
2206                            scrollbar_layout.y_for_row(end_display.row() as f32)
2207                        };
2208
2209                        if end_y - start_y < px(1.) {
2210                            end_y = start_y + px(1.);
2211                        }
2212                        let bounds = Bounds::from_corners(
2213                            point(scrollbar_layout.hitbox.left(), start_y),
2214                            point(scrollbar_layout.hitbox.right(), end_y),
2215                        );
2216
2217                        let color = match hunk.status() {
2218                            DiffHunkStatus::Added => cx.theme().status().created,
2219                            DiffHunkStatus::Modified => cx.theme().status().modified,
2220                            DiffHunkStatus::Removed => cx.theme().status().deleted,
2221                        };
2222                        cx.paint_quad(quad(
2223                            bounds,
2224                            Corners::default(),
2225                            color,
2226                            Edges {
2227                                top: Pixels::ZERO,
2228                                right: px(1.),
2229                                bottom: Pixels::ZERO,
2230                                left: px(1.),
2231                            },
2232                            cx.theme().colors().scrollbar_thumb_border,
2233                        ));
2234                    }
2235                }
2236
2237                if is_singleton && scrollbar_settings.diagnostics {
2238                    let max_point = layout
2239                        .position_map
2240                        .snapshot
2241                        .display_snapshot
2242                        .buffer_snapshot
2243                        .max_point();
2244
2245                    let diagnostics = layout
2246                        .position_map
2247                        .snapshot
2248                        .buffer_snapshot
2249                        .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
2250                        // We want to sort by severity, in order to paint the most severe diagnostics last.
2251                        .sorted_by_key(|diagnostic| {
2252                            std::cmp::Reverse(diagnostic.diagnostic.severity)
2253                        });
2254
2255                    for diagnostic in diagnostics {
2256                        let start_display = diagnostic
2257                            .range
2258                            .start
2259                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2260                        let end_display = diagnostic
2261                            .range
2262                            .end
2263                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2264                        let start_y = scrollbar_layout.y_for_row(start_display.row() as f32);
2265                        let mut end_y = if diagnostic.range.start == diagnostic.range.end {
2266                            scrollbar_layout.y_for_row((end_display.row() + 1) as f32)
2267                        } else {
2268                            scrollbar_layout.y_for_row(end_display.row() as f32)
2269                        };
2270
2271                        if end_y - start_y < px(1.) {
2272                            end_y = start_y + px(1.);
2273                        }
2274                        let bounds = Bounds::from_corners(
2275                            point(scrollbar_layout.hitbox.left(), start_y),
2276                            point(scrollbar_layout.hitbox.right(), end_y),
2277                        );
2278
2279                        let color = match diagnostic.diagnostic.severity {
2280                            DiagnosticSeverity::ERROR => cx.theme().status().error,
2281                            DiagnosticSeverity::WARNING => cx.theme().status().warning,
2282                            DiagnosticSeverity::INFORMATION => cx.theme().status().info,
2283                            _ => cx.theme().status().hint,
2284                        };
2285                        cx.paint_quad(quad(
2286                            bounds,
2287                            Corners::default(),
2288                            color,
2289                            Edges {
2290                                top: Pixels::ZERO,
2291                                right: px(1.),
2292                                bottom: Pixels::ZERO,
2293                                left: px(1.),
2294                            },
2295                            cx.theme().colors().scrollbar_thumb_border,
2296                        ));
2297                    }
2298                }
2299
2300                cx.paint_quad(quad(
2301                    thumb_bounds,
2302                    Corners::default(),
2303                    cx.theme().colors().scrollbar_thumb_background,
2304                    Edges {
2305                        top: Pixels::ZERO,
2306                        right: px(1.),
2307                        bottom: Pixels::ZERO,
2308                        left: px(1.),
2309                    },
2310                    cx.theme().colors().scrollbar_thumb_border,
2311                ));
2312            });
2313        }
2314
2315        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2316
2317        let scroll_height = scrollbar_layout.scroll_height;
2318        let height = scrollbar_layout.height;
2319        let row_range = scrollbar_layout.visible_row_range.clone();
2320
2321        cx.on_mouse_event({
2322            let editor = self.editor.clone();
2323            let hitbox = scrollbar_layout.hitbox.clone();
2324            let mut mouse_position = cx.mouse_position();
2325            move |event: &MouseMoveEvent, phase, cx| {
2326                if phase == DispatchPhase::Capture {
2327                    return;
2328                }
2329
2330                editor.update(cx, |editor, cx| {
2331                    if event.pressed_button == Some(MouseButton::Left)
2332                        && editor.scroll_manager.is_dragging_scrollbar()
2333                    {
2334                        let y = mouse_position.y;
2335                        let new_y = event.position.y;
2336                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2337                            let mut position = editor.scroll_position(cx);
2338                            position.y += (new_y - y) * scroll_height / height;
2339                            if position.y < 0.0 {
2340                                position.y = 0.0;
2341                            }
2342                            editor.set_scroll_position(position, cx);
2343                        }
2344
2345                        mouse_position = event.position;
2346                        cx.stop_propagation();
2347                    } else {
2348                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2349                        if hitbox.is_hovered(cx) {
2350                            editor.scroll_manager.show_scrollbar(cx);
2351                        }
2352                    }
2353                })
2354            }
2355        });
2356
2357        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2358            cx.on_mouse_event({
2359                let editor = self.editor.clone();
2360                move |_: &MouseUpEvent, phase, cx| {
2361                    if phase == DispatchPhase::Capture {
2362                        return;
2363                    }
2364
2365                    editor.update(cx, |editor, cx| {
2366                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2367                        cx.stop_propagation();
2368                    });
2369                }
2370            });
2371        } else {
2372            cx.on_mouse_event({
2373                let editor = self.editor.clone();
2374                let hitbox = scrollbar_layout.hitbox.clone();
2375                move |event: &MouseDownEvent, phase, cx| {
2376                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2377                        return;
2378                    }
2379
2380                    editor.update(cx, |editor, cx| {
2381                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2382
2383                        let y = event.position.y;
2384                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2385                            let center_row =
2386                                ((y - hitbox.top()) * scroll_height / height).round() as u32;
2387                            let top_row = center_row
2388                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2389                            let mut position = editor.scroll_position(cx);
2390                            position.y = top_row as f32;
2391                            editor.set_scroll_position(position, cx);
2392                        } else {
2393                            editor.scroll_manager.show_scrollbar(cx);
2394                        }
2395
2396                        cx.stop_propagation();
2397                    });
2398                }
2399            });
2400        }
2401    }
2402
2403    #[allow(clippy::too_many_arguments)]
2404    fn paint_highlighted_range(
2405        &self,
2406        range: Range<DisplayPoint>,
2407        color: Hsla,
2408        corner_radius: Pixels,
2409        line_end_overshoot: Pixels,
2410        layout: &EditorLayout,
2411        cx: &mut ElementContext,
2412    ) {
2413        let start_row = layout.visible_display_row_range.start;
2414        let end_row = layout.visible_display_row_range.end;
2415        if range.start != range.end {
2416            let row_range = if range.end.column() == 0 {
2417                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2418            } else {
2419                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2420            };
2421
2422            let highlighted_range = HighlightedRange {
2423                color,
2424                line_height: layout.position_map.line_height,
2425                corner_radius,
2426                start_y: layout.content_origin.y
2427                    + row_range.start as f32 * layout.position_map.line_height
2428                    - layout.position_map.scroll_pixel_position.y,
2429                lines: row_range
2430                    .into_iter()
2431                    .map(|row| {
2432                        let line_layout =
2433                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2434                        HighlightedRangeLine {
2435                            start_x: if row == range.start.row() {
2436                                layout.content_origin.x
2437                                    + line_layout.x_for_index(range.start.column() as usize)
2438                                    - layout.position_map.scroll_pixel_position.x
2439                            } else {
2440                                layout.content_origin.x
2441                                    - layout.position_map.scroll_pixel_position.x
2442                            },
2443                            end_x: if row == range.end.row() {
2444                                layout.content_origin.x
2445                                    + line_layout.x_for_index(range.end.column() as usize)
2446                                    - layout.position_map.scroll_pixel_position.x
2447                            } else {
2448                                layout.content_origin.x + line_layout.width + line_end_overshoot
2449                                    - layout.position_map.scroll_pixel_position.x
2450                            },
2451                        }
2452                    })
2453                    .collect(),
2454            };
2455
2456            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2457        }
2458    }
2459
2460    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2461        if layout.folds.is_empty() {
2462            return;
2463        }
2464
2465        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2466            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2467            for mut fold in mem::take(&mut layout.folds) {
2468                fold.hover_element.paint(cx);
2469
2470                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2471                let fold_background = if hover_element.interactivity().active.unwrap() {
2472                    cx.theme().colors().ghost_element_active
2473                } else if hover_element.interactivity().hovered.unwrap() {
2474                    cx.theme().colors().ghost_element_hover
2475                } else {
2476                    cx.theme().colors().ghost_element_background
2477                };
2478
2479                self.paint_highlighted_range(
2480                    fold.display_range.clone(),
2481                    fold_background,
2482                    fold_corner_radius,
2483                    fold_corner_radius * 2.,
2484                    layout,
2485                    cx,
2486                );
2487            }
2488        })
2489    }
2490
2491    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2492        for mut block in layout.blocks.drain(..) {
2493            block.element.paint(cx);
2494        }
2495    }
2496
2497    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2498        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2499            mouse_context_menu.paint(cx);
2500        }
2501    }
2502
2503    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2504        cx.on_mouse_event({
2505            let position_map = layout.position_map.clone();
2506            let editor = self.editor.clone();
2507            let hitbox = layout.hitbox.clone();
2508            let mut delta = ScrollDelta::default();
2509
2510            move |event: &ScrollWheelEvent, phase, cx| {
2511                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2512                    delta = delta.coalesce(event.delta);
2513                    editor.update(cx, |editor, cx| {
2514                        let position_map: &PositionMap = &position_map;
2515
2516                        let line_height = position_map.line_height;
2517                        let max_glyph_width = position_map.em_width;
2518                        let (delta, axis) = match delta {
2519                            gpui::ScrollDelta::Pixels(mut pixels) => {
2520                                //Trackpad
2521                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2522                                (pixels, axis)
2523                            }
2524
2525                            gpui::ScrollDelta::Lines(lines) => {
2526                                //Not trackpad
2527                                let pixels =
2528                                    point(lines.x * max_glyph_width, lines.y * line_height);
2529                                (pixels, None)
2530                            }
2531                        };
2532
2533                        let scroll_position = position_map.snapshot.scroll_position();
2534                        let x = (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width;
2535                        let y = (scroll_position.y * line_height - delta.y) / line_height;
2536                        let scroll_position =
2537                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2538                        editor.scroll(scroll_position, axis, cx);
2539                        cx.stop_propagation();
2540                    });
2541                }
2542            }
2543        });
2544    }
2545
2546    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2547        self.paint_scroll_wheel_listener(layout, cx);
2548
2549        cx.on_mouse_event({
2550            let position_map = layout.position_map.clone();
2551            let editor = self.editor.clone();
2552            let text_hitbox = layout.text_hitbox.clone();
2553            let gutter_hitbox = layout.gutter_hitbox.clone();
2554
2555            move |event: &MouseDownEvent, phase, cx| {
2556                if phase == DispatchPhase::Bubble {
2557                    match event.button {
2558                        MouseButton::Left => editor.update(cx, |editor, cx| {
2559                            Self::mouse_left_down(
2560                                editor,
2561                                event,
2562                                &position_map,
2563                                &text_hitbox,
2564                                &gutter_hitbox,
2565                                cx,
2566                            );
2567                        }),
2568                        MouseButton::Right => editor.update(cx, |editor, cx| {
2569                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2570                        }),
2571                        _ => {}
2572                    };
2573                }
2574            }
2575        });
2576
2577        cx.on_mouse_event({
2578            let editor = self.editor.clone();
2579            let position_map = layout.position_map.clone();
2580            let text_hitbox = layout.text_hitbox.clone();
2581
2582            move |event: &MouseUpEvent, phase, cx| {
2583                if phase == DispatchPhase::Bubble {
2584                    editor.update(cx, |editor, cx| {
2585                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2586                    });
2587                }
2588            }
2589        });
2590        cx.on_mouse_event({
2591            let position_map = layout.position_map.clone();
2592            let editor = self.editor.clone();
2593            let text_hitbox = layout.text_hitbox.clone();
2594            let gutter_hitbox = layout.gutter_hitbox.clone();
2595
2596            move |event: &MouseMoveEvent, phase, cx| {
2597                if phase == DispatchPhase::Bubble {
2598                    editor.update(cx, |editor, cx| {
2599                        if event.pressed_button == Some(MouseButton::Left) {
2600                            Self::mouse_dragged(
2601                                editor,
2602                                event,
2603                                &position_map,
2604                                text_hitbox.bounds,
2605                                cx,
2606                            )
2607                        }
2608
2609                        Self::mouse_moved(
2610                            editor,
2611                            event,
2612                            &position_map,
2613                            &text_hitbox,
2614                            &gutter_hitbox,
2615                            cx,
2616                        )
2617                    });
2618                }
2619            }
2620        });
2621    }
2622
2623    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2624        bounds.upper_right().x - self.style.scrollbar_width
2625    }
2626
2627    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2628        let style = &self.style;
2629        let font_size = style.text.font_size.to_pixels(cx.rem_size());
2630        let layout = cx
2631            .text_system()
2632            .shape_line(
2633                SharedString::from(" ".repeat(column)),
2634                font_size,
2635                &[TextRun {
2636                    len: column,
2637                    font: style.text.font(),
2638                    color: Hsla::default(),
2639                    background_color: None,
2640                    underline: None,
2641                    strikethrough: None,
2642                }],
2643            )
2644            .unwrap();
2645
2646        layout.width
2647    }
2648
2649    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2650        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2651        self.column_pixels(digit_count, cx)
2652    }
2653}
2654
2655#[derive(Debug)]
2656pub(crate) struct LineWithInvisibles {
2657    pub line: ShapedLine,
2658    invisibles: Vec<Invisible>,
2659}
2660
2661impl LineWithInvisibles {
2662    fn from_chunks<'a>(
2663        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2664        text_style: &TextStyle,
2665        max_line_len: usize,
2666        max_line_count: usize,
2667        line_number_layouts: &[Option<ShapedLine>],
2668        editor_mode: EditorMode,
2669        cx: &WindowContext,
2670    ) -> Vec<Self> {
2671        let mut layouts = Vec::with_capacity(max_line_count);
2672        let mut line = String::new();
2673        let mut invisibles = Vec::new();
2674        let mut styles = Vec::new();
2675        let mut non_whitespace_added = false;
2676        let mut row = 0;
2677        let mut line_exceeded_max_len = false;
2678        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2679
2680        for highlighted_chunk in chunks.chain([HighlightedChunk {
2681            chunk: "\n",
2682            style: None,
2683            is_tab: false,
2684        }]) {
2685            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2686                if ix > 0 {
2687                    let shaped_line = cx
2688                        .text_system()
2689                        .shape_line(line.clone().into(), font_size, &styles)
2690                        .unwrap();
2691                    layouts.push(Self {
2692                        line: shaped_line,
2693                        invisibles: std::mem::take(&mut invisibles),
2694                    });
2695
2696                    line.clear();
2697                    styles.clear();
2698                    row += 1;
2699                    line_exceeded_max_len = false;
2700                    non_whitespace_added = false;
2701                    if row == max_line_count {
2702                        return layouts;
2703                    }
2704                }
2705
2706                if !line_chunk.is_empty() && !line_exceeded_max_len {
2707                    let text_style = if let Some(style) = highlighted_chunk.style {
2708                        Cow::Owned(text_style.clone().highlight(style))
2709                    } else {
2710                        Cow::Borrowed(text_style)
2711                    };
2712
2713                    if line.len() + line_chunk.len() > max_line_len {
2714                        let mut chunk_len = max_line_len - line.len();
2715                        while !line_chunk.is_char_boundary(chunk_len) {
2716                            chunk_len -= 1;
2717                        }
2718                        line_chunk = &line_chunk[..chunk_len];
2719                        line_exceeded_max_len = true;
2720                    }
2721
2722                    styles.push(TextRun {
2723                        len: line_chunk.len(),
2724                        font: text_style.font(),
2725                        color: text_style.color,
2726                        background_color: text_style.background_color,
2727                        underline: text_style.underline,
2728                        strikethrough: text_style.strikethrough,
2729                    });
2730
2731                    if editor_mode == EditorMode::Full {
2732                        // Line wrap pads its contents with fake whitespaces,
2733                        // avoid printing them
2734                        let inside_wrapped_string = line_number_layouts
2735                            .get(row)
2736                            .and_then(|layout| layout.as_ref())
2737                            .is_none();
2738                        if highlighted_chunk.is_tab {
2739                            if non_whitespace_added || !inside_wrapped_string {
2740                                invisibles.push(Invisible::Tab {
2741                                    line_start_offset: line.len(),
2742                                });
2743                            }
2744                        } else {
2745                            invisibles.extend(
2746                                line_chunk
2747                                    .chars()
2748                                    .enumerate()
2749                                    .filter(|(_, line_char)| {
2750                                        let is_whitespace = line_char.is_whitespace();
2751                                        non_whitespace_added |= !is_whitespace;
2752                                        is_whitespace
2753                                            && (non_whitespace_added || !inside_wrapped_string)
2754                                    })
2755                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2756                                        line_offset: line.len() + whitespace_index,
2757                                    }),
2758                            )
2759                        }
2760                    }
2761
2762                    line.push_str(line_chunk);
2763                }
2764            }
2765        }
2766
2767        layouts
2768    }
2769
2770    fn draw(
2771        &self,
2772        layout: &EditorLayout,
2773        row: u32,
2774        content_origin: gpui::Point<Pixels>,
2775        whitespace_setting: ShowWhitespaceSetting,
2776        selection_ranges: &[Range<DisplayPoint>],
2777        cx: &mut ElementContext,
2778    ) {
2779        let line_height = layout.position_map.line_height;
2780        let line_y =
2781            line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
2782
2783        self.line
2784            .paint(
2785                content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y),
2786                line_height,
2787                cx,
2788            )
2789            .log_err();
2790
2791        self.draw_invisibles(
2792            &selection_ranges,
2793            layout,
2794            content_origin,
2795            line_y,
2796            row,
2797            line_height,
2798            whitespace_setting,
2799            cx,
2800        );
2801    }
2802
2803    #[allow(clippy::too_many_arguments)]
2804    fn draw_invisibles(
2805        &self,
2806        selection_ranges: &[Range<DisplayPoint>],
2807        layout: &EditorLayout,
2808        content_origin: gpui::Point<Pixels>,
2809        line_y: Pixels,
2810        row: u32,
2811        line_height: Pixels,
2812        whitespace_setting: ShowWhitespaceSetting,
2813        cx: &mut ElementContext,
2814    ) {
2815        let allowed_invisibles_regions = match whitespace_setting {
2816            ShowWhitespaceSetting::None => return,
2817            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2818            ShowWhitespaceSetting::All => None,
2819        };
2820
2821        for invisible in &self.invisibles {
2822            let (&token_offset, invisible_symbol) = match invisible {
2823                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2824                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2825            };
2826
2827            let x_offset = self.line.x_for_index(token_offset);
2828            let invisible_offset =
2829                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2830            let origin = content_origin
2831                + gpui::point(
2832                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
2833                    line_y,
2834                );
2835
2836            if let Some(allowed_regions) = allowed_invisibles_regions {
2837                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2838                if !allowed_regions
2839                    .iter()
2840                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2841                {
2842                    continue;
2843                }
2844            }
2845            invisible_symbol.paint(origin, line_height, cx).log_err();
2846        }
2847    }
2848}
2849
2850#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2851enum Invisible {
2852    Tab { line_start_offset: usize },
2853    Whitespace { line_offset: usize },
2854}
2855
2856impl Element for EditorElement {
2857    type BeforeLayout = ();
2858    type AfterLayout = EditorLayout;
2859
2860    fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
2861        self.editor.update(cx, |editor, cx| {
2862            editor.set_style(self.style.clone(), cx);
2863
2864            let layout_id = match editor.mode {
2865                EditorMode::SingleLine => {
2866                    let rem_size = cx.rem_size();
2867                    let mut style = Style::default();
2868                    style.size.width = relative(1.).into();
2869                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2870                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2871                }
2872                EditorMode::AutoHeight { max_lines } => {
2873                    let editor_handle = cx.view().clone();
2874                    let max_line_number_width =
2875                        self.max_line_number_width(&editor.snapshot(cx), cx);
2876                    cx.with_element_context(|cx| {
2877                        cx.request_measured_layout(
2878                            Style::default(),
2879                            move |known_dimensions, _, cx| {
2880                                editor_handle
2881                                    .update(cx, |editor, cx| {
2882                                        compute_auto_height_layout(
2883                                            editor,
2884                                            max_lines,
2885                                            max_line_number_width,
2886                                            known_dimensions,
2887                                            cx,
2888                                        )
2889                                    })
2890                                    .unwrap_or_default()
2891                            },
2892                        )
2893                    })
2894                }
2895                EditorMode::Full => {
2896                    let mut style = Style::default();
2897                    style.size.width = relative(1.).into();
2898                    style.size.height = relative(1.).into();
2899                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2900                }
2901            };
2902
2903            (layout_id, ())
2904        })
2905    }
2906
2907    fn after_layout(
2908        &mut self,
2909        bounds: Bounds<Pixels>,
2910        _: &mut Self::BeforeLayout,
2911        cx: &mut ElementContext,
2912    ) -> Self::AfterLayout {
2913        let text_style = TextStyleRefinement {
2914            font_size: Some(self.style.text.font_size),
2915            line_height: Some(self.style.text.line_height),
2916            ..Default::default()
2917        };
2918        cx.with_text_style(Some(text_style), |cx| {
2919            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2920                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
2921                let style = self.style.clone();
2922
2923                let font_id = cx.text_system().resolve_font(&style.text.font());
2924                let font_size = style.text.font_size.to_pixels(cx.rem_size());
2925                let line_height = style.text.line_height_in_pixels(cx.rem_size());
2926                let em_width = cx
2927                    .text_system()
2928                    .typographic_bounds(font_id, font_size, 'm')
2929                    .unwrap()
2930                    .size
2931                    .width;
2932                let em_advance = cx
2933                    .text_system()
2934                    .advance(font_id, font_size, 'm')
2935                    .unwrap()
2936                    .width;
2937
2938                let gutter_dimensions = snapshot.gutter_dimensions(
2939                    font_id,
2940                    font_size,
2941                    em_width,
2942                    self.max_line_number_width(&snapshot, cx),
2943                    cx,
2944                );
2945                let text_width = bounds.size.width - gutter_dimensions.width;
2946                let overscroll = size(em_width, px(0.));
2947
2948                snapshot = self.editor.update(cx, |editor, cx| {
2949                    editor.gutter_width = gutter_dimensions.width;
2950                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
2951
2952                    let editor_width =
2953                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
2954                    let wrap_width = match editor.soft_wrap_mode(cx) {
2955                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2956                        SoftWrap::EditorWidth => editor_width,
2957                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2958                    };
2959
2960                    if editor.set_wrap_width(Some(wrap_width), cx) {
2961                        editor.snapshot(cx)
2962                    } else {
2963                        snapshot
2964                    }
2965                });
2966
2967                let wrap_guides = self
2968                    .editor
2969                    .read(cx)
2970                    .wrap_guides(cx)
2971                    .iter()
2972                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2973                    .collect::<SmallVec<[_; 2]>>();
2974
2975                let hitbox = cx.insert_hitbox(bounds, false);
2976                let gutter_hitbox = cx.insert_hitbox(
2977                    Bounds {
2978                        origin: bounds.origin,
2979                        size: size(gutter_dimensions.width, bounds.size.height),
2980                    },
2981                    false,
2982                );
2983                let text_hitbox = cx.insert_hitbox(
2984                    Bounds {
2985                        origin: gutter_hitbox.upper_right(),
2986                        size: size(text_width, bounds.size.height),
2987                    },
2988                    false,
2989                );
2990                // Offset the content_bounds from the text_bounds by the gutter margin (which
2991                // is roughly half a character wide) to make hit testing work more like how we want.
2992                let content_origin =
2993                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
2994
2995                let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
2996                    let autoscroll_horizontally =
2997                        editor.autoscroll_vertically(bounds.size.height, line_height, cx);
2998                    snapshot = editor.snapshot(cx);
2999                    autoscroll_horizontally
3000                });
3001
3002                let mut scroll_position = snapshot.scroll_position();
3003                // The scroll position is a fractional point, the whole number of which represents
3004                // the top of the window in terms of display rows.
3005                let start_row = scroll_position.y as u32;
3006                let height_in_lines = bounds.size.height / line_height;
3007                let max_row = snapshot.max_point().row();
3008
3009                // Add 1 to ensure selections bleed off screen
3010                let end_row =
3011                    1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3012
3013                let start_anchor = if start_row == 0 {
3014                    Anchor::min()
3015                } else {
3016                    snapshot.buffer_snapshot.anchor_before(
3017                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3018                    )
3019                };
3020                let end_anchor = if end_row > max_row {
3021                    Anchor::max()
3022                } else {
3023                    snapshot.buffer_snapshot.anchor_before(
3024                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3025                    )
3026                };
3027
3028                let highlighted_rows = self
3029                    .editor
3030                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3031                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3032                    start_anchor..end_anchor,
3033                    &snapshot.display_snapshot,
3034                    cx.theme().colors(),
3035                );
3036
3037                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3038                    start_anchor..end_anchor,
3039                    &snapshot.display_snapshot,
3040                    cx,
3041                );
3042
3043                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3044                    start_anchor,
3045                    end_anchor,
3046                    &snapshot,
3047                    start_row,
3048                    end_row,
3049                    cx,
3050                );
3051
3052                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3053                    start_row..end_row,
3054                    &active_rows,
3055                    newest_selection_head,
3056                    &snapshot,
3057                    cx,
3058                );
3059
3060                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3061
3062                let mut max_visible_line_width = Pixels::ZERO;
3063                let line_layouts =
3064                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3065                for line_with_invisibles in &line_layouts {
3066                    if line_with_invisibles.line.width > max_visible_line_width {
3067                        max_visible_line_width = line_with_invisibles.line.width;
3068                    }
3069                }
3070
3071                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3072                    .unwrap()
3073                    .width;
3074                let mut scroll_width =
3075                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3076                let mut blocks = self.build_blocks(
3077                    start_row..end_row,
3078                    &snapshot,
3079                    &hitbox,
3080                    &text_hitbox,
3081                    &mut scroll_width,
3082                    &gutter_dimensions,
3083                    em_width,
3084                    gutter_dimensions.width + gutter_dimensions.margin,
3085                    line_height,
3086                    &line_layouts,
3087                    cx,
3088                );
3089
3090                let scroll_max = point(
3091                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3092                    max_row as f32,
3093                );
3094
3095                self.editor.update(cx, |editor, cx| {
3096                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3097
3098                    let autoscrolled = if autoscroll_horizontally {
3099                        editor.autoscroll_horizontally(
3100                            start_row,
3101                            text_hitbox.size.width,
3102                            scroll_width,
3103                            em_width,
3104                            &line_layouts,
3105                            cx,
3106                        )
3107                    } else {
3108                        false
3109                    };
3110
3111                    if clamped || autoscrolled {
3112                        snapshot = editor.snapshot(cx);
3113                        scroll_position = snapshot.scroll_position();
3114                    }
3115                });
3116
3117                let scroll_pixel_position = point(
3118                    scroll_position.x * em_width,
3119                    scroll_position.y * line_height,
3120                );
3121
3122                cx.with_element_id(Some("blocks"), |cx| {
3123                    self.layout_blocks(
3124                        &mut blocks,
3125                        &hitbox,
3126                        line_height,
3127                        scroll_pixel_position,
3128                        cx,
3129                    );
3130                });
3131
3132                let cursors = self.layout_cursors(
3133                    &snapshot,
3134                    &selections,
3135                    start_row..end_row,
3136                    &line_layouts,
3137                    &text_hitbox,
3138                    content_origin,
3139                    scroll_pixel_position,
3140                    line_height,
3141                    em_width,
3142                    cx,
3143                );
3144
3145                let scrollbar_layout = self.layout_scrollbar(
3146                    &snapshot,
3147                    bounds,
3148                    scroll_position,
3149                    line_height,
3150                    height_in_lines,
3151                    cx,
3152                );
3153
3154                let folds = cx.with_element_id(Some("folds"), |cx| {
3155                    self.layout_folds(
3156                        &snapshot,
3157                        content_origin,
3158                        start_anchor..end_anchor,
3159                        start_row..end_row,
3160                        scroll_pixel_position,
3161                        line_height,
3162                        &line_layouts,
3163                        cx,
3164                    )
3165                });
3166
3167                let gutter_settings = EditorSettings::get_global(cx).gutter;
3168
3169                let mut context_menu_visible = false;
3170                let mut code_actions_indicator = None;
3171                if let Some(newest_selection_head) = newest_selection_head {
3172                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3173                        context_menu_visible = self.layout_context_menu(
3174                            line_height,
3175                            &hitbox,
3176                            &text_hitbox,
3177                            content_origin,
3178                            start_row,
3179                            scroll_pixel_position,
3180                            &line_layouts,
3181                            newest_selection_head,
3182                            cx,
3183                        );
3184                        if gutter_settings.code_actions {
3185                            code_actions_indicator = self.layout_code_actions_indicator(
3186                                line_height,
3187                                newest_selection_head,
3188                                scroll_pixel_position,
3189                                &gutter_dimensions,
3190                                &gutter_hitbox,
3191                                cx,
3192                            );
3193                        }
3194                    }
3195                }
3196
3197                if !context_menu_visible && !cx.has_active_drag() {
3198                    self.layout_hover_popovers(
3199                        &snapshot,
3200                        &hitbox,
3201                        &text_hitbox,
3202                        start_row..end_row,
3203                        content_origin,
3204                        scroll_pixel_position,
3205                        &line_layouts,
3206                        line_height,
3207                        em_width,
3208                        cx,
3209                    );
3210                }
3211
3212                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3213
3214                let fold_indicators = if gutter_settings.folds {
3215                    cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3216                        self.layout_gutter_fold_indicators(
3217                            fold_statuses,
3218                            line_height,
3219                            &gutter_dimensions,
3220                            gutter_settings,
3221                            scroll_pixel_position,
3222                            &gutter_hitbox,
3223                            cx,
3224                        )
3225                    })
3226                } else {
3227                    Vec::new()
3228                };
3229
3230                let invisible_symbol_font_size = font_size / 2.;
3231                let tab_invisible = cx
3232                    .text_system()
3233                    .shape_line(
3234                        "".into(),
3235                        invisible_symbol_font_size,
3236                        &[TextRun {
3237                            len: "".len(),
3238                            font: self.style.text.font(),
3239                            color: cx.theme().colors().editor_invisible,
3240                            background_color: None,
3241                            underline: None,
3242                            strikethrough: None,
3243                        }],
3244                    )
3245                    .unwrap();
3246                let space_invisible = cx
3247                    .text_system()
3248                    .shape_line(
3249                        "".into(),
3250                        invisible_symbol_font_size,
3251                        &[TextRun {
3252                            len: "".len(),
3253                            font: self.style.text.font(),
3254                            color: cx.theme().colors().editor_invisible,
3255                            background_color: None,
3256                            underline: None,
3257                            strikethrough: None,
3258                        }],
3259                    )
3260                    .unwrap();
3261
3262                EditorLayout {
3263                    mode: snapshot.mode,
3264                    position_map: Arc::new(PositionMap {
3265                        size: bounds.size,
3266                        scroll_pixel_position,
3267                        scroll_max,
3268                        line_layouts,
3269                        line_height,
3270                        em_width,
3271                        em_advance,
3272                        snapshot,
3273                    }),
3274                    visible_display_row_range: start_row..end_row,
3275                    wrap_guides,
3276                    hitbox,
3277                    text_hitbox,
3278                    gutter_hitbox,
3279                    gutter_dimensions,
3280                    content_origin,
3281                    scrollbar_layout,
3282                    max_row,
3283                    active_rows,
3284                    highlighted_rows,
3285                    highlighted_ranges,
3286                    redacted_ranges,
3287                    line_numbers,
3288                    display_hunks,
3289                    folds,
3290                    blocks,
3291                    cursors,
3292                    selections,
3293                    mouse_context_menu,
3294                    code_actions_indicator,
3295                    fold_indicators,
3296                    tab_invisible,
3297                    space_invisible,
3298                }
3299            })
3300        })
3301    }
3302
3303    fn paint(
3304        &mut self,
3305        bounds: Bounds<gpui::Pixels>,
3306        _: &mut Self::BeforeLayout,
3307        layout: &mut Self::AfterLayout,
3308        cx: &mut ElementContext,
3309    ) {
3310        let focus_handle = self.editor.focus_handle(cx);
3311        let key_context = self.editor.read(cx).key_context(cx);
3312        cx.set_focus_handle(&focus_handle);
3313        cx.set_key_context(key_context);
3314        cx.set_view_id(self.editor.entity_id());
3315        cx.handle_input(
3316            &focus_handle,
3317            ElementInputHandler::new(bounds, self.editor.clone()),
3318        );
3319        self.register_actions(cx);
3320        self.register_key_listeners(cx, layout);
3321
3322        let text_style = TextStyleRefinement {
3323            font_size: Some(self.style.text.font_size),
3324            line_height: Some(self.style.text.line_height),
3325            ..Default::default()
3326        };
3327        cx.with_text_style(Some(text_style), |cx| {
3328            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3329                self.paint_mouse_listeners(layout, cx);
3330
3331                self.paint_background(layout, cx);
3332                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3333                    self.paint_gutter(layout, cx);
3334                }
3335                self.paint_text(layout, cx);
3336
3337                if !layout.blocks.is_empty() {
3338                    cx.with_element_id(Some("blocks"), |cx| {
3339                        self.paint_blocks(layout, cx);
3340                    });
3341                }
3342
3343                self.paint_scrollbar(layout, cx);
3344                self.paint_mouse_context_menu(layout, cx);
3345            });
3346        })
3347    }
3348}
3349
3350impl IntoElement for EditorElement {
3351    type Element = Self;
3352
3353    fn into_element(self) -> Self::Element {
3354        self
3355    }
3356}
3357
3358type BufferRow = u32;
3359
3360pub struct EditorLayout {
3361    position_map: Arc<PositionMap>,
3362    hitbox: Hitbox,
3363    text_hitbox: Hitbox,
3364    gutter_hitbox: Hitbox,
3365    gutter_dimensions: GutterDimensions,
3366    content_origin: gpui::Point<Pixels>,
3367    scrollbar_layout: Option<ScrollbarLayout>,
3368    mode: EditorMode,
3369    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3370    visible_display_row_range: Range<u32>,
3371    active_rows: BTreeMap<u32, bool>,
3372    highlighted_rows: BTreeMap<u32, Hsla>,
3373    line_numbers: Vec<Option<ShapedLine>>,
3374    display_hunks: Vec<DisplayDiffHunk>,
3375    folds: Vec<FoldLayout>,
3376    blocks: Vec<BlockLayout>,
3377    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3378    redacted_ranges: Vec<Range<DisplayPoint>>,
3379    cursors: Vec<CursorLayout>,
3380    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3381    max_row: u32,
3382    code_actions_indicator: Option<AnyElement>,
3383    fold_indicators: Vec<Option<AnyElement>>,
3384    mouse_context_menu: Option<AnyElement>,
3385    tab_invisible: ShapedLine,
3386    space_invisible: ShapedLine,
3387}
3388
3389impl EditorLayout {
3390    fn line_end_overshoot(&self) -> Pixels {
3391        0.15 * self.position_map.line_height
3392    }
3393}
3394
3395struct ScrollbarLayout {
3396    hitbox: Hitbox,
3397    visible_row_range: Range<f32>,
3398    visible: bool,
3399    height: Pixels,
3400    scroll_height: f32,
3401    first_row_y_offset: Pixels,
3402    row_height: Pixels,
3403}
3404
3405impl ScrollbarLayout {
3406    fn thumb_bounds(&self) -> Bounds<Pixels> {
3407        let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
3408        let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
3409        Bounds::from_corners(
3410            point(self.hitbox.left(), thumb_top),
3411            point(self.hitbox.right(), thumb_bottom),
3412        )
3413    }
3414
3415    fn y_for_row(&self, row: f32) -> Pixels {
3416        self.hitbox.top() + self.first_row_y_offset + row * self.row_height
3417    }
3418}
3419
3420struct FoldLayout {
3421    display_range: Range<DisplayPoint>,
3422    hover_element: AnyElement,
3423}
3424
3425struct PositionMap {
3426    size: Size<Pixels>,
3427    line_height: Pixels,
3428    scroll_pixel_position: gpui::Point<Pixels>,
3429    scroll_max: gpui::Point<f32>,
3430    em_width: Pixels,
3431    em_advance: Pixels,
3432    line_layouts: Vec<LineWithInvisibles>,
3433    snapshot: EditorSnapshot,
3434}
3435
3436#[derive(Debug, Copy, Clone)]
3437pub struct PointForPosition {
3438    pub previous_valid: DisplayPoint,
3439    pub next_valid: DisplayPoint,
3440    pub exact_unclipped: DisplayPoint,
3441    pub column_overshoot_after_line_end: u32,
3442}
3443
3444impl PointForPosition {
3445    pub fn as_valid(&self) -> Option<DisplayPoint> {
3446        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3447            Some(self.previous_valid)
3448        } else {
3449            None
3450        }
3451    }
3452}
3453
3454impl PositionMap {
3455    fn point_for_position(
3456        &self,
3457        text_bounds: Bounds<Pixels>,
3458        position: gpui::Point<Pixels>,
3459    ) -> PointForPosition {
3460        let scroll_position = self.snapshot.scroll_position();
3461        let position = position - text_bounds.origin;
3462        let y = position.y.max(px(0.)).min(self.size.height);
3463        let x = position.x + (scroll_position.x * self.em_width);
3464        let row = ((y / self.line_height) + scroll_position.y) as u32;
3465
3466        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3467            .line_layouts
3468            .get(row as usize - scroll_position.y as usize)
3469            .map(|LineWithInvisibles { line, .. }| line)
3470        {
3471            if let Some(ix) = line.index_for_x(x) {
3472                (ix as u32, px(0.))
3473            } else {
3474                (line.len as u32, px(0.).max(x - line.width))
3475            }
3476        } else {
3477            (0, x)
3478        };
3479
3480        let mut exact_unclipped = DisplayPoint::new(row, column);
3481        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3482        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3483
3484        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3485        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3486        PointForPosition {
3487            previous_valid,
3488            next_valid,
3489            exact_unclipped,
3490            column_overshoot_after_line_end,
3491        }
3492    }
3493}
3494
3495struct BlockLayout {
3496    row: u32,
3497    element: AnyElement,
3498    available_space: Size<AvailableSpace>,
3499    style: BlockStyle,
3500}
3501
3502fn layout_line(
3503    row: u32,
3504    snapshot: &EditorSnapshot,
3505    style: &EditorStyle,
3506    cx: &WindowContext,
3507) -> Result<ShapedLine> {
3508    let mut line = snapshot.line(row);
3509
3510    if line.len() > MAX_LINE_LEN {
3511        let mut len = MAX_LINE_LEN;
3512        while !line.is_char_boundary(len) {
3513            len -= 1;
3514        }
3515
3516        line.truncate(len);
3517    }
3518
3519    cx.text_system().shape_line(
3520        line.into(),
3521        style.text.font_size.to_pixels(cx.rem_size()),
3522        &[TextRun {
3523            len: snapshot.line_len(row) as usize,
3524            font: style.text.font(),
3525            color: Hsla::default(),
3526            background_color: None,
3527            underline: None,
3528            strikethrough: None,
3529        }],
3530    )
3531}
3532
3533pub struct CursorLayout {
3534    origin: gpui::Point<Pixels>,
3535    block_width: Pixels,
3536    line_height: Pixels,
3537    color: Hsla,
3538    shape: CursorShape,
3539    block_text: Option<ShapedLine>,
3540    cursor_name: Option<AnyElement>,
3541}
3542
3543#[derive(Debug)]
3544pub struct CursorName {
3545    string: SharedString,
3546    color: Hsla,
3547    is_top_row: bool,
3548}
3549
3550impl CursorLayout {
3551    pub fn new(
3552        origin: gpui::Point<Pixels>,
3553        block_width: Pixels,
3554        line_height: Pixels,
3555        color: Hsla,
3556        shape: CursorShape,
3557        block_text: Option<ShapedLine>,
3558    ) -> CursorLayout {
3559        CursorLayout {
3560            origin,
3561            block_width,
3562            line_height,
3563            color,
3564            shape,
3565            block_text,
3566            cursor_name: None,
3567        }
3568    }
3569
3570    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3571        Bounds {
3572            origin: self.origin + origin,
3573            size: size(self.block_width, self.line_height),
3574        }
3575    }
3576
3577    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3578        match self.shape {
3579            CursorShape::Bar => Bounds {
3580                origin: self.origin + origin,
3581                size: size(px(2.0), self.line_height),
3582            },
3583            CursorShape::Block | CursorShape::Hollow => Bounds {
3584                origin: self.origin + origin,
3585                size: size(self.block_width, self.line_height),
3586            },
3587            CursorShape::Underscore => Bounds {
3588                origin: self.origin
3589                    + origin
3590                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3591                size: size(self.block_width, px(2.0)),
3592            },
3593        }
3594    }
3595
3596    pub fn layout(
3597        &mut self,
3598        origin: gpui::Point<Pixels>,
3599        cursor_name: Option<CursorName>,
3600        cx: &mut ElementContext,
3601    ) {
3602        if let Some(cursor_name) = cursor_name {
3603            let bounds = self.bounds(origin);
3604            let text_size = self.line_height / 1.5;
3605
3606            let name_origin = if cursor_name.is_top_row {
3607                point(bounds.right() - px(1.), bounds.top())
3608            } else {
3609                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
3610            };
3611            let mut name_element = div()
3612                .bg(self.color)
3613                .text_size(text_size)
3614                .px_0p5()
3615                .line_height(text_size + px(2.))
3616                .text_color(cursor_name.color)
3617                .child(cursor_name.string.clone())
3618                .into_any_element();
3619
3620            name_element.layout(
3621                name_origin,
3622                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
3623                cx,
3624            );
3625
3626            self.cursor_name = Some(name_element);
3627        }
3628    }
3629
3630    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
3631        let bounds = self.bounds(origin);
3632
3633        //Draw background or border quad
3634        let cursor = if matches!(self.shape, CursorShape::Hollow) {
3635            outline(bounds, self.color)
3636        } else {
3637            fill(bounds, self.color)
3638        };
3639
3640        if let Some(name) = &mut self.cursor_name {
3641            name.paint(cx);
3642        }
3643
3644        cx.paint_quad(cursor);
3645
3646        if let Some(block_text) = &self.block_text {
3647            block_text
3648                .paint(self.origin + origin, self.line_height, cx)
3649                .log_err();
3650        }
3651    }
3652
3653    pub fn shape(&self) -> CursorShape {
3654        self.shape
3655    }
3656}
3657
3658#[derive(Debug)]
3659pub struct HighlightedRange {
3660    pub start_y: Pixels,
3661    pub line_height: Pixels,
3662    pub lines: Vec<HighlightedRangeLine>,
3663    pub color: Hsla,
3664    pub corner_radius: Pixels,
3665}
3666
3667#[derive(Debug)]
3668pub struct HighlightedRangeLine {
3669    pub start_x: Pixels,
3670    pub end_x: Pixels,
3671}
3672
3673impl HighlightedRange {
3674    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
3675        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3676            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3677            self.paint_lines(
3678                self.start_y + self.line_height,
3679                &self.lines[1..],
3680                bounds,
3681                cx,
3682            );
3683        } else {
3684            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3685        }
3686    }
3687
3688    fn paint_lines(
3689        &self,
3690        start_y: Pixels,
3691        lines: &[HighlightedRangeLine],
3692        _bounds: Bounds<Pixels>,
3693        cx: &mut ElementContext,
3694    ) {
3695        if lines.is_empty() {
3696            return;
3697        }
3698
3699        let first_line = lines.first().unwrap();
3700        let last_line = lines.last().unwrap();
3701
3702        let first_top_left = point(first_line.start_x, start_y);
3703        let first_top_right = point(first_line.end_x, start_y);
3704
3705        let curve_height = point(Pixels::ZERO, self.corner_radius);
3706        let curve_width = |start_x: Pixels, end_x: Pixels| {
3707            let max = (end_x - start_x) / 2.;
3708            let width = if max < self.corner_radius {
3709                max
3710            } else {
3711                self.corner_radius
3712            };
3713
3714            point(width, Pixels::ZERO)
3715        };
3716
3717        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3718        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3719        path.curve_to(first_top_right + curve_height, first_top_right);
3720
3721        let mut iter = lines.iter().enumerate().peekable();
3722        while let Some((ix, line)) = iter.next() {
3723            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3724
3725            if let Some((_, next_line)) = iter.peek() {
3726                let next_top_right = point(next_line.end_x, bottom_right.y);
3727
3728                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3729                    Ordering::Equal => {
3730                        path.line_to(bottom_right);
3731                    }
3732                    Ordering::Less => {
3733                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3734                        path.line_to(bottom_right - curve_height);
3735                        if self.corner_radius > Pixels::ZERO {
3736                            path.curve_to(bottom_right - curve_width, bottom_right);
3737                        }
3738                        path.line_to(next_top_right + curve_width);
3739                        if self.corner_radius > Pixels::ZERO {
3740                            path.curve_to(next_top_right + curve_height, next_top_right);
3741                        }
3742                    }
3743                    Ordering::Greater => {
3744                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3745                        path.line_to(bottom_right - curve_height);
3746                        if self.corner_radius > Pixels::ZERO {
3747                            path.curve_to(bottom_right + curve_width, bottom_right);
3748                        }
3749                        path.line_to(next_top_right - curve_width);
3750                        if self.corner_radius > Pixels::ZERO {
3751                            path.curve_to(next_top_right + curve_height, next_top_right);
3752                        }
3753                    }
3754                }
3755            } else {
3756                let curve_width = curve_width(line.start_x, line.end_x);
3757                path.line_to(bottom_right - curve_height);
3758                if self.corner_radius > Pixels::ZERO {
3759                    path.curve_to(bottom_right - curve_width, bottom_right);
3760                }
3761
3762                let bottom_left = point(line.start_x, bottom_right.y);
3763                path.line_to(bottom_left + curve_width);
3764                if self.corner_radius > Pixels::ZERO {
3765                    path.curve_to(bottom_left - curve_height, bottom_left);
3766                }
3767            }
3768        }
3769
3770        if first_line.start_x > last_line.start_x {
3771            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3772            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3773            path.line_to(second_top_left + curve_height);
3774            if self.corner_radius > Pixels::ZERO {
3775                path.curve_to(second_top_left + curve_width, second_top_left);
3776            }
3777            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3778            path.line_to(first_bottom_left - curve_width);
3779            if self.corner_radius > Pixels::ZERO {
3780                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3781            }
3782        }
3783
3784        path.line_to(first_top_left + curve_height);
3785        if self.corner_radius > Pixels::ZERO {
3786            path.curve_to(first_top_left + top_curve_width, first_top_left);
3787        }
3788        path.line_to(first_top_right - top_curve_width);
3789
3790        cx.paint_path(path, self.color);
3791    }
3792}
3793
3794pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3795    (delta.pow(1.5) / 100.0).into()
3796}
3797
3798fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3799    (delta.pow(1.2) / 300.0).into()
3800}
3801
3802#[cfg(test)]
3803mod tests {
3804    use super::*;
3805    use crate::{
3806        display_map::{BlockDisposition, BlockProperties},
3807        editor_tests::{init_test, update_test_language_settings},
3808        Editor, MultiBuffer,
3809    };
3810    use gpui::TestAppContext;
3811    use language::language_settings;
3812    use log::info;
3813    use std::{num::NonZeroU32, sync::Arc};
3814    use util::test::sample_text;
3815
3816    #[gpui::test]
3817    fn test_shape_line_numbers(cx: &mut TestAppContext) {
3818        init_test(cx, |_| {});
3819        let window = cx.add_window(|cx| {
3820            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3821            Editor::new(EditorMode::Full, buffer, None, cx)
3822        });
3823
3824        let editor = window.root(cx).unwrap();
3825        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3826        let element = EditorElement::new(&editor, style);
3827        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
3828
3829        let layouts = cx
3830            .update_window(*window, |_, cx| {
3831                cx.with_element_context(|cx| {
3832                    element
3833                        .layout_line_numbers(
3834                            0..6,
3835                            &Default::default(),
3836                            Some(DisplayPoint::new(0, 0)),
3837                            &snapshot,
3838                            cx,
3839                        )
3840                        .0
3841                })
3842            })
3843            .unwrap();
3844        assert_eq!(layouts.len(), 6);
3845
3846        let relative_rows = window
3847            .update(cx, |editor, cx| {
3848                let snapshot = editor.snapshot(cx);
3849                element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3850            })
3851            .unwrap();
3852        assert_eq!(relative_rows[&0], 3);
3853        assert_eq!(relative_rows[&1], 2);
3854        assert_eq!(relative_rows[&2], 1);
3855        // current line has no relative number
3856        assert_eq!(relative_rows[&4], 1);
3857        assert_eq!(relative_rows[&5], 2);
3858
3859        // works if cursor is before screen
3860        let relative_rows = window
3861            .update(cx, |editor, cx| {
3862                let snapshot = editor.snapshot(cx);
3863
3864                element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3865            })
3866            .unwrap();
3867        assert_eq!(relative_rows.len(), 3);
3868        assert_eq!(relative_rows[&3], 2);
3869        assert_eq!(relative_rows[&4], 3);
3870        assert_eq!(relative_rows[&5], 4);
3871
3872        // works if cursor is after screen
3873        let relative_rows = window
3874            .update(cx, |editor, cx| {
3875                let snapshot = editor.snapshot(cx);
3876
3877                element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3878            })
3879            .unwrap();
3880        assert_eq!(relative_rows.len(), 3);
3881        assert_eq!(relative_rows[&0], 5);
3882        assert_eq!(relative_rows[&1], 4);
3883        assert_eq!(relative_rows[&2], 3);
3884    }
3885
3886    #[gpui::test]
3887    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3888        init_test(cx, |_| {});
3889
3890        let window = cx.add_window(|cx| {
3891            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3892            Editor::new(EditorMode::Full, buffer, None, cx)
3893        });
3894        let editor = window.root(cx).unwrap();
3895        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3896        let mut element = EditorElement::new(&editor, style);
3897
3898        window
3899            .update(cx, |editor, cx| {
3900                editor.cursor_shape = CursorShape::Block;
3901                editor.change_selections(None, cx, |s| {
3902                    s.select_ranges([
3903                        Point::new(0, 0)..Point::new(1, 0),
3904                        Point::new(3, 2)..Point::new(3, 3),
3905                        Point::new(5, 6)..Point::new(6, 0),
3906                    ]);
3907                });
3908            })
3909            .unwrap();
3910        let state = cx
3911            .update_window(window.into(), |_view, cx| {
3912                cx.with_element_context(|cx| {
3913                    element.after_layout(
3914                        Bounds {
3915                            origin: point(px(500.), px(500.)),
3916                            size: size(px(500.), px(500.)),
3917                        },
3918                        &mut (),
3919                        cx,
3920                    )
3921                })
3922            })
3923            .unwrap();
3924
3925        assert_eq!(state.selections.len(), 1);
3926        let local_selections = &state.selections[0].1;
3927        assert_eq!(local_selections.len(), 3);
3928        // moves cursor back one line
3929        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3930        assert_eq!(
3931            local_selections[0].range,
3932            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3933        );
3934
3935        // moves cursor back one column
3936        assert_eq!(
3937            local_selections[1].range,
3938            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3939        );
3940        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3941
3942        // leaves cursor on the max point
3943        assert_eq!(
3944            local_selections[2].range,
3945            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3946        );
3947        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3948
3949        // active lines does not include 1 (even though the range of the selection does)
3950        assert_eq!(
3951            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3952            vec![0, 3, 5, 6]
3953        );
3954
3955        // multi-buffer support
3956        // in DisplayPoint coordinates, this is what we're dealing with:
3957        //  0: [[file
3958        //  1:   header]]
3959        //  2: aaaaaa
3960        //  3: bbbbbb
3961        //  4: cccccc
3962        //  5:
3963        //  6: ...
3964        //  7: ffffff
3965        //  8: gggggg
3966        //  9: hhhhhh
3967        // 10:
3968        // 11: [[file
3969        // 12:   header]]
3970        // 13: bbbbbb
3971        // 14: cccccc
3972        // 15: dddddd
3973        let window = cx.add_window(|cx| {
3974            let buffer = MultiBuffer::build_multi(
3975                [
3976                    (
3977                        &(sample_text(8, 6, 'a') + "\n"),
3978                        vec![
3979                            Point::new(0, 0)..Point::new(3, 0),
3980                            Point::new(4, 0)..Point::new(7, 0),
3981                        ],
3982                    ),
3983                    (
3984                        &(sample_text(8, 6, 'a') + "\n"),
3985                        vec![Point::new(1, 0)..Point::new(3, 0)],
3986                    ),
3987                ],
3988                cx,
3989            );
3990            Editor::new(EditorMode::Full, buffer, None, cx)
3991        });
3992        let editor = window.root(cx).unwrap();
3993        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3994        let mut element = EditorElement::new(&editor, style);
3995        let _state = window.update(cx, |editor, cx| {
3996            editor.cursor_shape = CursorShape::Block;
3997            editor.change_selections(None, cx, |s| {
3998                s.select_display_ranges([
3999                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4000                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4001                ]);
4002            });
4003        });
4004
4005        let state = cx
4006            .update_window(window.into(), |_view, cx| {
4007                cx.with_element_context(|cx| {
4008                    element.after_layout(
4009                        Bounds {
4010                            origin: point(px(500.), px(500.)),
4011                            size: size(px(500.), px(500.)),
4012                        },
4013                        &mut (),
4014                        cx,
4015                    )
4016                })
4017            })
4018            .unwrap();
4019        assert_eq!(state.selections.len(), 1);
4020        let local_selections = &state.selections[0].1;
4021        assert_eq!(local_selections.len(), 2);
4022
4023        // moves cursor on excerpt boundary back a line
4024        // and doesn't allow selection to bleed through
4025        assert_eq!(
4026            local_selections[0].range,
4027            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4028        );
4029        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4030        // moves cursor on buffer boundary back two lines
4031        // and doesn't allow selection to bleed through
4032        assert_eq!(
4033            local_selections[1].range,
4034            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4035        );
4036        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4037    }
4038
4039    #[gpui::test]
4040    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4041        init_test(cx, |_| {});
4042
4043        let window = cx.add_window(|cx| {
4044            let buffer = MultiBuffer::build_simple("", cx);
4045            Editor::new(EditorMode::Full, buffer, None, cx)
4046        });
4047        let editor = window.root(cx).unwrap();
4048        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4049        window
4050            .update(cx, |editor, cx| {
4051                editor.set_placeholder_text("hello", cx);
4052                editor.insert_blocks(
4053                    [BlockProperties {
4054                        style: BlockStyle::Fixed,
4055                        disposition: BlockDisposition::Above,
4056                        height: 3,
4057                        position: Anchor::min(),
4058                        render: Arc::new(|_| div().into_any()),
4059                    }],
4060                    None,
4061                    cx,
4062                );
4063
4064                // Blur the editor so that it displays placeholder text.
4065                cx.blur();
4066            })
4067            .unwrap();
4068
4069        let mut element = EditorElement::new(&editor, style);
4070        let state = cx
4071            .update_window(window.into(), |_view, cx| {
4072                cx.with_element_context(|cx| {
4073                    element.after_layout(
4074                        Bounds {
4075                            origin: point(px(500.), px(500.)),
4076                            size: size(px(500.), px(500.)),
4077                        },
4078                        &mut (),
4079                        cx,
4080                    )
4081                })
4082            })
4083            .unwrap();
4084
4085        assert_eq!(state.position_map.line_layouts.len(), 4);
4086        assert_eq!(
4087            state
4088                .line_numbers
4089                .iter()
4090                .map(Option::is_some)
4091                .collect::<Vec<_>>(),
4092            &[false, false, false, true]
4093        );
4094    }
4095
4096    #[gpui::test]
4097    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4098        const TAB_SIZE: u32 = 4;
4099
4100        let input_text = "\t \t|\t| a b";
4101        let expected_invisibles = vec![
4102            Invisible::Tab {
4103                line_start_offset: 0,
4104            },
4105            Invisible::Whitespace {
4106                line_offset: TAB_SIZE as usize,
4107            },
4108            Invisible::Tab {
4109                line_start_offset: TAB_SIZE as usize + 1,
4110            },
4111            Invisible::Tab {
4112                line_start_offset: TAB_SIZE as usize * 2 + 1,
4113            },
4114            Invisible::Whitespace {
4115                line_offset: TAB_SIZE as usize * 3 + 1,
4116            },
4117            Invisible::Whitespace {
4118                line_offset: TAB_SIZE as usize * 3 + 3,
4119            },
4120        ];
4121        assert_eq!(
4122            expected_invisibles.len(),
4123            input_text
4124                .chars()
4125                .filter(|initial_char| initial_char.is_whitespace())
4126                .count(),
4127            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4128        );
4129
4130        init_test(cx, |s| {
4131            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4132            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4133        });
4134
4135        let actual_invisibles =
4136            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4137
4138        assert_eq!(expected_invisibles, actual_invisibles);
4139    }
4140
4141    #[gpui::test]
4142    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4143        init_test(cx, |s| {
4144            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4145            s.defaults.tab_size = NonZeroU32::new(4);
4146        });
4147
4148        for editor_mode_without_invisibles in [
4149            EditorMode::SingleLine,
4150            EditorMode::AutoHeight { max_lines: 100 },
4151        ] {
4152            let invisibles = collect_invisibles_from_new_editor(
4153                cx,
4154                editor_mode_without_invisibles,
4155                "\t\t\t| | a b",
4156                px(500.0),
4157            );
4158            assert!(invisibles.is_empty(),
4159                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4160        }
4161    }
4162
4163    #[gpui::test]
4164    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4165        let tab_size = 4;
4166        let input_text = "a\tbcd   ".repeat(9);
4167        let repeated_invisibles = [
4168            Invisible::Tab {
4169                line_start_offset: 1,
4170            },
4171            Invisible::Whitespace {
4172                line_offset: tab_size as usize + 3,
4173            },
4174            Invisible::Whitespace {
4175                line_offset: tab_size as usize + 4,
4176            },
4177            Invisible::Whitespace {
4178                line_offset: tab_size as usize + 5,
4179            },
4180        ];
4181        let expected_invisibles = std::iter::once(repeated_invisibles)
4182            .cycle()
4183            .take(9)
4184            .flatten()
4185            .collect::<Vec<_>>();
4186        assert_eq!(
4187            expected_invisibles.len(),
4188            input_text
4189                .chars()
4190                .filter(|initial_char| initial_char.is_whitespace())
4191                .count(),
4192            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4193        );
4194        info!("Expected invisibles: {expected_invisibles:?}");
4195
4196        init_test(cx, |_| {});
4197
4198        // Put the same string with repeating whitespace pattern into editors of various size,
4199        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4200        let resize_step = 10.0;
4201        let mut editor_width = 200.0;
4202        while editor_width <= 1000.0 {
4203            update_test_language_settings(cx, |s| {
4204                s.defaults.tab_size = NonZeroU32::new(tab_size);
4205                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4206                s.defaults.preferred_line_length = Some(editor_width as u32);
4207                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4208            });
4209
4210            let actual_invisibles = collect_invisibles_from_new_editor(
4211                cx,
4212                EditorMode::Full,
4213                &input_text,
4214                px(editor_width),
4215            );
4216
4217            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4218            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4219            let mut i = 0;
4220            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4221                i = actual_index;
4222                match expected_invisibles.get(i) {
4223                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4224                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4225                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4226                        _ => {
4227                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4228                        }
4229                    },
4230                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4231                }
4232            }
4233            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4234            assert!(
4235                missing_expected_invisibles.is_empty(),
4236                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4237            );
4238
4239            editor_width += resize_step;
4240        }
4241    }
4242
4243    fn collect_invisibles_from_new_editor(
4244        cx: &mut TestAppContext,
4245        editor_mode: EditorMode,
4246        input_text: &str,
4247        editor_width: Pixels,
4248    ) -> Vec<Invisible> {
4249        info!(
4250            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4251            editor_width.0
4252        );
4253        let window = cx.add_window(|cx| {
4254            let buffer = MultiBuffer::build_simple(&input_text, cx);
4255            Editor::new(editor_mode, buffer, None, cx)
4256        });
4257        let editor = window.root(cx).unwrap();
4258        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4259        let mut element = EditorElement::new(&editor, style);
4260        window
4261            .update(cx, |editor, cx| {
4262                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4263                editor.set_wrap_width(Some(editor_width), cx);
4264            })
4265            .unwrap();
4266        let layout_state = cx
4267            .update_window(window.into(), |_, cx| {
4268                cx.with_element_context(|cx| {
4269                    element.after_layout(
4270                        Bounds {
4271                            origin: point(px(500.), px(500.)),
4272                            size: size(px(500.), px(500.)),
4273                        },
4274                        &mut (),
4275                        cx,
4276                    )
4277                })
4278            })
4279            .unwrap();
4280
4281        layout_state
4282            .position_map
4283            .line_layouts
4284            .iter()
4285            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4286            .cloned()
4287            .collect()
4288    }
4289}
4290
4291pub fn register_action<T: Action>(
4292    view: &View<Editor>,
4293    cx: &mut WindowContext,
4294    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4295) {
4296    let view = view.clone();
4297    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4298        let action = action.downcast_ref().unwrap();
4299        if phase == DispatchPhase::Bubble {
4300            view.update(cx, |editor, cx| {
4301                listener(editor, action, cx);
4302            })
4303        }
4304    })
4305}
4306
4307fn compute_auto_height_layout(
4308    editor: &mut Editor,
4309    max_lines: usize,
4310    max_line_number_width: Pixels,
4311    known_dimensions: Size<Option<Pixels>>,
4312    cx: &mut ViewContext<Editor>,
4313) -> Option<Size<Pixels>> {
4314    let width = known_dimensions.width?;
4315    if let Some(height) = known_dimensions.height {
4316        return Some(size(width, height));
4317    }
4318
4319    let style = editor.style.as_ref().unwrap();
4320    let font_id = cx.text_system().resolve_font(&style.text.font());
4321    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4322    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4323    let em_width = cx
4324        .text_system()
4325        .typographic_bounds(font_id, font_size, 'm')
4326        .unwrap()
4327        .size
4328        .width;
4329
4330    let mut snapshot = editor.snapshot(cx);
4331    let gutter_dimensions =
4332        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4333
4334    editor.gutter_width = gutter_dimensions.width;
4335    let text_width = width - gutter_dimensions.width;
4336    let overscroll = size(em_width, px(0.));
4337
4338    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4339    if editor.set_wrap_width(Some(editor_width), cx) {
4340        snapshot = editor.snapshot(cx);
4341    }
4342
4343    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4344    let height = scroll_height
4345        .max(line_height)
4346        .min(line_height * max_lines as f32);
4347
4348    Some(size(width, height))
4349}