element.rs

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