element.rs

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