items.rs

   1use crate::{
   2    editor_settings::SeedQuerySetting, link_go_to_definition::hide_link_definition,
   3    persistence::DB, scroll::ScrollAnchor, Anchor, Autoscroll, Editor, EditorEvent, EditorSettings,
   4    ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, NavigationData, ToPoint as _,
   5};
   6use anyhow::{anyhow, Context as _, Result};
   7use collections::HashSet;
   8use futures::future::try_join_all;
   9use gpui::{
  10    div, point, AnyElement, AppContext, AsyncWindowContext, Context, Entity, EntityId,
  11    EventEmitter, IntoElement, Model, ParentElement, Pixels, Render, SharedString, Styled,
  12    Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
  13};
  14use language::{
  15    proto::serialize_anchor as serialize_text_anchor, Bias, Buffer, CharKind, OffsetRangeExt,
  16    Point, SelectionGoal,
  17};
  18use project::repository::GitFileStatus;
  19use project::{search::SearchQuery, FormatTrigger, Item as _, Project, ProjectPath};
  20use rpc::proto::{self, update_view, PeerId};
  21use settings::Settings;
  22use workspace::item::ItemSettings;
  23
  24use std::fmt::Write;
  25use std::{
  26    borrow::Cow,
  27    cmp::{self, Ordering},
  28    iter,
  29    ops::Range,
  30    path::{Path, PathBuf},
  31    sync::Arc,
  32};
  33use text::Selection;
  34use theme::Theme;
  35use ui::{h_stack, prelude::*, Label};
  36use util::{paths::PathExt, paths::FILE_ROW_COLUMN_DELIMITER, ResultExt, TryFutureExt};
  37use workspace::{
  38    item::{BreadcrumbText, FollowEvent, FollowableItemHandle},
  39    StatusItemView,
  40};
  41use workspace::{
  42    item::{FollowableItem, Item, ItemEvent, ItemHandle, ProjectItem},
  43    searchable::{Direction, SearchEvent, SearchableItem, SearchableItemHandle},
  44    ItemId, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
  45};
  46
  47pub const MAX_TAB_TITLE_LEN: usize = 24;
  48
  49impl FollowableItem for Editor {
  50    fn remote_id(&self) -> Option<ViewId> {
  51        self.remote_id
  52    }
  53
  54    fn from_state_proto(
  55        pane: View<workspace::Pane>,
  56        workspace: View<Workspace>,
  57        remote_id: ViewId,
  58        state: &mut Option<proto::view::Variant>,
  59        cx: &mut WindowContext,
  60    ) -> Option<Task<Result<View<Self>>>> {
  61        let project = workspace.read(cx).project().to_owned();
  62        let Some(proto::view::Variant::Editor(_)) = state else {
  63            return None;
  64        };
  65        let Some(proto::view::Variant::Editor(state)) = state.take() else {
  66            unreachable!()
  67        };
  68
  69        let client = project.read(cx).client();
  70        let replica_id = project.read(cx).replica_id();
  71        let buffer_ids = state
  72            .excerpts
  73            .iter()
  74            .map(|excerpt| excerpt.buffer_id)
  75            .collect::<HashSet<_>>();
  76        let buffers = project.update(cx, |project, cx| {
  77            buffer_ids
  78                .iter()
  79                .map(|id| project.open_buffer_by_id(*id, cx))
  80                .collect::<Vec<_>>()
  81        });
  82
  83        let pane = pane.downgrade();
  84        Some(cx.spawn(|mut cx| async move {
  85            let mut buffers = futures::future::try_join_all(buffers).await?;
  86            let editor = pane.update(&mut cx, |pane, cx| {
  87                let mut editors = pane.items_of_type::<Self>();
  88                editors.find(|editor| {
  89                    let ids_match = editor.remote_id(&client, cx) == Some(remote_id);
  90                    let singleton_buffer_matches = state.singleton
  91                        && buffers.first()
  92                            == editor.read(cx).buffer.read(cx).as_singleton().as_ref();
  93                    ids_match || singleton_buffer_matches
  94                })
  95            })?;
  96
  97            let editor = if let Some(editor) = editor {
  98                editor
  99            } else {
 100                pane.update(&mut cx, |_, cx| {
 101                    let multibuffer = cx.new_model(|cx| {
 102                        let mut multibuffer;
 103                        if state.singleton && buffers.len() == 1 {
 104                            multibuffer = MultiBuffer::singleton(buffers.pop().unwrap(), cx)
 105                        } else {
 106                            multibuffer =
 107                                MultiBuffer::new(replica_id, project.read(cx).capability());
 108                            let mut excerpts = state.excerpts.into_iter().peekable();
 109                            while let Some(excerpt) = excerpts.peek() {
 110                                let buffer_id = excerpt.buffer_id;
 111                                let buffer_excerpts = iter::from_fn(|| {
 112                                    let excerpt = excerpts.peek()?;
 113                                    (excerpt.buffer_id == buffer_id)
 114                                        .then(|| excerpts.next().unwrap())
 115                                });
 116                                let buffer =
 117                                    buffers.iter().find(|b| b.read(cx).remote_id() == buffer_id);
 118                                if let Some(buffer) = buffer {
 119                                    multibuffer.push_excerpts(
 120                                        buffer.clone(),
 121                                        buffer_excerpts.filter_map(deserialize_excerpt_range),
 122                                        cx,
 123                                    );
 124                                }
 125                            }
 126                        };
 127
 128                        if let Some(title) = &state.title {
 129                            multibuffer = multibuffer.with_title(title.clone())
 130                        }
 131
 132                        multibuffer
 133                    });
 134
 135                    cx.new_view(|cx| {
 136                        let mut editor =
 137                            Editor::for_multibuffer(multibuffer, Some(project.clone()), cx);
 138                        editor.remote_id = Some(remote_id);
 139                        editor
 140                    })
 141                })?
 142            };
 143
 144            update_editor_from_message(
 145                editor.downgrade(),
 146                project,
 147                proto::update_view::Editor {
 148                    selections: state.selections,
 149                    pending_selection: state.pending_selection,
 150                    scroll_top_anchor: state.scroll_top_anchor,
 151                    scroll_x: state.scroll_x,
 152                    scroll_y: state.scroll_y,
 153                    ..Default::default()
 154                },
 155                &mut cx,
 156            )
 157            .await?;
 158
 159            Ok(editor)
 160        }))
 161    }
 162
 163    fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>) {
 164        self.leader_peer_id = leader_peer_id;
 165        if self.leader_peer_id.is_some() {
 166            self.buffer.update(cx, |buffer, cx| {
 167                buffer.remove_active_selections(cx);
 168            });
 169        } else if self.focus_handle.is_focused(cx) {
 170            self.buffer.update(cx, |buffer, cx| {
 171                buffer.set_active_selections(
 172                    &self.selections.disjoint_anchors(),
 173                    self.selections.line_mode,
 174                    self.cursor_shape,
 175                    cx,
 176                );
 177            });
 178        }
 179        cx.notify();
 180    }
 181
 182    fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
 183        let buffer = self.buffer.read(cx);
 184        let scroll_anchor = self.scroll_manager.anchor();
 185        let excerpts = buffer
 186            .read(cx)
 187            .excerpts()
 188            .map(|(id, buffer, range)| proto::Excerpt {
 189                id: id.to_proto(),
 190                buffer_id: buffer.remote_id(),
 191                context_start: Some(serialize_text_anchor(&range.context.start)),
 192                context_end: Some(serialize_text_anchor(&range.context.end)),
 193                primary_start: range
 194                    .primary
 195                    .as_ref()
 196                    .map(|range| serialize_text_anchor(&range.start)),
 197                primary_end: range
 198                    .primary
 199                    .as_ref()
 200                    .map(|range| serialize_text_anchor(&range.end)),
 201            })
 202            .collect();
 203
 204        Some(proto::view::Variant::Editor(proto::view::Editor {
 205            singleton: buffer.is_singleton(),
 206            title: (!buffer.is_singleton()).then(|| buffer.title(cx).into()),
 207            excerpts,
 208            scroll_top_anchor: Some(serialize_anchor(&scroll_anchor.anchor)),
 209            scroll_x: scroll_anchor.offset.x,
 210            scroll_y: scroll_anchor.offset.y,
 211            selections: self
 212                .selections
 213                .disjoint_anchors()
 214                .iter()
 215                .map(serialize_selection)
 216                .collect(),
 217            pending_selection: self
 218                .selections
 219                .pending_anchor()
 220                .as_ref()
 221                .map(serialize_selection),
 222        }))
 223    }
 224
 225    fn to_follow_event(event: &EditorEvent) -> Option<workspace::item::FollowEvent> {
 226        match event {
 227            EditorEvent::Edited => Some(FollowEvent::Unfollow),
 228            EditorEvent::SelectionsChanged { local }
 229            | EditorEvent::ScrollPositionChanged { local, .. } => {
 230                if *local {
 231                    Some(FollowEvent::Unfollow)
 232                } else {
 233                    None
 234                }
 235            }
 236            _ => None,
 237        }
 238    }
 239
 240    fn add_event_to_update_proto(
 241        &self,
 242        event: &EditorEvent,
 243        update: &mut Option<proto::update_view::Variant>,
 244        cx: &WindowContext,
 245    ) -> bool {
 246        let update =
 247            update.get_or_insert_with(|| proto::update_view::Variant::Editor(Default::default()));
 248
 249        match update {
 250            proto::update_view::Variant::Editor(update) => match event {
 251                EditorEvent::ExcerptsAdded {
 252                    buffer,
 253                    predecessor,
 254                    excerpts,
 255                } => {
 256                    let buffer_id = buffer.read(cx).remote_id();
 257                    let mut excerpts = excerpts.iter();
 258                    if let Some((id, range)) = excerpts.next() {
 259                        update.inserted_excerpts.push(proto::ExcerptInsertion {
 260                            previous_excerpt_id: Some(predecessor.to_proto()),
 261                            excerpt: serialize_excerpt(buffer_id, id, range),
 262                        });
 263                        update.inserted_excerpts.extend(excerpts.map(|(id, range)| {
 264                            proto::ExcerptInsertion {
 265                                previous_excerpt_id: None,
 266                                excerpt: serialize_excerpt(buffer_id, id, range),
 267                            }
 268                        }))
 269                    }
 270                    true
 271                }
 272                EditorEvent::ExcerptsRemoved { ids } => {
 273                    update
 274                        .deleted_excerpts
 275                        .extend(ids.iter().map(ExcerptId::to_proto));
 276                    true
 277                }
 278                EditorEvent::ScrollPositionChanged { .. } => {
 279                    let scroll_anchor = self.scroll_manager.anchor();
 280                    update.scroll_top_anchor = Some(serialize_anchor(&scroll_anchor.anchor));
 281                    update.scroll_x = scroll_anchor.offset.x;
 282                    update.scroll_y = scroll_anchor.offset.y;
 283                    true
 284                }
 285                EditorEvent::SelectionsChanged { .. } => {
 286                    update.selections = self
 287                        .selections
 288                        .disjoint_anchors()
 289                        .iter()
 290                        .map(serialize_selection)
 291                        .collect();
 292                    update.pending_selection = self
 293                        .selections
 294                        .pending_anchor()
 295                        .as_ref()
 296                        .map(serialize_selection);
 297                    true
 298                }
 299                _ => false,
 300            },
 301        }
 302    }
 303
 304    fn apply_update_proto(
 305        &mut self,
 306        project: &Model<Project>,
 307        message: update_view::Variant,
 308        cx: &mut ViewContext<Self>,
 309    ) -> Task<Result<()>> {
 310        let update_view::Variant::Editor(message) = message;
 311        let project = project.clone();
 312        cx.spawn(|this, mut cx| async move {
 313            update_editor_from_message(this, project, message, &mut cx).await
 314        })
 315    }
 316
 317    fn is_project_item(&self, _cx: &WindowContext) -> bool {
 318        true
 319    }
 320}
 321
 322async fn update_editor_from_message(
 323    this: WeakView<Editor>,
 324    project: Model<Project>,
 325    message: proto::update_view::Editor,
 326    cx: &mut AsyncWindowContext,
 327) -> Result<()> {
 328    // Open all of the buffers of which excerpts were added to the editor.
 329    let inserted_excerpt_buffer_ids = message
 330        .inserted_excerpts
 331        .iter()
 332        .filter_map(|insertion| Some(insertion.excerpt.as_ref()?.buffer_id))
 333        .collect::<HashSet<_>>();
 334    let inserted_excerpt_buffers = project.update(cx, |project, cx| {
 335        inserted_excerpt_buffer_ids
 336            .into_iter()
 337            .map(|id| project.open_buffer_by_id(id, cx))
 338            .collect::<Vec<_>>()
 339    })?;
 340    let _inserted_excerpt_buffers = try_join_all(inserted_excerpt_buffers).await?;
 341
 342    // Update the editor's excerpts.
 343    this.update(cx, |editor, cx| {
 344        editor.buffer.update(cx, |multibuffer, cx| {
 345            let mut removed_excerpt_ids = message
 346                .deleted_excerpts
 347                .into_iter()
 348                .map(ExcerptId::from_proto)
 349                .collect::<Vec<_>>();
 350            removed_excerpt_ids.sort_by({
 351                let multibuffer = multibuffer.read(cx);
 352                move |a, b| a.cmp(&b, &multibuffer)
 353            });
 354
 355            let mut insertions = message.inserted_excerpts.into_iter().peekable();
 356            while let Some(insertion) = insertions.next() {
 357                let Some(excerpt) = insertion.excerpt else {
 358                    continue;
 359                };
 360                let Some(previous_excerpt_id) = insertion.previous_excerpt_id else {
 361                    continue;
 362                };
 363                let buffer_id = excerpt.buffer_id;
 364                let Some(buffer) = project.read(cx).buffer_for_id(buffer_id) else {
 365                    continue;
 366                };
 367
 368                let adjacent_excerpts = iter::from_fn(|| {
 369                    let insertion = insertions.peek()?;
 370                    if insertion.previous_excerpt_id.is_none()
 371                        && insertion.excerpt.as_ref()?.buffer_id == buffer_id
 372                    {
 373                        insertions.next()?.excerpt
 374                    } else {
 375                        None
 376                    }
 377                });
 378
 379                multibuffer.insert_excerpts_with_ids_after(
 380                    ExcerptId::from_proto(previous_excerpt_id),
 381                    buffer,
 382                    [excerpt]
 383                        .into_iter()
 384                        .chain(adjacent_excerpts)
 385                        .filter_map(|excerpt| {
 386                            Some((
 387                                ExcerptId::from_proto(excerpt.id),
 388                                deserialize_excerpt_range(excerpt)?,
 389                            ))
 390                        }),
 391                    cx,
 392                );
 393            }
 394
 395            multibuffer.remove_excerpts(removed_excerpt_ids, cx);
 396        });
 397    })?;
 398
 399    // Deserialize the editor state.
 400    let (selections, pending_selection, scroll_top_anchor) = this.update(cx, |editor, cx| {
 401        let buffer = editor.buffer.read(cx).read(cx);
 402        let selections = message
 403            .selections
 404            .into_iter()
 405            .filter_map(|selection| deserialize_selection(&buffer, selection))
 406            .collect::<Vec<_>>();
 407        let pending_selection = message
 408            .pending_selection
 409            .and_then(|selection| deserialize_selection(&buffer, selection));
 410        let scroll_top_anchor = message
 411            .scroll_top_anchor
 412            .and_then(|anchor| deserialize_anchor(&buffer, anchor));
 413        anyhow::Ok((selections, pending_selection, scroll_top_anchor))
 414    })??;
 415
 416    // Wait until the buffer has received all of the operations referenced by
 417    // the editor's new state.
 418    this.update(cx, |editor, cx| {
 419        editor.buffer.update(cx, |buffer, cx| {
 420            buffer.wait_for_anchors(
 421                selections
 422                    .iter()
 423                    .chain(pending_selection.as_ref())
 424                    .flat_map(|selection| [selection.start, selection.end])
 425                    .chain(scroll_top_anchor),
 426                cx,
 427            )
 428        })
 429    })?
 430    .await?;
 431
 432    // Update the editor's state.
 433    this.update(cx, |editor, cx| {
 434        if !selections.is_empty() || pending_selection.is_some() {
 435            editor.set_selections_from_remote(selections, pending_selection, cx);
 436            editor.request_autoscroll_remotely(Autoscroll::newest(), cx);
 437        } else if let Some(scroll_top_anchor) = scroll_top_anchor {
 438            editor.set_scroll_anchor_remote(
 439                ScrollAnchor {
 440                    anchor: scroll_top_anchor,
 441                    offset: point(message.scroll_x, message.scroll_y),
 442                },
 443                cx,
 444            );
 445        }
 446    })?;
 447    Ok(())
 448}
 449
 450fn serialize_excerpt(
 451    buffer_id: u64,
 452    id: &ExcerptId,
 453    range: &ExcerptRange<language::Anchor>,
 454) -> Option<proto::Excerpt> {
 455    Some(proto::Excerpt {
 456        id: id.to_proto(),
 457        buffer_id,
 458        context_start: Some(serialize_text_anchor(&range.context.start)),
 459        context_end: Some(serialize_text_anchor(&range.context.end)),
 460        primary_start: range
 461            .primary
 462            .as_ref()
 463            .map(|r| serialize_text_anchor(&r.start)),
 464        primary_end: range
 465            .primary
 466            .as_ref()
 467            .map(|r| serialize_text_anchor(&r.end)),
 468    })
 469}
 470
 471fn serialize_selection(selection: &Selection<Anchor>) -> proto::Selection {
 472    proto::Selection {
 473        id: selection.id as u64,
 474        start: Some(serialize_anchor(&selection.start)),
 475        end: Some(serialize_anchor(&selection.end)),
 476        reversed: selection.reversed,
 477    }
 478}
 479
 480fn serialize_anchor(anchor: &Anchor) -> proto::EditorAnchor {
 481    proto::EditorAnchor {
 482        excerpt_id: anchor.excerpt_id.to_proto(),
 483        anchor: Some(serialize_text_anchor(&anchor.text_anchor)),
 484    }
 485}
 486
 487fn deserialize_excerpt_range(excerpt: proto::Excerpt) -> Option<ExcerptRange<language::Anchor>> {
 488    let context = {
 489        let start = language::proto::deserialize_anchor(excerpt.context_start?)?;
 490        let end = language::proto::deserialize_anchor(excerpt.context_end?)?;
 491        start..end
 492    };
 493    let primary = excerpt
 494        .primary_start
 495        .zip(excerpt.primary_end)
 496        .and_then(|(start, end)| {
 497            let start = language::proto::deserialize_anchor(start)?;
 498            let end = language::proto::deserialize_anchor(end)?;
 499            Some(start..end)
 500        });
 501    Some(ExcerptRange { context, primary })
 502}
 503
 504fn deserialize_selection(
 505    buffer: &MultiBufferSnapshot,
 506    selection: proto::Selection,
 507) -> Option<Selection<Anchor>> {
 508    Some(Selection {
 509        id: selection.id as usize,
 510        start: deserialize_anchor(buffer, selection.start?)?,
 511        end: deserialize_anchor(buffer, selection.end?)?,
 512        reversed: selection.reversed,
 513        goal: SelectionGoal::None,
 514    })
 515}
 516
 517fn deserialize_anchor(buffer: &MultiBufferSnapshot, anchor: proto::EditorAnchor) -> Option<Anchor> {
 518    let excerpt_id = ExcerptId::from_proto(anchor.excerpt_id);
 519    Some(Anchor {
 520        excerpt_id,
 521        text_anchor: language::proto::deserialize_anchor(anchor.anchor?)?,
 522        buffer_id: buffer.buffer_id_for_excerpt(excerpt_id),
 523    })
 524}
 525
 526impl Item for Editor {
 527    type Event = EditorEvent;
 528
 529    fn navigate(&mut self, data: Box<dyn std::any::Any>, cx: &mut ViewContext<Self>) -> bool {
 530        if let Ok(data) = data.downcast::<NavigationData>() {
 531            let newest_selection = self.selections.newest::<Point>(cx);
 532            let buffer = self.buffer.read(cx).read(cx);
 533            let offset = if buffer.can_resolve(&data.cursor_anchor) {
 534                data.cursor_anchor.to_point(&buffer)
 535            } else {
 536                buffer.clip_point(data.cursor_position, Bias::Left)
 537            };
 538
 539            let mut scroll_anchor = data.scroll_anchor;
 540            if !buffer.can_resolve(&scroll_anchor.anchor) {
 541                scroll_anchor.anchor = buffer.anchor_before(
 542                    buffer.clip_point(Point::new(data.scroll_top_row, 0), Bias::Left),
 543                );
 544            }
 545
 546            drop(buffer);
 547
 548            if newest_selection.head() == offset {
 549                false
 550            } else {
 551                let nav_history = self.nav_history.take();
 552                self.set_scroll_anchor(scroll_anchor, cx);
 553                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 554                    s.select_ranges([offset..offset])
 555                });
 556                self.nav_history = nav_history;
 557                true
 558            }
 559        } else {
 560            false
 561        }
 562    }
 563
 564    fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
 565        let file_path = self
 566            .buffer()
 567            .read(cx)
 568            .as_singleton()?
 569            .read(cx)
 570            .file()
 571            .and_then(|f| f.as_local())?
 572            .abs_path(cx);
 573
 574        let file_path = file_path.compact().to_string_lossy().to_string();
 575
 576        Some(file_path.into())
 577    }
 578
 579    fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<SharedString> {
 580        let path = path_for_buffer(&self.buffer, detail, true, cx)?;
 581        Some(path.to_string_lossy().to_string().into())
 582    }
 583
 584    fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement {
 585        let git_status = if ItemSettings::get_global(cx).git_status {
 586            self.buffer()
 587                .read(cx)
 588                .as_singleton()
 589                .and_then(|buffer| buffer.read(cx).project_path(cx))
 590                .and_then(|path| self.project.as_ref()?.read(cx).entry_for_path(&path, cx))
 591                .and_then(|entry| entry.git_status())
 592        } else {
 593            None
 594        };
 595        let label_color = match git_status {
 596            Some(GitFileStatus::Added) => Color::Created,
 597            Some(GitFileStatus::Modified) => Color::Modified,
 598            Some(GitFileStatus::Conflict) => Color::Conflict,
 599            None => {
 600                if selected {
 601                    Color::Default
 602                } else {
 603                    Color::Muted
 604                }
 605            }
 606        };
 607
 608        let description = detail.and_then(|detail| {
 609            let path = path_for_buffer(&self.buffer, detail, false, cx)?;
 610            let description = path.to_string_lossy();
 611            let description = description.trim();
 612
 613            if description.is_empty() {
 614                return None;
 615            }
 616
 617            Some(util::truncate_and_trailoff(&description, MAX_TAB_TITLE_LEN))
 618        });
 619
 620        h_stack()
 621            .gap_2()
 622            .child(Label::new(self.title(cx).to_string()).color(label_color))
 623            .when_some(description, |this, description| {
 624                this.child(
 625                    Label::new(description)
 626                        .size(LabelSize::XSmall)
 627                        .color(Color::Muted),
 628                )
 629            })
 630            .into_any_element()
 631    }
 632
 633    fn for_each_project_item(
 634        &self,
 635        cx: &AppContext,
 636        f: &mut dyn FnMut(EntityId, &dyn project::Item),
 637    ) {
 638        self.buffer
 639            .read(cx)
 640            .for_each_buffer(|buffer| f(buffer.entity_id(), buffer.read(cx)));
 641    }
 642
 643    fn is_singleton(&self, cx: &AppContext) -> bool {
 644        self.buffer.read(cx).is_singleton()
 645    }
 646
 647    fn clone_on_split(
 648        &self,
 649        _workspace_id: WorkspaceId,
 650        cx: &mut ViewContext<Self>,
 651    ) -> Option<View<Editor>>
 652    where
 653        Self: Sized,
 654    {
 655        Some(cx.new_view(|cx| self.clone(cx)))
 656    }
 657
 658    fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
 659        self.nav_history = Some(history);
 660    }
 661
 662    fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
 663        let selection = self.selections.newest_anchor();
 664        self.push_to_nav_history(selection.head(), None, cx);
 665    }
 666
 667    fn workspace_deactivated(&mut self, cx: &mut ViewContext<Self>) {
 668        hide_link_definition(self, cx);
 669        self.link_go_to_definition_state.last_trigger_point = None;
 670    }
 671
 672    fn is_dirty(&self, cx: &AppContext) -> bool {
 673        self.buffer().read(cx).read(cx).is_dirty()
 674    }
 675
 676    fn has_conflict(&self, cx: &AppContext) -> bool {
 677        self.buffer().read(cx).read(cx).has_conflict()
 678    }
 679
 680    fn can_save(&self, cx: &AppContext) -> bool {
 681        let buffer = &self.buffer().read(cx);
 682        if let Some(buffer) = buffer.as_singleton() {
 683            buffer.read(cx).project_path(cx).is_some()
 684        } else {
 685            true
 686        }
 687    }
 688
 689    fn save(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 690        self.report_editor_event("save", None, cx);
 691        let format = self.perform_format(project.clone(), FormatTrigger::Save, cx);
 692        let buffers = self.buffer().clone().read(cx).all_buffers();
 693        cx.spawn(|_, mut cx| async move {
 694            format.await?;
 695
 696            if buffers.len() == 1 {
 697                project
 698                    .update(&mut cx, |project, cx| project.save_buffers(buffers, cx))?
 699                    .await?;
 700            } else {
 701                // For multi-buffers, only save those ones that contain changes. For clean buffers
 702                // we simulate saving by calling `Buffer::did_save`, so that language servers or
 703                // other downstream listeners of save events get notified.
 704                let (dirty_buffers, clean_buffers) = buffers.into_iter().partition(|buffer| {
 705                    buffer
 706                        .update(&mut cx, |buffer, _| {
 707                            buffer.is_dirty() || buffer.has_conflict()
 708                        })
 709                        .unwrap_or(false)
 710                });
 711
 712                project
 713                    .update(&mut cx, |project, cx| {
 714                        project.save_buffers(dirty_buffers, cx)
 715                    })?
 716                    .await?;
 717                for buffer in clean_buffers {
 718                    buffer
 719                        .update(&mut cx, |buffer, cx| {
 720                            let version = buffer.saved_version().clone();
 721                            let fingerprint = buffer.saved_version_fingerprint();
 722                            let mtime = buffer.saved_mtime();
 723                            buffer.did_save(version, fingerprint, mtime, cx);
 724                        })
 725                        .ok();
 726                }
 727            }
 728
 729            Ok(())
 730        })
 731    }
 732
 733    fn save_as(
 734        &mut self,
 735        project: Model<Project>,
 736        abs_path: PathBuf,
 737        cx: &mut ViewContext<Self>,
 738    ) -> Task<Result<()>> {
 739        let buffer = self
 740            .buffer()
 741            .read(cx)
 742            .as_singleton()
 743            .expect("cannot call save_as on an excerpt list");
 744
 745        let file_extension = abs_path
 746            .extension()
 747            .map(|a| a.to_string_lossy().to_string());
 748        self.report_editor_event("save", file_extension, cx);
 749
 750        project.update(cx, |project, cx| {
 751            project.save_buffer_as(buffer, abs_path, cx)
 752        })
 753    }
 754
 755    fn reload(&mut self, project: Model<Project>, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
 756        let buffer = self.buffer().clone();
 757        let buffers = self.buffer.read(cx).all_buffers();
 758        let reload_buffers =
 759            project.update(cx, |project, cx| project.reload_buffers(buffers, true, cx));
 760        cx.spawn(|this, mut cx| async move {
 761            let transaction = reload_buffers.log_err().await;
 762            this.update(&mut cx, |editor, cx| {
 763                editor.request_autoscroll(Autoscroll::fit(), cx)
 764            })?;
 765            buffer
 766                .update(&mut cx, |buffer, cx| {
 767                    if let Some(transaction) = transaction {
 768                        if !buffer.is_singleton() {
 769                            buffer.push_transaction(&transaction.0, cx);
 770                        }
 771                    }
 772                })
 773                .ok();
 774            Ok(())
 775        })
 776    }
 777
 778    fn as_searchable(&self, handle: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
 779        Some(Box::new(handle.clone()))
 780    }
 781
 782    fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<gpui::Point<Pixels>> {
 783        self.pixel_position_of_newest_cursor
 784    }
 785
 786    fn breadcrumb_location(&self) -> ToolbarItemLocation {
 787        ToolbarItemLocation::PrimaryLeft
 788    }
 789
 790    fn breadcrumbs(&self, variant: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
 791        let cursor = self.selections.newest_anchor().head();
 792        let multibuffer = &self.buffer().read(cx);
 793        let (buffer_id, symbols) =
 794            multibuffer.symbols_containing(cursor, Some(&variant.syntax()), cx)?;
 795        let buffer = multibuffer.buffer(buffer_id)?;
 796
 797        let buffer = buffer.read(cx);
 798        let filename = buffer
 799            .snapshot()
 800            .resolve_file_path(
 801                cx,
 802                self.project
 803                    .as_ref()
 804                    .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
 805                    .unwrap_or_default(),
 806            )
 807            .map(|path| path.to_string_lossy().to_string())
 808            .unwrap_or_else(|| "untitled".to_string());
 809
 810        let mut breadcrumbs = vec![BreadcrumbText {
 811            text: filename,
 812            highlights: None,
 813        }];
 814        breadcrumbs.extend(symbols.into_iter().map(|symbol| BreadcrumbText {
 815            text: symbol.text,
 816            highlights: Some(symbol.highlight_ranges),
 817        }));
 818        Some(breadcrumbs)
 819    }
 820
 821    fn added_to_workspace(&mut self, workspace: &mut Workspace, cx: &mut ViewContext<Self>) {
 822        let workspace_id = workspace.database_id();
 823        let item_id = cx.view().item_id().as_u64() as ItemId;
 824        self.workspace = Some((workspace.weak_handle(), workspace.database_id()));
 825
 826        fn serialize(
 827            buffer: Model<Buffer>,
 828            workspace_id: WorkspaceId,
 829            item_id: ItemId,
 830            cx: &mut AppContext,
 831        ) {
 832            if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 833                let path = file.abs_path(cx);
 834
 835                cx.background_executor()
 836                    .spawn(async move {
 837                        DB.save_path(item_id, workspace_id, path.clone())
 838                            .await
 839                            .log_err()
 840                    })
 841                    .detach();
 842            }
 843        }
 844
 845        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 846            serialize(buffer.clone(), workspace_id, item_id, cx);
 847
 848            cx.subscribe(&buffer, |this, buffer, event, cx| {
 849                if let Some((_, workspace_id)) = this.workspace.as_ref() {
 850                    if let language::Event::FileHandleChanged = event {
 851                        serialize(
 852                            buffer,
 853                            *workspace_id,
 854                            cx.view().item_id().as_u64() as ItemId,
 855                            cx,
 856                        );
 857                    }
 858                }
 859            })
 860            .detach();
 861        }
 862    }
 863
 864    fn serialized_item_kind() -> Option<&'static str> {
 865        Some("Editor")
 866    }
 867
 868    fn to_item_events(event: &EditorEvent, mut f: impl FnMut(ItemEvent)) {
 869        match event {
 870            EditorEvent::Closed => f(ItemEvent::CloseItem),
 871
 872            EditorEvent::Saved | EditorEvent::TitleChanged => {
 873                f(ItemEvent::UpdateTab);
 874                f(ItemEvent::UpdateBreadcrumbs);
 875            }
 876
 877            EditorEvent::Reparsed => {
 878                f(ItemEvent::UpdateBreadcrumbs);
 879            }
 880
 881            EditorEvent::SelectionsChanged { local } if *local => {
 882                f(ItemEvent::UpdateBreadcrumbs);
 883            }
 884
 885            EditorEvent::DirtyChanged => {
 886                f(ItemEvent::UpdateTab);
 887            }
 888
 889            EditorEvent::BufferEdited => {
 890                f(ItemEvent::Edit);
 891                f(ItemEvent::UpdateBreadcrumbs);
 892            }
 893
 894            EditorEvent::ExcerptsAdded { .. } | EditorEvent::ExcerptsRemoved { .. } => {
 895                f(ItemEvent::Edit);
 896            }
 897
 898            _ => {}
 899        }
 900    }
 901
 902    fn deserialize(
 903        project: Model<Project>,
 904        _workspace: WeakView<Workspace>,
 905        workspace_id: workspace::WorkspaceId,
 906        item_id: ItemId,
 907        cx: &mut ViewContext<Pane>,
 908    ) -> Task<Result<View<Self>>> {
 909        let project_item: Result<_> = project.update(cx, |project, cx| {
 910            // Look up the path with this key associated, create a self with that path
 911            let path = DB
 912                .get_path(item_id, workspace_id)?
 913                .context("No path stored for this editor")?;
 914
 915            let (worktree, path) = project
 916                .find_local_worktree(&path, cx)
 917                .with_context(|| format!("No worktree for path: {path:?}"))?;
 918            let project_path = ProjectPath {
 919                worktree_id: worktree.read(cx).id(),
 920                path: path.into(),
 921            };
 922
 923            Ok(project.open_path(project_path, cx))
 924        });
 925
 926        project_item
 927            .map(|project_item| {
 928                cx.spawn(|pane, mut cx| async move {
 929                    let (_, project_item) = project_item.await?;
 930                    let buffer = project_item
 931                        .downcast::<Buffer>()
 932                        .map_err(|_| anyhow!("Project item at stored path was not a buffer"))?;
 933                    Ok(pane.update(&mut cx, |_, cx| {
 934                        cx.new_view(|cx| {
 935                            let mut editor = Editor::for_buffer(buffer, Some(project), cx);
 936
 937                            editor.read_scroll_position_from_db(item_id, workspace_id, cx);
 938                            editor
 939                        })
 940                    })?)
 941                })
 942            })
 943            .unwrap_or_else(|error| Task::ready(Err(error)))
 944    }
 945}
 946
 947impl ProjectItem for Editor {
 948    type Item = Buffer;
 949
 950    fn for_project_item(
 951        project: Model<Project>,
 952        buffer: Model<Buffer>,
 953        cx: &mut ViewContext<Self>,
 954    ) -> Self {
 955        Self::for_buffer(buffer, Some(project), cx)
 956    }
 957}
 958
 959impl EventEmitter<SearchEvent> for Editor {}
 960
 961pub(crate) enum BufferSearchHighlights {}
 962impl SearchableItem for Editor {
 963    type Match = Range<Anchor>;
 964
 965    fn clear_matches(&mut self, cx: &mut ViewContext<Self>) {
 966        self.clear_background_highlights::<BufferSearchHighlights>(cx);
 967    }
 968
 969    fn update_matches(&mut self, matches: Vec<Range<Anchor>>, cx: &mut ViewContext<Self>) {
 970        self.highlight_background::<BufferSearchHighlights>(
 971            matches,
 972            |theme| theme.search_match_background,
 973            cx,
 974        );
 975    }
 976
 977    fn query_suggestion(&mut self, cx: &mut ViewContext<Self>) -> String {
 978        let setting = EditorSettings::get_global(cx).seed_search_query_from_cursor;
 979        let snapshot = &self.snapshot(cx).buffer_snapshot;
 980        let selection = self.selections.newest::<usize>(cx);
 981
 982        match setting {
 983            SeedQuerySetting::Never => String::new(),
 984            SeedQuerySetting::Selection | SeedQuerySetting::Always if !selection.is_empty() => {
 985                snapshot
 986                    .text_for_range(selection.start..selection.end)
 987                    .collect()
 988            }
 989            SeedQuerySetting::Selection => String::new(),
 990            SeedQuerySetting::Always => {
 991                let (range, kind) = snapshot.surrounding_word(selection.start);
 992                if kind == Some(CharKind::Word) {
 993                    let text: String = snapshot.text_for_range(range).collect();
 994                    if !text.trim().is_empty() {
 995                        return text;
 996                    }
 997                }
 998                String::new()
 999            }
1000        }
1001    }
1002
1003    fn activate_match(
1004        &mut self,
1005        index: usize,
1006        matches: Vec<Range<Anchor>>,
1007        cx: &mut ViewContext<Self>,
1008    ) {
1009        self.unfold_ranges([matches[index].clone()], false, true, cx);
1010        let range = self.range_for_match(&matches[index]);
1011        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
1012            s.select_ranges([range]);
1013        })
1014    }
1015
1016    fn select_matches(&mut self, matches: Vec<Self::Match>, cx: &mut ViewContext<Self>) {
1017        self.unfold_ranges(matches.clone(), false, false, cx);
1018        let mut ranges = Vec::new();
1019        for m in &matches {
1020            ranges.push(self.range_for_match(&m))
1021        }
1022        self.change_selections(None, cx, |s| s.select_ranges(ranges));
1023    }
1024    fn replace(
1025        &mut self,
1026        identifier: &Self::Match,
1027        query: &SearchQuery,
1028        cx: &mut ViewContext<Self>,
1029    ) {
1030        let text = self.buffer.read(cx);
1031        let text = text.snapshot(cx);
1032        let text = text.text_for_range(identifier.clone()).collect::<Vec<_>>();
1033        let text: Cow<_> = if text.len() == 1 {
1034            text.first().cloned().unwrap().into()
1035        } else {
1036            let joined_chunks = text.join("");
1037            joined_chunks.into()
1038        };
1039
1040        if let Some(replacement) = query.replacement_for(&text) {
1041            self.transact(cx, |this, cx| {
1042                this.edit([(identifier.clone(), Arc::from(&*replacement))], cx);
1043            });
1044        }
1045    }
1046    fn match_index_for_direction(
1047        &mut self,
1048        matches: &Vec<Range<Anchor>>,
1049        current_index: usize,
1050        direction: Direction,
1051        count: usize,
1052        cx: &mut ViewContext<Self>,
1053    ) -> usize {
1054        let buffer = self.buffer().read(cx).snapshot(cx);
1055        let current_index_position = if self.selections.disjoint_anchors().len() == 1 {
1056            self.selections.newest_anchor().head()
1057        } else {
1058            matches[current_index].start
1059        };
1060
1061        let mut count = count % matches.len();
1062        if count == 0 {
1063            return current_index;
1064        }
1065        match direction {
1066            Direction::Next => {
1067                if matches[current_index]
1068                    .start
1069                    .cmp(&current_index_position, &buffer)
1070                    .is_gt()
1071                {
1072                    count = count - 1
1073                }
1074
1075                (current_index + count) % matches.len()
1076            }
1077            Direction::Prev => {
1078                if matches[current_index]
1079                    .end
1080                    .cmp(&current_index_position, &buffer)
1081                    .is_lt()
1082                {
1083                    count = count - 1;
1084                }
1085
1086                if current_index >= count {
1087                    current_index - count
1088                } else {
1089                    matches.len() - (count - current_index)
1090                }
1091            }
1092        }
1093    }
1094
1095    fn find_matches(
1096        &mut self,
1097        query: Arc<project::search::SearchQuery>,
1098        cx: &mut ViewContext<Self>,
1099    ) -> Task<Vec<Range<Anchor>>> {
1100        let buffer = self.buffer().read(cx).snapshot(cx);
1101        cx.background_executor().spawn(async move {
1102            let mut ranges = Vec::new();
1103            if let Some((_, _, excerpt_buffer)) = buffer.as_singleton() {
1104                ranges.extend(
1105                    query
1106                        .search(excerpt_buffer, None)
1107                        .await
1108                        .into_iter()
1109                        .map(|range| {
1110                            buffer.anchor_after(range.start)..buffer.anchor_before(range.end)
1111                        }),
1112                );
1113            } else {
1114                for excerpt in buffer.excerpt_boundaries_in_range(0..buffer.len()) {
1115                    let excerpt_range = excerpt.range.context.to_offset(&excerpt.buffer);
1116                    ranges.extend(
1117                        query
1118                            .search(&excerpt.buffer, Some(excerpt_range.clone()))
1119                            .await
1120                            .into_iter()
1121                            .map(|range| {
1122                                let start = excerpt
1123                                    .buffer
1124                                    .anchor_after(excerpt_range.start + range.start);
1125                                let end = excerpt
1126                                    .buffer
1127                                    .anchor_before(excerpt_range.start + range.end);
1128                                buffer.anchor_in_excerpt(excerpt.id.clone(), start)
1129                                    ..buffer.anchor_in_excerpt(excerpt.id.clone(), end)
1130                            }),
1131                    );
1132                }
1133            }
1134            ranges
1135        })
1136    }
1137
1138    fn active_match_index(
1139        &mut self,
1140        matches: Vec<Range<Anchor>>,
1141        cx: &mut ViewContext<Self>,
1142    ) -> Option<usize> {
1143        active_match_index(
1144            &matches,
1145            &self.selections.newest_anchor().head(),
1146            &self.buffer().read(cx).snapshot(cx),
1147        )
1148    }
1149}
1150
1151pub fn active_match_index(
1152    ranges: &[Range<Anchor>],
1153    cursor: &Anchor,
1154    buffer: &MultiBufferSnapshot,
1155) -> Option<usize> {
1156    if ranges.is_empty() {
1157        None
1158    } else {
1159        match ranges.binary_search_by(|probe| {
1160            if probe.end.cmp(cursor, &*buffer).is_lt() {
1161                Ordering::Less
1162            } else if probe.start.cmp(cursor, &*buffer).is_gt() {
1163                Ordering::Greater
1164            } else {
1165                Ordering::Equal
1166            }
1167        }) {
1168            Ok(i) | Err(i) => Some(cmp::min(i, ranges.len() - 1)),
1169        }
1170    }
1171}
1172
1173pub struct CursorPosition {
1174    position: Option<Point>,
1175    selected_count: usize,
1176    _observe_active_editor: Option<Subscription>,
1177}
1178
1179impl Default for CursorPosition {
1180    fn default() -> Self {
1181        Self::new()
1182    }
1183}
1184
1185impl CursorPosition {
1186    pub fn new() -> Self {
1187        Self {
1188            position: None,
1189            selected_count: 0,
1190            _observe_active_editor: None,
1191        }
1192    }
1193
1194    fn update_position(&mut self, editor: View<Editor>, cx: &mut ViewContext<Self>) {
1195        let editor = editor.read(cx);
1196        let buffer = editor.buffer().read(cx).snapshot(cx);
1197
1198        self.selected_count = 0;
1199        let mut last_selection: Option<Selection<usize>> = None;
1200        for selection in editor.selections.all::<usize>(cx) {
1201            self.selected_count += selection.end - selection.start;
1202            if last_selection
1203                .as_ref()
1204                .map_or(true, |last_selection| selection.id > last_selection.id)
1205            {
1206                last_selection = Some(selection);
1207            }
1208        }
1209        self.position = last_selection.map(|s| s.head().to_point(&buffer));
1210
1211        cx.notify();
1212    }
1213}
1214
1215impl Render for CursorPosition {
1216    fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1217        div().when_some(self.position, |el, position| {
1218            let mut text = format!(
1219                "{}{FILE_ROW_COLUMN_DELIMITER}{}",
1220                position.row + 1,
1221                position.column + 1
1222            );
1223            if self.selected_count > 0 {
1224                write!(text, " ({} selected)", self.selected_count).unwrap();
1225            }
1226
1227            el.child(Label::new(text).size(LabelSize::Small))
1228        })
1229    }
1230}
1231
1232impl StatusItemView for CursorPosition {
1233    fn set_active_pane_item(
1234        &mut self,
1235        active_pane_item: Option<&dyn ItemHandle>,
1236        cx: &mut ViewContext<Self>,
1237    ) {
1238        if let Some(editor) = active_pane_item.and_then(|item| item.act_as::<Editor>(cx)) {
1239            self._observe_active_editor = Some(cx.observe(&editor, Self::update_position));
1240            self.update_position(editor, cx);
1241        } else {
1242            self.position = None;
1243            self._observe_active_editor = None;
1244        }
1245
1246        cx.notify();
1247    }
1248}
1249
1250fn path_for_buffer<'a>(
1251    buffer: &Model<MultiBuffer>,
1252    height: usize,
1253    include_filename: bool,
1254    cx: &'a AppContext,
1255) -> Option<Cow<'a, Path>> {
1256    let file = buffer.read(cx).as_singleton()?.read(cx).file()?;
1257    path_for_file(file.as_ref(), height, include_filename, cx)
1258}
1259
1260fn path_for_file<'a>(
1261    file: &'a dyn language::File,
1262    mut height: usize,
1263    include_filename: bool,
1264    cx: &'a AppContext,
1265) -> Option<Cow<'a, Path>> {
1266    // Ensure we always render at least the filename.
1267    height += 1;
1268
1269    let mut prefix = file.path().as_ref();
1270    while height > 0 {
1271        if let Some(parent) = prefix.parent() {
1272            prefix = parent;
1273            height -= 1;
1274        } else {
1275            break;
1276        }
1277    }
1278
1279    // Here we could have just always used `full_path`, but that is very
1280    // allocation-heavy and so we try to use a `Cow<Path>` if we haven't
1281    // traversed all the way up to the worktree's root.
1282    if height > 0 {
1283        let full_path = file.full_path(cx);
1284        if include_filename {
1285            Some(full_path.into())
1286        } else {
1287            Some(full_path.parent()?.to_path_buf().into())
1288        }
1289    } else {
1290        let mut path = file.path().strip_prefix(prefix).ok()?;
1291        if !include_filename {
1292            path = path.parent()?;
1293        }
1294        Some(path.into())
1295    }
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300    use super::*;
1301    use gpui::AppContext;
1302    use std::{
1303        path::{Path, PathBuf},
1304        sync::Arc,
1305        time::SystemTime,
1306    };
1307
1308    #[gpui::test]
1309    fn test_path_for_file(cx: &mut AppContext) {
1310        let file = TestFile {
1311            path: Path::new("").into(),
1312            full_path: PathBuf::from(""),
1313        };
1314        assert_eq!(path_for_file(&file, 0, false, cx), None);
1315    }
1316
1317    struct TestFile {
1318        path: Arc<Path>,
1319        full_path: PathBuf,
1320    }
1321
1322    impl language::File for TestFile {
1323        fn path(&self) -> &Arc<Path> {
1324            &self.path
1325        }
1326
1327        fn full_path(&self, _: &gpui::AppContext) -> PathBuf {
1328            self.full_path.clone()
1329        }
1330
1331        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1332            unimplemented!()
1333        }
1334
1335        fn mtime(&self) -> SystemTime {
1336            unimplemented!()
1337        }
1338
1339        fn file_name<'a>(&'a self, _: &'a gpui::AppContext) -> &'a std::ffi::OsStr {
1340            unimplemented!()
1341        }
1342
1343        fn worktree_id(&self) -> usize {
1344            0
1345        }
1346
1347        fn is_deleted(&self) -> bool {
1348            unimplemented!()
1349        }
1350
1351        fn as_any(&self) -> &dyn std::any::Any {
1352            unimplemented!()
1353        }
1354
1355        fn to_proto(&self) -> rpc::proto::File {
1356            unimplemented!()
1357        }
1358    }
1359}