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