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: ScrollbarLayout::BORDER_WIDTH,
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                let left = scrollbar_layout.hitbox.left();
2177                let right = scrollbar_layout.hitbox.right();
2178                let column_width =
2179                    px(((right - left - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
2180                if is_singleton && scrollbar_settings.selections {
2181                    let start_anchor = Anchor::min();
2182                    let end_anchor = Anchor::max();
2183                    let background_ranges = self
2184                        .editor
2185                        .read(cx)
2186                        .background_highlight_row_ranges::<BufferSearchHighlights>(
2187                            start_anchor..end_anchor,
2188                            &layout.position_map.snapshot,
2189                            50000,
2190                        );
2191                    let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2192                    let right_x = left_x + column_width;
2193                    for range in background_ranges {
2194                        let (start_y, end_y) =
2195                            scrollbar_layout.ys_for_marker(range.start().row(), range.end().row());
2196                        let bounds =
2197                            Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2198                        cx.paint_quad(quad(
2199                            bounds,
2200                            Corners::default(),
2201                            cx.theme().status().info,
2202                            Edges::default(),
2203                            cx.theme().colors().scrollbar_thumb_border,
2204                        ));
2205                    }
2206                }
2207
2208                if is_singleton && scrollbar_settings.symbols_selections {
2209                    let selection_ranges = self.editor.read(cx).background_highlights_in_range(
2210                        Anchor::min()..Anchor::max(),
2211                        &layout.position_map.snapshot,
2212                        cx.theme().colors(),
2213                    );
2214                    let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2215                    let right_x = left_x + column_width;
2216                    for hunk in selection_ranges {
2217                        let start_display = Point::new(hunk.0.start.row(), 0)
2218                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2219                        let end_display = Point::new(hunk.0.end.row(), 0)
2220                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2221                        let (start_y, end_y) =
2222                            scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2223                        let bounds =
2224                            Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2225                        cx.paint_quad(quad(
2226                            bounds,
2227                            Corners::default(),
2228                            cx.theme().status().info,
2229                            Edges::default(),
2230                            cx.theme().colors().scrollbar_thumb_border,
2231                        ));
2232                    }
2233                }
2234
2235                if is_singleton && scrollbar_settings.git_diff {
2236                    let left_x = left + ScrollbarLayout::BORDER_WIDTH;
2237                    let right_x = left_x + column_width;
2238                    for hunk in layout
2239                        .position_map
2240                        .snapshot
2241                        .buffer_snapshot
2242                        .git_diff_hunks_in_range(0..layout.max_row)
2243                    {
2244                        let start_display_row = Point::new(hunk.associated_range.start, 0)
2245                            .to_display_point(&layout.position_map.snapshot.display_snapshot)
2246                            .row();
2247                        let mut end_display_row = Point::new(hunk.associated_range.end, 0)
2248                            .to_display_point(&layout.position_map.snapshot.display_snapshot)
2249                            .row();
2250                        if end_display_row != start_display_row {
2251                            end_display_row -= 1;
2252                        }
2253                        let (start_y, end_y) =
2254                            scrollbar_layout.ys_for_marker(start_display_row, end_display_row);
2255                        let bounds =
2256                            Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2257                        let color = match hunk.status() {
2258                            DiffHunkStatus::Added => cx.theme().status().created,
2259                            DiffHunkStatus::Modified => cx.theme().status().modified,
2260                            DiffHunkStatus::Removed => cx.theme().status().deleted,
2261                        };
2262                        cx.paint_quad(quad(
2263                            bounds,
2264                            Corners::default(),
2265                            color,
2266                            Edges::default(),
2267                            cx.theme().colors().scrollbar_thumb_border,
2268                        ));
2269                    }
2270                }
2271
2272                if is_singleton && scrollbar_settings.diagnostics {
2273                    let max_point = layout
2274                        .position_map
2275                        .snapshot
2276                        .display_snapshot
2277                        .buffer_snapshot
2278                        .max_point();
2279
2280                    let diagnostics = layout
2281                        .position_map
2282                        .snapshot
2283                        .buffer_snapshot
2284                        .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
2285                        // We want to sort by severity, in order to paint the most severe diagnostics last.
2286                        .sorted_by_key(|diagnostic| {
2287                            std::cmp::Reverse(diagnostic.diagnostic.severity)
2288                        });
2289
2290                    let left_x = left + ScrollbarLayout::BORDER_WIDTH + 2.0 * column_width;
2291                    for diagnostic in diagnostics {
2292                        let start_display = diagnostic
2293                            .range
2294                            .start
2295                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2296                        let end_display = diagnostic
2297                            .range
2298                            .end
2299                            .to_display_point(&layout.position_map.snapshot.display_snapshot);
2300                        let (start_y, end_y) =
2301                            scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2302                        let bounds =
2303                            Bounds::from_corners(point(left_x, start_y), point(right, end_y));
2304                        let color = match diagnostic.diagnostic.severity {
2305                            DiagnosticSeverity::ERROR => cx.theme().status().error,
2306                            DiagnosticSeverity::WARNING => cx.theme().status().warning,
2307                            DiagnosticSeverity::INFORMATION => cx.theme().status().info,
2308                            _ => cx.theme().status().hint,
2309                        };
2310                        cx.paint_quad(quad(
2311                            bounds,
2312                            Corners::default(),
2313                            color,
2314                            Edges::default(),
2315                            cx.theme().colors().scrollbar_thumb_border,
2316                        ));
2317                    }
2318                }
2319
2320                cx.paint_quad(quad(
2321                    thumb_bounds,
2322                    Corners::default(),
2323                    cx.theme().colors().scrollbar_thumb_background,
2324                    Edges {
2325                        top: Pixels::ZERO,
2326                        right: Pixels::ZERO,
2327                        bottom: Pixels::ZERO,
2328                        left: ScrollbarLayout::BORDER_WIDTH,
2329                    },
2330                    cx.theme().colors().scrollbar_thumb_border,
2331                ));
2332            });
2333        }
2334
2335        cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2336
2337        let scroll_height = scrollbar_layout.scroll_height;
2338        let height = scrollbar_layout.height;
2339        let row_range = scrollbar_layout.visible_row_range.clone();
2340
2341        cx.on_mouse_event({
2342            let editor = self.editor.clone();
2343            let hitbox = scrollbar_layout.hitbox.clone();
2344            let mut mouse_position = cx.mouse_position();
2345            move |event: &MouseMoveEvent, phase, cx| {
2346                if phase == DispatchPhase::Capture {
2347                    return;
2348                }
2349
2350                editor.update(cx, |editor, cx| {
2351                    if event.pressed_button == Some(MouseButton::Left)
2352                        && editor.scroll_manager.is_dragging_scrollbar()
2353                    {
2354                        let y = mouse_position.y;
2355                        let new_y = event.position.y;
2356                        if (hitbox.top()..hitbox.bottom()).contains(&y) {
2357                            let mut position = editor.scroll_position(cx);
2358                            position.y += (new_y - y) * scroll_height / height;
2359                            if position.y < 0.0 {
2360                                position.y = 0.0;
2361                            }
2362                            editor.set_scroll_position(position, cx);
2363                        }
2364
2365                        mouse_position = event.position;
2366                        cx.stop_propagation();
2367                    } else {
2368                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2369                        if hitbox.is_hovered(cx) {
2370                            editor.scroll_manager.show_scrollbar(cx);
2371                        }
2372                    }
2373                })
2374            }
2375        });
2376
2377        if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2378            cx.on_mouse_event({
2379                let editor = self.editor.clone();
2380                move |_: &MouseUpEvent, phase, cx| {
2381                    if phase == DispatchPhase::Capture {
2382                        return;
2383                    }
2384
2385                    editor.update(cx, |editor, cx| {
2386                        editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2387                        cx.stop_propagation();
2388                    });
2389                }
2390            });
2391        } else {
2392            cx.on_mouse_event({
2393                let editor = self.editor.clone();
2394                let hitbox = scrollbar_layout.hitbox.clone();
2395                move |event: &MouseDownEvent, phase, cx| {
2396                    if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2397                        return;
2398                    }
2399
2400                    editor.update(cx, |editor, cx| {
2401                        editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2402
2403                        let y = event.position.y;
2404                        if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2405                            let center_row =
2406                                ((y - hitbox.top()) * scroll_height / height).round() as u32;
2407                            let top_row = center_row
2408                                .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2409                            let mut position = editor.scroll_position(cx);
2410                            position.y = top_row as f32;
2411                            editor.set_scroll_position(position, cx);
2412                        } else {
2413                            editor.scroll_manager.show_scrollbar(cx);
2414                        }
2415
2416                        cx.stop_propagation();
2417                    });
2418                }
2419            });
2420        }
2421    }
2422
2423    #[allow(clippy::too_many_arguments)]
2424    fn paint_highlighted_range(
2425        &self,
2426        range: Range<DisplayPoint>,
2427        color: Hsla,
2428        corner_radius: Pixels,
2429        line_end_overshoot: Pixels,
2430        layout: &EditorLayout,
2431        cx: &mut ElementContext,
2432    ) {
2433        let start_row = layout.visible_display_row_range.start;
2434        let end_row = layout.visible_display_row_range.end;
2435        if range.start != range.end {
2436            let row_range = if range.end.column() == 0 {
2437                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2438            } else {
2439                cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2440            };
2441
2442            let highlighted_range = HighlightedRange {
2443                color,
2444                line_height: layout.position_map.line_height,
2445                corner_radius,
2446                start_y: layout.content_origin.y
2447                    + row_range.start as f32 * layout.position_map.line_height
2448                    - layout.position_map.scroll_pixel_position.y,
2449                lines: row_range
2450                    .into_iter()
2451                    .map(|row| {
2452                        let line_layout =
2453                            &layout.position_map.line_layouts[(row - start_row) as usize].line;
2454                        HighlightedRangeLine {
2455                            start_x: if row == range.start.row() {
2456                                layout.content_origin.x
2457                                    + line_layout.x_for_index(range.start.column() as usize)
2458                                    - layout.position_map.scroll_pixel_position.x
2459                            } else {
2460                                layout.content_origin.x
2461                                    - layout.position_map.scroll_pixel_position.x
2462                            },
2463                            end_x: if row == range.end.row() {
2464                                layout.content_origin.x
2465                                    + line_layout.x_for_index(range.end.column() as usize)
2466                                    - layout.position_map.scroll_pixel_position.x
2467                            } else {
2468                                layout.content_origin.x + line_layout.width + line_end_overshoot
2469                                    - layout.position_map.scroll_pixel_position.x
2470                            },
2471                        }
2472                    })
2473                    .collect(),
2474            };
2475
2476            highlighted_range.paint(layout.text_hitbox.bounds, cx);
2477        }
2478    }
2479
2480    fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2481        if layout.folds.is_empty() {
2482            return;
2483        }
2484
2485        cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2486            let fold_corner_radius = 0.15 * layout.position_map.line_height;
2487            for mut fold in mem::take(&mut layout.folds) {
2488                fold.hover_element.paint(cx);
2489
2490                let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2491                let fold_background = if hover_element.interactivity().active.unwrap() {
2492                    cx.theme().colors().ghost_element_active
2493                } else if hover_element.interactivity().hovered.unwrap() {
2494                    cx.theme().colors().ghost_element_hover
2495                } else {
2496                    cx.theme().colors().ghost_element_background
2497                };
2498
2499                self.paint_highlighted_range(
2500                    fold.display_range.clone(),
2501                    fold_background,
2502                    fold_corner_radius,
2503                    fold_corner_radius * 2.,
2504                    layout,
2505                    cx,
2506                );
2507            }
2508        })
2509    }
2510
2511    fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2512        for mut block in layout.blocks.drain(..) {
2513            block.element.paint(cx);
2514        }
2515    }
2516
2517    fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2518        if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2519            mouse_context_menu.paint(cx);
2520        }
2521    }
2522
2523    fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2524        cx.on_mouse_event({
2525            let position_map = layout.position_map.clone();
2526            let editor = self.editor.clone();
2527            let hitbox = layout.hitbox.clone();
2528            let mut delta = ScrollDelta::default();
2529
2530            move |event: &ScrollWheelEvent, phase, cx| {
2531                if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2532                    delta = delta.coalesce(event.delta);
2533                    editor.update(cx, |editor, cx| {
2534                        let position_map: &PositionMap = &position_map;
2535
2536                        let line_height = position_map.line_height;
2537                        let max_glyph_width = position_map.em_width;
2538                        let (delta, axis) = match delta {
2539                            gpui::ScrollDelta::Pixels(mut pixels) => {
2540                                //Trackpad
2541                                let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2542                                (pixels, axis)
2543                            }
2544
2545                            gpui::ScrollDelta::Lines(lines) => {
2546                                //Not trackpad
2547                                let pixels =
2548                                    point(lines.x * max_glyph_width, lines.y * line_height);
2549                                (pixels, None)
2550                            }
2551                        };
2552
2553                        let scroll_position = position_map.snapshot.scroll_position();
2554                        let x = (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width;
2555                        let y = (scroll_position.y * line_height - delta.y) / line_height;
2556                        let scroll_position =
2557                            point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2558                        editor.scroll(scroll_position, axis, cx);
2559                        cx.stop_propagation();
2560                    });
2561                }
2562            }
2563        });
2564    }
2565
2566    fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2567        self.paint_scroll_wheel_listener(layout, cx);
2568
2569        cx.on_mouse_event({
2570            let position_map = layout.position_map.clone();
2571            let editor = self.editor.clone();
2572            let text_hitbox = layout.text_hitbox.clone();
2573            let gutter_hitbox = layout.gutter_hitbox.clone();
2574
2575            move |event: &MouseDownEvent, phase, cx| {
2576                if phase == DispatchPhase::Bubble {
2577                    match event.button {
2578                        MouseButton::Left => editor.update(cx, |editor, cx| {
2579                            Self::mouse_left_down(
2580                                editor,
2581                                event,
2582                                &position_map,
2583                                &text_hitbox,
2584                                &gutter_hitbox,
2585                                cx,
2586                            );
2587                        }),
2588                        MouseButton::Right => editor.update(cx, |editor, cx| {
2589                            Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2590                        }),
2591                        _ => {}
2592                    };
2593                }
2594            }
2595        });
2596
2597        cx.on_mouse_event({
2598            let editor = self.editor.clone();
2599            let position_map = layout.position_map.clone();
2600            let text_hitbox = layout.text_hitbox.clone();
2601
2602            move |event: &MouseUpEvent, phase, cx| {
2603                if phase == DispatchPhase::Bubble {
2604                    editor.update(cx, |editor, cx| {
2605                        Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2606                    });
2607                }
2608            }
2609        });
2610        cx.on_mouse_event({
2611            let position_map = layout.position_map.clone();
2612            let editor = self.editor.clone();
2613            let text_hitbox = layout.text_hitbox.clone();
2614            let gutter_hitbox = layout.gutter_hitbox.clone();
2615
2616            move |event: &MouseMoveEvent, phase, cx| {
2617                if phase == DispatchPhase::Bubble {
2618                    editor.update(cx, |editor, cx| {
2619                        if event.pressed_button == Some(MouseButton::Left) {
2620                            Self::mouse_dragged(
2621                                editor,
2622                                event,
2623                                &position_map,
2624                                text_hitbox.bounds,
2625                                cx,
2626                            )
2627                        }
2628
2629                        Self::mouse_moved(
2630                            editor,
2631                            event,
2632                            &position_map,
2633                            &text_hitbox,
2634                            &gutter_hitbox,
2635                            cx,
2636                        )
2637                    });
2638                }
2639            }
2640        });
2641    }
2642
2643    fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2644        bounds.upper_right().x - self.style.scrollbar_width
2645    }
2646
2647    fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2648        let style = &self.style;
2649        let font_size = style.text.font_size.to_pixels(cx.rem_size());
2650        let layout = cx
2651            .text_system()
2652            .shape_line(
2653                SharedString::from(" ".repeat(column)),
2654                font_size,
2655                &[TextRun {
2656                    len: column,
2657                    font: style.text.font(),
2658                    color: Hsla::default(),
2659                    background_color: None,
2660                    underline: None,
2661                    strikethrough: None,
2662                }],
2663            )
2664            .unwrap();
2665
2666        layout.width
2667    }
2668
2669    fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2670        let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2671        self.column_pixels(digit_count, cx)
2672    }
2673}
2674
2675#[derive(Debug)]
2676pub(crate) struct LineWithInvisibles {
2677    pub line: ShapedLine,
2678    invisibles: Vec<Invisible>,
2679}
2680
2681impl LineWithInvisibles {
2682    fn from_chunks<'a>(
2683        chunks: impl Iterator<Item = HighlightedChunk<'a>>,
2684        text_style: &TextStyle,
2685        max_line_len: usize,
2686        max_line_count: usize,
2687        line_number_layouts: &[Option<ShapedLine>],
2688        editor_mode: EditorMode,
2689        cx: &WindowContext,
2690    ) -> Vec<Self> {
2691        let mut layouts = Vec::with_capacity(max_line_count);
2692        let mut line = String::new();
2693        let mut invisibles = Vec::new();
2694        let mut styles = Vec::new();
2695        let mut non_whitespace_added = false;
2696        let mut row = 0;
2697        let mut line_exceeded_max_len = false;
2698        let font_size = text_style.font_size.to_pixels(cx.rem_size());
2699
2700        for highlighted_chunk in chunks.chain([HighlightedChunk {
2701            chunk: "\n",
2702            style: None,
2703            is_tab: false,
2704        }]) {
2705            for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
2706                if ix > 0 {
2707                    let shaped_line = cx
2708                        .text_system()
2709                        .shape_line(line.clone().into(), font_size, &styles)
2710                        .unwrap();
2711                    layouts.push(Self {
2712                        line: shaped_line,
2713                        invisibles: std::mem::take(&mut invisibles),
2714                    });
2715
2716                    line.clear();
2717                    styles.clear();
2718                    row += 1;
2719                    line_exceeded_max_len = false;
2720                    non_whitespace_added = false;
2721                    if row == max_line_count {
2722                        return layouts;
2723                    }
2724                }
2725
2726                if !line_chunk.is_empty() && !line_exceeded_max_len {
2727                    let text_style = if let Some(style) = highlighted_chunk.style {
2728                        Cow::Owned(text_style.clone().highlight(style))
2729                    } else {
2730                        Cow::Borrowed(text_style)
2731                    };
2732
2733                    if line.len() + line_chunk.len() > max_line_len {
2734                        let mut chunk_len = max_line_len - line.len();
2735                        while !line_chunk.is_char_boundary(chunk_len) {
2736                            chunk_len -= 1;
2737                        }
2738                        line_chunk = &line_chunk[..chunk_len];
2739                        line_exceeded_max_len = true;
2740                    }
2741
2742                    styles.push(TextRun {
2743                        len: line_chunk.len(),
2744                        font: text_style.font(),
2745                        color: text_style.color,
2746                        background_color: text_style.background_color,
2747                        underline: text_style.underline,
2748                        strikethrough: text_style.strikethrough,
2749                    });
2750
2751                    if editor_mode == EditorMode::Full {
2752                        // Line wrap pads its contents with fake whitespaces,
2753                        // avoid printing them
2754                        let inside_wrapped_string = line_number_layouts
2755                            .get(row)
2756                            .and_then(|layout| layout.as_ref())
2757                            .is_none();
2758                        if highlighted_chunk.is_tab {
2759                            if non_whitespace_added || !inside_wrapped_string {
2760                                invisibles.push(Invisible::Tab {
2761                                    line_start_offset: line.len(),
2762                                });
2763                            }
2764                        } else {
2765                            invisibles.extend(
2766                                line_chunk
2767                                    .chars()
2768                                    .enumerate()
2769                                    .filter(|(_, line_char)| {
2770                                        let is_whitespace = line_char.is_whitespace();
2771                                        non_whitespace_added |= !is_whitespace;
2772                                        is_whitespace
2773                                            && (non_whitespace_added || !inside_wrapped_string)
2774                                    })
2775                                    .map(|(whitespace_index, _)| Invisible::Whitespace {
2776                                        line_offset: line.len() + whitespace_index,
2777                                    }),
2778                            )
2779                        }
2780                    }
2781
2782                    line.push_str(line_chunk);
2783                }
2784            }
2785        }
2786
2787        layouts
2788    }
2789
2790    fn draw(
2791        &self,
2792        layout: &EditorLayout,
2793        row: u32,
2794        content_origin: gpui::Point<Pixels>,
2795        whitespace_setting: ShowWhitespaceSetting,
2796        selection_ranges: &[Range<DisplayPoint>],
2797        cx: &mut ElementContext,
2798    ) {
2799        let line_height = layout.position_map.line_height;
2800        let line_y =
2801            line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
2802
2803        self.line
2804            .paint(
2805                content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y),
2806                line_height,
2807                cx,
2808            )
2809            .log_err();
2810
2811        self.draw_invisibles(
2812            &selection_ranges,
2813            layout,
2814            content_origin,
2815            line_y,
2816            row,
2817            line_height,
2818            whitespace_setting,
2819            cx,
2820        );
2821    }
2822
2823    #[allow(clippy::too_many_arguments)]
2824    fn draw_invisibles(
2825        &self,
2826        selection_ranges: &[Range<DisplayPoint>],
2827        layout: &EditorLayout,
2828        content_origin: gpui::Point<Pixels>,
2829        line_y: Pixels,
2830        row: u32,
2831        line_height: Pixels,
2832        whitespace_setting: ShowWhitespaceSetting,
2833        cx: &mut ElementContext,
2834    ) {
2835        let allowed_invisibles_regions = match whitespace_setting {
2836            ShowWhitespaceSetting::None => return,
2837            ShowWhitespaceSetting::Selection => Some(selection_ranges),
2838            ShowWhitespaceSetting::All => None,
2839        };
2840
2841        for invisible in &self.invisibles {
2842            let (&token_offset, invisible_symbol) = match invisible {
2843                Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
2844                Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
2845            };
2846
2847            let x_offset = self.line.x_for_index(token_offset);
2848            let invisible_offset =
2849                (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
2850            let origin = content_origin
2851                + gpui::point(
2852                    x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
2853                    line_y,
2854                );
2855
2856            if let Some(allowed_regions) = allowed_invisibles_regions {
2857                let invisible_point = DisplayPoint::new(row, token_offset as u32);
2858                if !allowed_regions
2859                    .iter()
2860                    .any(|region| region.start <= invisible_point && invisible_point < region.end)
2861                {
2862                    continue;
2863                }
2864            }
2865            invisible_symbol.paint(origin, line_height, cx).log_err();
2866        }
2867    }
2868}
2869
2870#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2871enum Invisible {
2872    Tab { line_start_offset: usize },
2873    Whitespace { line_offset: usize },
2874}
2875
2876impl Element for EditorElement {
2877    type BeforeLayout = ();
2878    type AfterLayout = EditorLayout;
2879
2880    fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
2881        self.editor.update(cx, |editor, cx| {
2882            editor.set_style(self.style.clone(), cx);
2883
2884            let layout_id = match editor.mode {
2885                EditorMode::SingleLine => {
2886                    let rem_size = cx.rem_size();
2887                    let mut style = Style::default();
2888                    style.size.width = relative(1.).into();
2889                    style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
2890                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2891                }
2892                EditorMode::AutoHeight { max_lines } => {
2893                    let editor_handle = cx.view().clone();
2894                    let max_line_number_width =
2895                        self.max_line_number_width(&editor.snapshot(cx), cx);
2896                    cx.with_element_context(|cx| {
2897                        cx.request_measured_layout(
2898                            Style::default(),
2899                            move |known_dimensions, _, cx| {
2900                                editor_handle
2901                                    .update(cx, |editor, cx| {
2902                                        compute_auto_height_layout(
2903                                            editor,
2904                                            max_lines,
2905                                            max_line_number_width,
2906                                            known_dimensions,
2907                                            cx,
2908                                        )
2909                                    })
2910                                    .unwrap_or_default()
2911                            },
2912                        )
2913                    })
2914                }
2915                EditorMode::Full => {
2916                    let mut style = Style::default();
2917                    style.size.width = relative(1.).into();
2918                    style.size.height = relative(1.).into();
2919                    cx.with_element_context(|cx| cx.request_layout(&style, None))
2920                }
2921            };
2922
2923            (layout_id, ())
2924        })
2925    }
2926
2927    fn after_layout(
2928        &mut self,
2929        bounds: Bounds<Pixels>,
2930        _: &mut Self::BeforeLayout,
2931        cx: &mut ElementContext,
2932    ) -> Self::AfterLayout {
2933        let text_style = TextStyleRefinement {
2934            font_size: Some(self.style.text.font_size),
2935            line_height: Some(self.style.text.line_height),
2936            ..Default::default()
2937        };
2938        cx.with_text_style(Some(text_style), |cx| {
2939            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
2940                let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
2941                let style = self.style.clone();
2942
2943                let font_id = cx.text_system().resolve_font(&style.text.font());
2944                let font_size = style.text.font_size.to_pixels(cx.rem_size());
2945                let line_height = style.text.line_height_in_pixels(cx.rem_size());
2946                let em_width = cx
2947                    .text_system()
2948                    .typographic_bounds(font_id, font_size, 'm')
2949                    .unwrap()
2950                    .size
2951                    .width;
2952                let em_advance = cx
2953                    .text_system()
2954                    .advance(font_id, font_size, 'm')
2955                    .unwrap()
2956                    .width;
2957
2958                let gutter_dimensions = snapshot.gutter_dimensions(
2959                    font_id,
2960                    font_size,
2961                    em_width,
2962                    self.max_line_number_width(&snapshot, cx),
2963                    cx,
2964                );
2965                let text_width = bounds.size.width - gutter_dimensions.width;
2966                let overscroll = size(em_width, px(0.));
2967
2968                snapshot = self.editor.update(cx, |editor, cx| {
2969                    editor.gutter_width = gutter_dimensions.width;
2970                    editor.set_visible_line_count(bounds.size.height / line_height, cx);
2971
2972                    let editor_width =
2973                        text_width - gutter_dimensions.margin - overscroll.width - em_width;
2974                    let wrap_width = match editor.soft_wrap_mode(cx) {
2975                        SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
2976                        SoftWrap::EditorWidth => editor_width,
2977                        SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
2978                    };
2979
2980                    if editor.set_wrap_width(Some(wrap_width), cx) {
2981                        editor.snapshot(cx)
2982                    } else {
2983                        snapshot
2984                    }
2985                });
2986
2987                let wrap_guides = self
2988                    .editor
2989                    .read(cx)
2990                    .wrap_guides(cx)
2991                    .iter()
2992                    .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
2993                    .collect::<SmallVec<[_; 2]>>();
2994
2995                let hitbox = cx.insert_hitbox(bounds, false);
2996                let gutter_hitbox = cx.insert_hitbox(
2997                    Bounds {
2998                        origin: bounds.origin,
2999                        size: size(gutter_dimensions.width, bounds.size.height),
3000                    },
3001                    false,
3002                );
3003                let text_hitbox = cx.insert_hitbox(
3004                    Bounds {
3005                        origin: gutter_hitbox.upper_right(),
3006                        size: size(text_width, bounds.size.height),
3007                    },
3008                    false,
3009                );
3010                // Offset the content_bounds from the text_bounds by the gutter margin (which
3011                // is roughly half a character wide) to make hit testing work more like how we want.
3012                let content_origin =
3013                    text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3014
3015                let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3016                    let autoscroll_horizontally =
3017                        editor.autoscroll_vertically(bounds.size.height, line_height, cx);
3018                    snapshot = editor.snapshot(cx);
3019                    autoscroll_horizontally
3020                });
3021
3022                let mut scroll_position = snapshot.scroll_position();
3023                // The scroll position is a fractional point, the whole number of which represents
3024                // the top of the window in terms of display rows.
3025                let start_row = scroll_position.y as u32;
3026                let height_in_lines = bounds.size.height / line_height;
3027                let max_row = snapshot.max_point().row();
3028
3029                // Add 1 to ensure selections bleed off screen
3030                let end_row =
3031                    1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3032
3033                let start_anchor = if start_row == 0 {
3034                    Anchor::min()
3035                } else {
3036                    snapshot.buffer_snapshot.anchor_before(
3037                        DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3038                    )
3039                };
3040                let end_anchor = if end_row > max_row {
3041                    Anchor::max()
3042                } else {
3043                    snapshot.buffer_snapshot.anchor_before(
3044                        DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3045                    )
3046                };
3047
3048                let highlighted_rows = self
3049                    .editor
3050                    .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3051                let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3052                    start_anchor..end_anchor,
3053                    &snapshot.display_snapshot,
3054                    cx.theme().colors(),
3055                );
3056
3057                let redacted_ranges = self.editor.read(cx).redacted_ranges(
3058                    start_anchor..end_anchor,
3059                    &snapshot.display_snapshot,
3060                    cx,
3061                );
3062
3063                let (selections, active_rows, newest_selection_head) = self.layout_selections(
3064                    start_anchor,
3065                    end_anchor,
3066                    &snapshot,
3067                    start_row,
3068                    end_row,
3069                    cx,
3070                );
3071
3072                let (line_numbers, fold_statuses) = self.layout_line_numbers(
3073                    start_row..end_row,
3074                    &active_rows,
3075                    newest_selection_head,
3076                    &snapshot,
3077                    cx,
3078                );
3079
3080                let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3081
3082                let mut max_visible_line_width = Pixels::ZERO;
3083                let line_layouts =
3084                    self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3085                for line_with_invisibles in &line_layouts {
3086                    if line_with_invisibles.line.width > max_visible_line_width {
3087                        max_visible_line_width = line_with_invisibles.line.width;
3088                    }
3089                }
3090
3091                let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3092                    .unwrap()
3093                    .width;
3094                let mut scroll_width =
3095                    longest_line_width.max(max_visible_line_width) + overscroll.width;
3096                let mut blocks = self.build_blocks(
3097                    start_row..end_row,
3098                    &snapshot,
3099                    &hitbox,
3100                    &text_hitbox,
3101                    &mut scroll_width,
3102                    &gutter_dimensions,
3103                    em_width,
3104                    gutter_dimensions.width + gutter_dimensions.margin,
3105                    line_height,
3106                    &line_layouts,
3107                    cx,
3108                );
3109
3110                let scroll_max = point(
3111                    ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3112                    max_row as f32,
3113                );
3114
3115                self.editor.update(cx, |editor, cx| {
3116                    let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3117
3118                    let autoscrolled = if autoscroll_horizontally {
3119                        editor.autoscroll_horizontally(
3120                            start_row,
3121                            text_hitbox.size.width,
3122                            scroll_width,
3123                            em_width,
3124                            &line_layouts,
3125                            cx,
3126                        )
3127                    } else {
3128                        false
3129                    };
3130
3131                    if clamped || autoscrolled {
3132                        snapshot = editor.snapshot(cx);
3133                        scroll_position = snapshot.scroll_position();
3134                    }
3135                });
3136
3137                let scroll_pixel_position = point(
3138                    scroll_position.x * em_width,
3139                    scroll_position.y * line_height,
3140                );
3141
3142                cx.with_element_id(Some("blocks"), |cx| {
3143                    self.layout_blocks(
3144                        &mut blocks,
3145                        &hitbox,
3146                        line_height,
3147                        scroll_pixel_position,
3148                        cx,
3149                    );
3150                });
3151
3152                let cursors = self.layout_cursors(
3153                    &snapshot,
3154                    &selections,
3155                    start_row..end_row,
3156                    &line_layouts,
3157                    &text_hitbox,
3158                    content_origin,
3159                    scroll_pixel_position,
3160                    line_height,
3161                    em_width,
3162                    cx,
3163                );
3164
3165                let scrollbar_layout = self.layout_scrollbar(
3166                    &snapshot,
3167                    bounds,
3168                    scroll_position,
3169                    line_height,
3170                    height_in_lines,
3171                    cx,
3172                );
3173
3174                let folds = cx.with_element_id(Some("folds"), |cx| {
3175                    self.layout_folds(
3176                        &snapshot,
3177                        content_origin,
3178                        start_anchor..end_anchor,
3179                        start_row..end_row,
3180                        scroll_pixel_position,
3181                        line_height,
3182                        &line_layouts,
3183                        cx,
3184                    )
3185                });
3186
3187                let gutter_settings = EditorSettings::get_global(cx).gutter;
3188
3189                let mut context_menu_visible = false;
3190                let mut code_actions_indicator = None;
3191                if let Some(newest_selection_head) = newest_selection_head {
3192                    if (start_row..end_row).contains(&newest_selection_head.row()) {
3193                        context_menu_visible = self.layout_context_menu(
3194                            line_height,
3195                            &hitbox,
3196                            &text_hitbox,
3197                            content_origin,
3198                            start_row,
3199                            scroll_pixel_position,
3200                            &line_layouts,
3201                            newest_selection_head,
3202                            cx,
3203                        );
3204                        if gutter_settings.code_actions {
3205                            code_actions_indicator = self.layout_code_actions_indicator(
3206                                line_height,
3207                                newest_selection_head,
3208                                scroll_pixel_position,
3209                                &gutter_dimensions,
3210                                &gutter_hitbox,
3211                                cx,
3212                            );
3213                        }
3214                    }
3215                }
3216
3217                if !context_menu_visible && !cx.has_active_drag() {
3218                    self.layout_hover_popovers(
3219                        &snapshot,
3220                        &hitbox,
3221                        &text_hitbox,
3222                        start_row..end_row,
3223                        content_origin,
3224                        scroll_pixel_position,
3225                        &line_layouts,
3226                        line_height,
3227                        em_width,
3228                        cx,
3229                    );
3230                }
3231
3232                let mouse_context_menu = self.layout_mouse_context_menu(cx);
3233
3234                let fold_indicators = if gutter_settings.folds {
3235                    cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3236                        self.layout_gutter_fold_indicators(
3237                            fold_statuses,
3238                            line_height,
3239                            &gutter_dimensions,
3240                            gutter_settings,
3241                            scroll_pixel_position,
3242                            &gutter_hitbox,
3243                            cx,
3244                        )
3245                    })
3246                } else {
3247                    Vec::new()
3248                };
3249
3250                let invisible_symbol_font_size = font_size / 2.;
3251                let tab_invisible = cx
3252                    .text_system()
3253                    .shape_line(
3254                        "".into(),
3255                        invisible_symbol_font_size,
3256                        &[TextRun {
3257                            len: "".len(),
3258                            font: self.style.text.font(),
3259                            color: cx.theme().colors().editor_invisible,
3260                            background_color: None,
3261                            underline: None,
3262                            strikethrough: None,
3263                        }],
3264                    )
3265                    .unwrap();
3266                let space_invisible = cx
3267                    .text_system()
3268                    .shape_line(
3269                        "".into(),
3270                        invisible_symbol_font_size,
3271                        &[TextRun {
3272                            len: "".len(),
3273                            font: self.style.text.font(),
3274                            color: cx.theme().colors().editor_invisible,
3275                            background_color: None,
3276                            underline: None,
3277                            strikethrough: None,
3278                        }],
3279                    )
3280                    .unwrap();
3281
3282                EditorLayout {
3283                    mode: snapshot.mode,
3284                    position_map: Arc::new(PositionMap {
3285                        size: bounds.size,
3286                        scroll_pixel_position,
3287                        scroll_max,
3288                        line_layouts,
3289                        line_height,
3290                        em_width,
3291                        em_advance,
3292                        snapshot,
3293                    }),
3294                    visible_display_row_range: start_row..end_row,
3295                    wrap_guides,
3296                    hitbox,
3297                    text_hitbox,
3298                    gutter_hitbox,
3299                    gutter_dimensions,
3300                    content_origin,
3301                    scrollbar_layout,
3302                    max_row,
3303                    active_rows,
3304                    highlighted_rows,
3305                    highlighted_ranges,
3306                    redacted_ranges,
3307                    line_numbers,
3308                    display_hunks,
3309                    folds,
3310                    blocks,
3311                    cursors,
3312                    selections,
3313                    mouse_context_menu,
3314                    code_actions_indicator,
3315                    fold_indicators,
3316                    tab_invisible,
3317                    space_invisible,
3318                }
3319            })
3320        })
3321    }
3322
3323    fn paint(
3324        &mut self,
3325        bounds: Bounds<gpui::Pixels>,
3326        _: &mut Self::BeforeLayout,
3327        layout: &mut Self::AfterLayout,
3328        cx: &mut ElementContext,
3329    ) {
3330        let focus_handle = self.editor.focus_handle(cx);
3331        let key_context = self.editor.read(cx).key_context(cx);
3332        cx.set_focus_handle(&focus_handle);
3333        cx.set_key_context(key_context);
3334        cx.set_view_id(self.editor.entity_id());
3335        cx.handle_input(
3336            &focus_handle,
3337            ElementInputHandler::new(bounds, self.editor.clone()),
3338        );
3339        self.register_actions(cx);
3340        self.register_key_listeners(cx, layout);
3341
3342        let text_style = TextStyleRefinement {
3343            font_size: Some(self.style.text.font_size),
3344            line_height: Some(self.style.text.line_height),
3345            ..Default::default()
3346        };
3347        cx.with_text_style(Some(text_style), |cx| {
3348            cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3349                self.paint_mouse_listeners(layout, cx);
3350
3351                self.paint_background(layout, cx);
3352                if layout.gutter_hitbox.size.width > Pixels::ZERO {
3353                    self.paint_gutter(layout, cx);
3354                }
3355                self.paint_text(layout, cx);
3356
3357                if !layout.blocks.is_empty() {
3358                    cx.with_element_id(Some("blocks"), |cx| {
3359                        self.paint_blocks(layout, cx);
3360                    });
3361                }
3362
3363                self.paint_scrollbar(layout, cx);
3364                self.paint_mouse_context_menu(layout, cx);
3365            });
3366        })
3367    }
3368}
3369
3370impl IntoElement for EditorElement {
3371    type Element = Self;
3372
3373    fn into_element(self) -> Self::Element {
3374        self
3375    }
3376}
3377
3378type BufferRow = u32;
3379
3380pub struct EditorLayout {
3381    position_map: Arc<PositionMap>,
3382    hitbox: Hitbox,
3383    text_hitbox: Hitbox,
3384    gutter_hitbox: Hitbox,
3385    gutter_dimensions: GutterDimensions,
3386    content_origin: gpui::Point<Pixels>,
3387    scrollbar_layout: Option<ScrollbarLayout>,
3388    mode: EditorMode,
3389    wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3390    visible_display_row_range: Range<u32>,
3391    active_rows: BTreeMap<u32, bool>,
3392    highlighted_rows: BTreeMap<u32, Hsla>,
3393    line_numbers: Vec<Option<ShapedLine>>,
3394    display_hunks: Vec<DisplayDiffHunk>,
3395    folds: Vec<FoldLayout>,
3396    blocks: Vec<BlockLayout>,
3397    highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3398    redacted_ranges: Vec<Range<DisplayPoint>>,
3399    cursors: Vec<CursorLayout>,
3400    selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3401    max_row: u32,
3402    code_actions_indicator: Option<AnyElement>,
3403    fold_indicators: Vec<Option<AnyElement>>,
3404    mouse_context_menu: Option<AnyElement>,
3405    tab_invisible: ShapedLine,
3406    space_invisible: ShapedLine,
3407}
3408
3409impl EditorLayout {
3410    fn line_end_overshoot(&self) -> Pixels {
3411        0.15 * self.position_map.line_height
3412    }
3413}
3414
3415struct ScrollbarLayout {
3416    hitbox: Hitbox,
3417    visible_row_range: Range<f32>,
3418    visible: bool,
3419    height: Pixels,
3420    scroll_height: f32,
3421    first_row_y_offset: Pixels,
3422    row_height: Pixels,
3423}
3424
3425impl ScrollbarLayout {
3426    const BORDER_WIDTH: Pixels = px(1.0);
3427    const MIN_MARKER_HEIGHT: Pixels = px(2.0);
3428
3429    fn thumb_bounds(&self) -> Bounds<Pixels> {
3430        let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
3431        let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
3432        Bounds::from_corners(
3433            point(self.hitbox.left(), thumb_top),
3434            point(self.hitbox.right(), thumb_bottom),
3435        )
3436    }
3437
3438    fn y_for_row(&self, row: f32) -> Pixels {
3439        self.hitbox.top() + self.first_row_y_offset + row * self.row_height
3440    }
3441
3442    fn ys_for_marker(&self, start_row: u32, end_row: u32) -> (Pixels, Pixels) {
3443        let start_y = self.y_for_row(start_row as f32);
3444        let mut end_y = self.y_for_row((end_row + 1) as f32);
3445        if end_y - start_y < Self::MIN_MARKER_HEIGHT {
3446            end_y = start_y + Self::MIN_MARKER_HEIGHT;
3447        }
3448        (start_y, end_y)
3449    }
3450}
3451
3452struct FoldLayout {
3453    display_range: Range<DisplayPoint>,
3454    hover_element: AnyElement,
3455}
3456
3457struct PositionMap {
3458    size: Size<Pixels>,
3459    line_height: Pixels,
3460    scroll_pixel_position: gpui::Point<Pixels>,
3461    scroll_max: gpui::Point<f32>,
3462    em_width: Pixels,
3463    em_advance: Pixels,
3464    line_layouts: Vec<LineWithInvisibles>,
3465    snapshot: EditorSnapshot,
3466}
3467
3468#[derive(Debug, Copy, Clone)]
3469pub struct PointForPosition {
3470    pub previous_valid: DisplayPoint,
3471    pub next_valid: DisplayPoint,
3472    pub exact_unclipped: DisplayPoint,
3473    pub column_overshoot_after_line_end: u32,
3474}
3475
3476impl PointForPosition {
3477    pub fn as_valid(&self) -> Option<DisplayPoint> {
3478        if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3479            Some(self.previous_valid)
3480        } else {
3481            None
3482        }
3483    }
3484}
3485
3486impl PositionMap {
3487    fn point_for_position(
3488        &self,
3489        text_bounds: Bounds<Pixels>,
3490        position: gpui::Point<Pixels>,
3491    ) -> PointForPosition {
3492        let scroll_position = self.snapshot.scroll_position();
3493        let position = position - text_bounds.origin;
3494        let y = position.y.max(px(0.)).min(self.size.height);
3495        let x = position.x + (scroll_position.x * self.em_width);
3496        let row = ((y / self.line_height) + scroll_position.y) as u32;
3497
3498        let (column, x_overshoot_after_line_end) = if let Some(line) = self
3499            .line_layouts
3500            .get(row as usize - scroll_position.y as usize)
3501            .map(|LineWithInvisibles { line, .. }| line)
3502        {
3503            if let Some(ix) = line.index_for_x(x) {
3504                (ix as u32, px(0.))
3505            } else {
3506                (line.len as u32, px(0.).max(x - line.width))
3507            }
3508        } else {
3509            (0, x)
3510        };
3511
3512        let mut exact_unclipped = DisplayPoint::new(row, column);
3513        let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3514        let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3515
3516        let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3517        *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3518        PointForPosition {
3519            previous_valid,
3520            next_valid,
3521            exact_unclipped,
3522            column_overshoot_after_line_end,
3523        }
3524    }
3525}
3526
3527struct BlockLayout {
3528    row: u32,
3529    element: AnyElement,
3530    available_space: Size<AvailableSpace>,
3531    style: BlockStyle,
3532}
3533
3534fn layout_line(
3535    row: u32,
3536    snapshot: &EditorSnapshot,
3537    style: &EditorStyle,
3538    cx: &WindowContext,
3539) -> Result<ShapedLine> {
3540    let mut line = snapshot.line(row);
3541
3542    if line.len() > MAX_LINE_LEN {
3543        let mut len = MAX_LINE_LEN;
3544        while !line.is_char_boundary(len) {
3545            len -= 1;
3546        }
3547
3548        line.truncate(len);
3549    }
3550
3551    cx.text_system().shape_line(
3552        line.into(),
3553        style.text.font_size.to_pixels(cx.rem_size()),
3554        &[TextRun {
3555            len: snapshot.line_len(row) as usize,
3556            font: style.text.font(),
3557            color: Hsla::default(),
3558            background_color: None,
3559            underline: None,
3560            strikethrough: None,
3561        }],
3562    )
3563}
3564
3565pub struct CursorLayout {
3566    origin: gpui::Point<Pixels>,
3567    block_width: Pixels,
3568    line_height: Pixels,
3569    color: Hsla,
3570    shape: CursorShape,
3571    block_text: Option<ShapedLine>,
3572    cursor_name: Option<AnyElement>,
3573}
3574
3575#[derive(Debug)]
3576pub struct CursorName {
3577    string: SharedString,
3578    color: Hsla,
3579    is_top_row: bool,
3580}
3581
3582impl CursorLayout {
3583    pub fn new(
3584        origin: gpui::Point<Pixels>,
3585        block_width: Pixels,
3586        line_height: Pixels,
3587        color: Hsla,
3588        shape: CursorShape,
3589        block_text: Option<ShapedLine>,
3590    ) -> CursorLayout {
3591        CursorLayout {
3592            origin,
3593            block_width,
3594            line_height,
3595            color,
3596            shape,
3597            block_text,
3598            cursor_name: None,
3599        }
3600    }
3601
3602    pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3603        Bounds {
3604            origin: self.origin + origin,
3605            size: size(self.block_width, self.line_height),
3606        }
3607    }
3608
3609    fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3610        match self.shape {
3611            CursorShape::Bar => Bounds {
3612                origin: self.origin + origin,
3613                size: size(px(2.0), self.line_height),
3614            },
3615            CursorShape::Block | CursorShape::Hollow => Bounds {
3616                origin: self.origin + origin,
3617                size: size(self.block_width, self.line_height),
3618            },
3619            CursorShape::Underscore => Bounds {
3620                origin: self.origin
3621                    + origin
3622                    + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
3623                size: size(self.block_width, px(2.0)),
3624            },
3625        }
3626    }
3627
3628    pub fn layout(
3629        &mut self,
3630        origin: gpui::Point<Pixels>,
3631        cursor_name: Option<CursorName>,
3632        cx: &mut ElementContext,
3633    ) {
3634        if let Some(cursor_name) = cursor_name {
3635            let bounds = self.bounds(origin);
3636            let text_size = self.line_height / 1.5;
3637
3638            let name_origin = if cursor_name.is_top_row {
3639                point(bounds.right() - px(1.), bounds.top())
3640            } else {
3641                point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
3642            };
3643            let mut name_element = div()
3644                .bg(self.color)
3645                .text_size(text_size)
3646                .px_0p5()
3647                .line_height(text_size + px(2.))
3648                .text_color(cursor_name.color)
3649                .child(cursor_name.string.clone())
3650                .into_any_element();
3651
3652            name_element.layout(
3653                name_origin,
3654                size(AvailableSpace::MinContent, AvailableSpace::MinContent),
3655                cx,
3656            );
3657
3658            self.cursor_name = Some(name_element);
3659        }
3660    }
3661
3662    pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
3663        let bounds = self.bounds(origin);
3664
3665        //Draw background or border quad
3666        let cursor = if matches!(self.shape, CursorShape::Hollow) {
3667            outline(bounds, self.color)
3668        } else {
3669            fill(bounds, self.color)
3670        };
3671
3672        if let Some(name) = &mut self.cursor_name {
3673            name.paint(cx);
3674        }
3675
3676        cx.paint_quad(cursor);
3677
3678        if let Some(block_text) = &self.block_text {
3679            block_text
3680                .paint(self.origin + origin, self.line_height, cx)
3681                .log_err();
3682        }
3683    }
3684
3685    pub fn shape(&self) -> CursorShape {
3686        self.shape
3687    }
3688}
3689
3690#[derive(Debug)]
3691pub struct HighlightedRange {
3692    pub start_y: Pixels,
3693    pub line_height: Pixels,
3694    pub lines: Vec<HighlightedRangeLine>,
3695    pub color: Hsla,
3696    pub corner_radius: Pixels,
3697}
3698
3699#[derive(Debug)]
3700pub struct HighlightedRangeLine {
3701    pub start_x: Pixels,
3702    pub end_x: Pixels,
3703}
3704
3705impl HighlightedRange {
3706    pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
3707        if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
3708            self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
3709            self.paint_lines(
3710                self.start_y + self.line_height,
3711                &self.lines[1..],
3712                bounds,
3713                cx,
3714            );
3715        } else {
3716            self.paint_lines(self.start_y, &self.lines, bounds, cx);
3717        }
3718    }
3719
3720    fn paint_lines(
3721        &self,
3722        start_y: Pixels,
3723        lines: &[HighlightedRangeLine],
3724        _bounds: Bounds<Pixels>,
3725        cx: &mut ElementContext,
3726    ) {
3727        if lines.is_empty() {
3728            return;
3729        }
3730
3731        let first_line = lines.first().unwrap();
3732        let last_line = lines.last().unwrap();
3733
3734        let first_top_left = point(first_line.start_x, start_y);
3735        let first_top_right = point(first_line.end_x, start_y);
3736
3737        let curve_height = point(Pixels::ZERO, self.corner_radius);
3738        let curve_width = |start_x: Pixels, end_x: Pixels| {
3739            let max = (end_x - start_x) / 2.;
3740            let width = if max < self.corner_radius {
3741                max
3742            } else {
3743                self.corner_radius
3744            };
3745
3746            point(width, Pixels::ZERO)
3747        };
3748
3749        let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
3750        let mut path = gpui::Path::new(first_top_right - top_curve_width);
3751        path.curve_to(first_top_right + curve_height, first_top_right);
3752
3753        let mut iter = lines.iter().enumerate().peekable();
3754        while let Some((ix, line)) = iter.next() {
3755            let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
3756
3757            if let Some((_, next_line)) = iter.peek() {
3758                let next_top_right = point(next_line.end_x, bottom_right.y);
3759
3760                match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
3761                    Ordering::Equal => {
3762                        path.line_to(bottom_right);
3763                    }
3764                    Ordering::Less => {
3765                        let curve_width = curve_width(next_top_right.x, bottom_right.x);
3766                        path.line_to(bottom_right - curve_height);
3767                        if self.corner_radius > Pixels::ZERO {
3768                            path.curve_to(bottom_right - curve_width, bottom_right);
3769                        }
3770                        path.line_to(next_top_right + curve_width);
3771                        if self.corner_radius > Pixels::ZERO {
3772                            path.curve_to(next_top_right + curve_height, next_top_right);
3773                        }
3774                    }
3775                    Ordering::Greater => {
3776                        let curve_width = curve_width(bottom_right.x, next_top_right.x);
3777                        path.line_to(bottom_right - curve_height);
3778                        if self.corner_radius > Pixels::ZERO {
3779                            path.curve_to(bottom_right + curve_width, bottom_right);
3780                        }
3781                        path.line_to(next_top_right - curve_width);
3782                        if self.corner_radius > Pixels::ZERO {
3783                            path.curve_to(next_top_right + curve_height, next_top_right);
3784                        }
3785                    }
3786                }
3787            } else {
3788                let curve_width = curve_width(line.start_x, line.end_x);
3789                path.line_to(bottom_right - curve_height);
3790                if self.corner_radius > Pixels::ZERO {
3791                    path.curve_to(bottom_right - curve_width, bottom_right);
3792                }
3793
3794                let bottom_left = point(line.start_x, bottom_right.y);
3795                path.line_to(bottom_left + curve_width);
3796                if self.corner_radius > Pixels::ZERO {
3797                    path.curve_to(bottom_left - curve_height, bottom_left);
3798                }
3799            }
3800        }
3801
3802        if first_line.start_x > last_line.start_x {
3803            let curve_width = curve_width(last_line.start_x, first_line.start_x);
3804            let second_top_left = point(last_line.start_x, start_y + self.line_height);
3805            path.line_to(second_top_left + curve_height);
3806            if self.corner_radius > Pixels::ZERO {
3807                path.curve_to(second_top_left + curve_width, second_top_left);
3808            }
3809            let first_bottom_left = point(first_line.start_x, second_top_left.y);
3810            path.line_to(first_bottom_left - curve_width);
3811            if self.corner_radius > Pixels::ZERO {
3812                path.curve_to(first_bottom_left - curve_height, first_bottom_left);
3813            }
3814        }
3815
3816        path.line_to(first_top_left + curve_height);
3817        if self.corner_radius > Pixels::ZERO {
3818            path.curve_to(first_top_left + top_curve_width, first_top_left);
3819        }
3820        path.line_to(first_top_right - top_curve_width);
3821
3822        cx.paint_path(path, self.color);
3823    }
3824}
3825
3826pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3827    (delta.pow(1.5) / 100.0).into()
3828}
3829
3830fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
3831    (delta.pow(1.2) / 300.0).into()
3832}
3833
3834#[cfg(test)]
3835mod tests {
3836    use super::*;
3837    use crate::{
3838        display_map::{BlockDisposition, BlockProperties},
3839        editor_tests::{init_test, update_test_language_settings},
3840        Editor, MultiBuffer,
3841    };
3842    use gpui::TestAppContext;
3843    use language::language_settings;
3844    use log::info;
3845    use std::{num::NonZeroU32, sync::Arc};
3846    use util::test::sample_text;
3847
3848    #[gpui::test]
3849    fn test_shape_line_numbers(cx: &mut TestAppContext) {
3850        init_test(cx, |_| {});
3851        let window = cx.add_window(|cx| {
3852            let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3853            Editor::new(EditorMode::Full, buffer, None, cx)
3854        });
3855
3856        let editor = window.root(cx).unwrap();
3857        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3858        let element = EditorElement::new(&editor, style);
3859        let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
3860
3861        let layouts = cx
3862            .update_window(*window, |_, cx| {
3863                cx.with_element_context(|cx| {
3864                    element
3865                        .layout_line_numbers(
3866                            0..6,
3867                            &Default::default(),
3868                            Some(DisplayPoint::new(0, 0)),
3869                            &snapshot,
3870                            cx,
3871                        )
3872                        .0
3873                })
3874            })
3875            .unwrap();
3876        assert_eq!(layouts.len(), 6);
3877
3878        let relative_rows = window
3879            .update(cx, |editor, cx| {
3880                let snapshot = editor.snapshot(cx);
3881                element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
3882            })
3883            .unwrap();
3884        assert_eq!(relative_rows[&0], 3);
3885        assert_eq!(relative_rows[&1], 2);
3886        assert_eq!(relative_rows[&2], 1);
3887        // current line has no relative number
3888        assert_eq!(relative_rows[&4], 1);
3889        assert_eq!(relative_rows[&5], 2);
3890
3891        // works if cursor is before screen
3892        let relative_rows = window
3893            .update(cx, |editor, cx| {
3894                let snapshot = editor.snapshot(cx);
3895
3896                element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
3897            })
3898            .unwrap();
3899        assert_eq!(relative_rows.len(), 3);
3900        assert_eq!(relative_rows[&3], 2);
3901        assert_eq!(relative_rows[&4], 3);
3902        assert_eq!(relative_rows[&5], 4);
3903
3904        // works if cursor is after screen
3905        let relative_rows = window
3906            .update(cx, |editor, cx| {
3907                let snapshot = editor.snapshot(cx);
3908
3909                element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
3910            })
3911            .unwrap();
3912        assert_eq!(relative_rows.len(), 3);
3913        assert_eq!(relative_rows[&0], 5);
3914        assert_eq!(relative_rows[&1], 4);
3915        assert_eq!(relative_rows[&2], 3);
3916    }
3917
3918    #[gpui::test]
3919    async fn test_vim_visual_selections(cx: &mut TestAppContext) {
3920        init_test(cx, |_| {});
3921
3922        let window = cx.add_window(|cx| {
3923            let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
3924            Editor::new(EditorMode::Full, buffer, None, cx)
3925        });
3926        let editor = window.root(cx).unwrap();
3927        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
3928        let mut element = EditorElement::new(&editor, style);
3929
3930        window
3931            .update(cx, |editor, cx| {
3932                editor.cursor_shape = CursorShape::Block;
3933                editor.change_selections(None, cx, |s| {
3934                    s.select_ranges([
3935                        Point::new(0, 0)..Point::new(1, 0),
3936                        Point::new(3, 2)..Point::new(3, 3),
3937                        Point::new(5, 6)..Point::new(6, 0),
3938                    ]);
3939                });
3940            })
3941            .unwrap();
3942        let state = cx
3943            .update_window(window.into(), |_view, cx| {
3944                cx.with_element_context(|cx| {
3945                    element.after_layout(
3946                        Bounds {
3947                            origin: point(px(500.), px(500.)),
3948                            size: size(px(500.), px(500.)),
3949                        },
3950                        &mut (),
3951                        cx,
3952                    )
3953                })
3954            })
3955            .unwrap();
3956
3957        assert_eq!(state.selections.len(), 1);
3958        let local_selections = &state.selections[0].1;
3959        assert_eq!(local_selections.len(), 3);
3960        // moves cursor back one line
3961        assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
3962        assert_eq!(
3963            local_selections[0].range,
3964            DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
3965        );
3966
3967        // moves cursor back one column
3968        assert_eq!(
3969            local_selections[1].range,
3970            DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
3971        );
3972        assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
3973
3974        // leaves cursor on the max point
3975        assert_eq!(
3976            local_selections[2].range,
3977            DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
3978        );
3979        assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
3980
3981        // active lines does not include 1 (even though the range of the selection does)
3982        assert_eq!(
3983            state.active_rows.keys().cloned().collect::<Vec<u32>>(),
3984            vec![0, 3, 5, 6]
3985        );
3986
3987        // multi-buffer support
3988        // in DisplayPoint coordinates, this is what we're dealing with:
3989        //  0: [[file
3990        //  1:   header]]
3991        //  2: aaaaaa
3992        //  3: bbbbbb
3993        //  4: cccccc
3994        //  5:
3995        //  6: ...
3996        //  7: ffffff
3997        //  8: gggggg
3998        //  9: hhhhhh
3999        // 10:
4000        // 11: [[file
4001        // 12:   header]]
4002        // 13: bbbbbb
4003        // 14: cccccc
4004        // 15: dddddd
4005        let window = cx.add_window(|cx| {
4006            let buffer = MultiBuffer::build_multi(
4007                [
4008                    (
4009                        &(sample_text(8, 6, 'a') + "\n"),
4010                        vec![
4011                            Point::new(0, 0)..Point::new(3, 0),
4012                            Point::new(4, 0)..Point::new(7, 0),
4013                        ],
4014                    ),
4015                    (
4016                        &(sample_text(8, 6, 'a') + "\n"),
4017                        vec![Point::new(1, 0)..Point::new(3, 0)],
4018                    ),
4019                ],
4020                cx,
4021            );
4022            Editor::new(EditorMode::Full, buffer, None, cx)
4023        });
4024        let editor = window.root(cx).unwrap();
4025        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4026        let mut element = EditorElement::new(&editor, style);
4027        let _state = window.update(cx, |editor, cx| {
4028            editor.cursor_shape = CursorShape::Block;
4029            editor.change_selections(None, cx, |s| {
4030                s.select_display_ranges([
4031                    DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4032                    DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4033                ]);
4034            });
4035        });
4036
4037        let state = cx
4038            .update_window(window.into(), |_view, cx| {
4039                cx.with_element_context(|cx| {
4040                    element.after_layout(
4041                        Bounds {
4042                            origin: point(px(500.), px(500.)),
4043                            size: size(px(500.), px(500.)),
4044                        },
4045                        &mut (),
4046                        cx,
4047                    )
4048                })
4049            })
4050            .unwrap();
4051        assert_eq!(state.selections.len(), 1);
4052        let local_selections = &state.selections[0].1;
4053        assert_eq!(local_selections.len(), 2);
4054
4055        // moves cursor on excerpt boundary back a line
4056        // and doesn't allow selection to bleed through
4057        assert_eq!(
4058            local_selections[0].range,
4059            DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4060        );
4061        assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4062        // moves cursor on buffer boundary back two lines
4063        // and doesn't allow selection to bleed through
4064        assert_eq!(
4065            local_selections[1].range,
4066            DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4067        );
4068        assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4069    }
4070
4071    #[gpui::test]
4072    fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4073        init_test(cx, |_| {});
4074
4075        let window = cx.add_window(|cx| {
4076            let buffer = MultiBuffer::build_simple("", cx);
4077            Editor::new(EditorMode::Full, buffer, None, cx)
4078        });
4079        let editor = window.root(cx).unwrap();
4080        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4081        window
4082            .update(cx, |editor, cx| {
4083                editor.set_placeholder_text("hello", cx);
4084                editor.insert_blocks(
4085                    [BlockProperties {
4086                        style: BlockStyle::Fixed,
4087                        disposition: BlockDisposition::Above,
4088                        height: 3,
4089                        position: Anchor::min(),
4090                        render: Arc::new(|_| div().into_any()),
4091                    }],
4092                    None,
4093                    cx,
4094                );
4095
4096                // Blur the editor so that it displays placeholder text.
4097                cx.blur();
4098            })
4099            .unwrap();
4100
4101        let mut element = EditorElement::new(&editor, style);
4102        let state = cx
4103            .update_window(window.into(), |_view, cx| {
4104                cx.with_element_context(|cx| {
4105                    element.after_layout(
4106                        Bounds {
4107                            origin: point(px(500.), px(500.)),
4108                            size: size(px(500.), px(500.)),
4109                        },
4110                        &mut (),
4111                        cx,
4112                    )
4113                })
4114            })
4115            .unwrap();
4116
4117        assert_eq!(state.position_map.line_layouts.len(), 4);
4118        assert_eq!(
4119            state
4120                .line_numbers
4121                .iter()
4122                .map(Option::is_some)
4123                .collect::<Vec<_>>(),
4124            &[false, false, false, true]
4125        );
4126    }
4127
4128    #[gpui::test]
4129    fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4130        const TAB_SIZE: u32 = 4;
4131
4132        let input_text = "\t \t|\t| a b";
4133        let expected_invisibles = vec![
4134            Invisible::Tab {
4135                line_start_offset: 0,
4136            },
4137            Invisible::Whitespace {
4138                line_offset: TAB_SIZE as usize,
4139            },
4140            Invisible::Tab {
4141                line_start_offset: TAB_SIZE as usize + 1,
4142            },
4143            Invisible::Tab {
4144                line_start_offset: TAB_SIZE as usize * 2 + 1,
4145            },
4146            Invisible::Whitespace {
4147                line_offset: TAB_SIZE as usize * 3 + 1,
4148            },
4149            Invisible::Whitespace {
4150                line_offset: TAB_SIZE as usize * 3 + 3,
4151            },
4152        ];
4153        assert_eq!(
4154            expected_invisibles.len(),
4155            input_text
4156                .chars()
4157                .filter(|initial_char| initial_char.is_whitespace())
4158                .count(),
4159            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4160        );
4161
4162        init_test(cx, |s| {
4163            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4164            s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4165        });
4166
4167        let actual_invisibles =
4168            collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4169
4170        assert_eq!(expected_invisibles, actual_invisibles);
4171    }
4172
4173    #[gpui::test]
4174    fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4175        init_test(cx, |s| {
4176            s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4177            s.defaults.tab_size = NonZeroU32::new(4);
4178        });
4179
4180        for editor_mode_without_invisibles in [
4181            EditorMode::SingleLine,
4182            EditorMode::AutoHeight { max_lines: 100 },
4183        ] {
4184            let invisibles = collect_invisibles_from_new_editor(
4185                cx,
4186                editor_mode_without_invisibles,
4187                "\t\t\t| | a b",
4188                px(500.0),
4189            );
4190            assert!(invisibles.is_empty(),
4191                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4192        }
4193    }
4194
4195    #[gpui::test]
4196    fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4197        let tab_size = 4;
4198        let input_text = "a\tbcd   ".repeat(9);
4199        let repeated_invisibles = [
4200            Invisible::Tab {
4201                line_start_offset: 1,
4202            },
4203            Invisible::Whitespace {
4204                line_offset: tab_size as usize + 3,
4205            },
4206            Invisible::Whitespace {
4207                line_offset: tab_size as usize + 4,
4208            },
4209            Invisible::Whitespace {
4210                line_offset: tab_size as usize + 5,
4211            },
4212        ];
4213        let expected_invisibles = std::iter::once(repeated_invisibles)
4214            .cycle()
4215            .take(9)
4216            .flatten()
4217            .collect::<Vec<_>>();
4218        assert_eq!(
4219            expected_invisibles.len(),
4220            input_text
4221                .chars()
4222                .filter(|initial_char| initial_char.is_whitespace())
4223                .count(),
4224            "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4225        );
4226        info!("Expected invisibles: {expected_invisibles:?}");
4227
4228        init_test(cx, |_| {});
4229
4230        // Put the same string with repeating whitespace pattern into editors of various size,
4231        // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4232        let resize_step = 10.0;
4233        let mut editor_width = 200.0;
4234        while editor_width <= 1000.0 {
4235            update_test_language_settings(cx, |s| {
4236                s.defaults.tab_size = NonZeroU32::new(tab_size);
4237                s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4238                s.defaults.preferred_line_length = Some(editor_width as u32);
4239                s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4240            });
4241
4242            let actual_invisibles = collect_invisibles_from_new_editor(
4243                cx,
4244                EditorMode::Full,
4245                &input_text,
4246                px(editor_width),
4247            );
4248
4249            // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4250            // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4251            let mut i = 0;
4252            for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4253                i = actual_index;
4254                match expected_invisibles.get(i) {
4255                    Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4256                        (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4257                        | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4258                        _ => {
4259                            panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4260                        }
4261                    },
4262                    None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4263                }
4264            }
4265            let missing_expected_invisibles = &expected_invisibles[i + 1..];
4266            assert!(
4267                missing_expected_invisibles.is_empty(),
4268                "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4269            );
4270
4271            editor_width += resize_step;
4272        }
4273    }
4274
4275    fn collect_invisibles_from_new_editor(
4276        cx: &mut TestAppContext,
4277        editor_mode: EditorMode,
4278        input_text: &str,
4279        editor_width: Pixels,
4280    ) -> Vec<Invisible> {
4281        info!(
4282            "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4283            editor_width.0
4284        );
4285        let window = cx.add_window(|cx| {
4286            let buffer = MultiBuffer::build_simple(&input_text, cx);
4287            Editor::new(editor_mode, buffer, None, cx)
4288        });
4289        let editor = window.root(cx).unwrap();
4290        let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4291        let mut element = EditorElement::new(&editor, style);
4292        window
4293            .update(cx, |editor, cx| {
4294                editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4295                editor.set_wrap_width(Some(editor_width), cx);
4296            })
4297            .unwrap();
4298        let layout_state = cx
4299            .update_window(window.into(), |_, cx| {
4300                cx.with_element_context(|cx| {
4301                    element.after_layout(
4302                        Bounds {
4303                            origin: point(px(500.), px(500.)),
4304                            size: size(px(500.), px(500.)),
4305                        },
4306                        &mut (),
4307                        cx,
4308                    )
4309                })
4310            })
4311            .unwrap();
4312
4313        layout_state
4314            .position_map
4315            .line_layouts
4316            .iter()
4317            .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4318            .cloned()
4319            .collect()
4320    }
4321}
4322
4323pub fn register_action<T: Action>(
4324    view: &View<Editor>,
4325    cx: &mut WindowContext,
4326    listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4327) {
4328    let view = view.clone();
4329    cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4330        let action = action.downcast_ref().unwrap();
4331        if phase == DispatchPhase::Bubble {
4332            view.update(cx, |editor, cx| {
4333                listener(editor, action, cx);
4334            })
4335        }
4336    })
4337}
4338
4339fn compute_auto_height_layout(
4340    editor: &mut Editor,
4341    max_lines: usize,
4342    max_line_number_width: Pixels,
4343    known_dimensions: Size<Option<Pixels>>,
4344    cx: &mut ViewContext<Editor>,
4345) -> Option<Size<Pixels>> {
4346    let width = known_dimensions.width?;
4347    if let Some(height) = known_dimensions.height {
4348        return Some(size(width, height));
4349    }
4350
4351    let style = editor.style.as_ref().unwrap();
4352    let font_id = cx.text_system().resolve_font(&style.text.font());
4353    let font_size = style.text.font_size.to_pixels(cx.rem_size());
4354    let line_height = style.text.line_height_in_pixels(cx.rem_size());
4355    let em_width = cx
4356        .text_system()
4357        .typographic_bounds(font_id, font_size, 'm')
4358        .unwrap()
4359        .size
4360        .width;
4361
4362    let mut snapshot = editor.snapshot(cx);
4363    let gutter_dimensions =
4364        snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4365
4366    editor.gutter_width = gutter_dimensions.width;
4367    let text_width = width - gutter_dimensions.width;
4368    let overscroll = size(em_width, px(0.));
4369
4370    let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4371    if editor.set_wrap_width(Some(editor_width), cx) {
4372        snapshot = editor.snapshot(cx);
4373    }
4374
4375    let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4376    let height = scroll_height
4377        .max(line_height)
4378        .min(line_height * max_lines as f32);
4379
4380    Some(size(width, height))
4381}