element.rs

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